import { PlusOutlined, SwapOutlined } from '@ant-design/icons';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import { useRequest } from 'ahooks';
import { Button, Modal, Select, Space, Switch, Tag } from 'antd';
import React, { useRef, useState } from 'react';
import Icon, { IconImg } from '../../components/Icon';
import Truly from '../../components/Truly';
import { OPTIONS } from '../../constants';
import { CommonController, MenuController, types } from '../../services';
import { isFalse, isTrue } from '../../utils/auth';
import { decodeHtml, isSvg } from '../../utils/html';
import { getTreeFromList } from '../../utils/tree';
import EditForm from './EditForm';

const User: React.FC<unknown> = () => {
  const actionRef = useRef<ActionType>();
  const [tableList, setTableList] = useState<MenuController.MenuFields[]>([]);
  const [selectedAppId, setSelectedAppId] =
    useState<types.AppFields['appId']>();
  const [expandedRowKeys, setExpandedRowKeys] = useState<string[]>([]);

  const { data: appList } = useRequest(CommonController.getAppSelectApi, {
    onSuccess: (appList) => {
      const [{ value = '' } = {}] = appList || [];
      setSelectedAppId(value);
      actionRef.current?.reload();
    },
  });

  const onDelete = async (record: MenuController.MenuFields) => {
    Modal.confirm({
      title: '操作提示',
      content: `是否确认删除菜单名称为"${record.menuName}"的数据项？`,
      maskClosable: true,
      onOk: async () => {
        await MenuController.delApi(record.menuId);
        actionRef.current?.reload();
      },
      okText: '确定',
      cancelText: '取消',
    });
  };

  const onExpand = () => {
    if (expandedRowKeys.length === 0) {
      const newExpandedRowKeys = tableList.map((item) => item.menuId || '');
      setExpandedRowKeys(newExpandedRowKeys);
    } else {
      setExpandedRowKeys([]);
    }
  };

  const columns: ProColumns<MenuController.MenuFields>[] = [
    {
      title: '菜单名称',
      dataIndex: 'menuName',
      width: 300,
    },

    {
      title: '排序',
      dataIndex: 'orderNum',
      hideInSearch: true,
      width: 120,
      ellipsis: true,
    },
    {
      title: '菜单类型',
      dataIndex: 'menuType',
      valueType: 'select',
      hideInSearch: true,
      width: 120,
      ellipsis: true,
      request: async () => {
        return OPTIONS.OPTIONS_MENU_TYPE;
      },
    },
    {
      title: '图标',
      dataIndex: 'icon',
      hideInSearch: true,
      width: 120,
      ellipsis: true,
      render: (_, record) => {
        const icon = decodeHtml(record.icon || '');
        return (
          <Truly
            truly={isSvg(icon)}
            falsyRender={<IconImg url={icon} width={16}></IconImg>}
          >
            <Icon svg={icon} size={16}></Icon>
            <span style={{ color: '#999', fontSize: 12, marginLeft: 8 }}>
              svg
            </span>
          </Truly>
        );
      },
    },
    {
      title: '路由地址',
      dataIndex: 'path',
      hideInSearch: true,
      width: 360,
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      search: false,
      width: 120,
      ellipsis: true,
      render: (_, record) => {
        if (isTrue('administration:menu:status:change')) {
          return (
            <Switch
              size="small"
              checked={Boolean(2 - Number(record.status))}
              onChange={async () => {
                const { status: preStatus } = record;
                const status = preStatus === '1' ? '2' : '1';
                await MenuController.updateApi({ ...record, status });
                actionRef.current?.reload();
              }}
            />
          );
        } else if (record.status === '1') {
          return <Tag color="blue">启用</Tag>;
        }
        return <Tag color="red">停用</Tag>;
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInTable: true,
      valueType: 'select',
      request: async () => {
        return OPTIONS.OPTIONS_AVAILABLE;
      },
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInSearch: true,
      width: 240,
      ellipsis: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      hideInTable: isFalse(
        'administration:menu:add',
        'administration:menu:edit',
        'administration:menu:delete',
      ),
      width: 160,
      fixed: 'right',
      render: (_, record) => (
        <Space>
          <Truly
            truly={record.menuType !== 'F' && isTrue('administration:menu:add')}
          >
            <EditForm
              key="add"
              type="add-child"
              title="新增菜单"
              appList={appList || []}
              appId={selectedAppId}
              initailParentValues={record}
              onOk={() => {
                actionRef.current?.reload();
              }}
            >
              <a>新增</a>
            </EditForm>
          </Truly>
          <Truly truly={isTrue('administration:menu:edit')}>
            <EditForm
              key="update"
              type="update"
              title="编辑菜单"
              initialValues={record}
              appList={appList || []}
              tableList={tableList || []}
              onOk={() => {
                actionRef.current?.reload();
              }}
            >
              <a>编辑</a>
            </EditForm>
          </Truly>
          <Truly
            truly={
              (record.children || []).length === 0 &&
              isTrue('administration:menu:delete')
            }
          >
            <a onClick={() => onDelete(record)} style={{ color: '#FF4D4F' }}>
              删除
            </a>
          </Truly>
        </Space>
      ),
    },
  ];

  return (
    <ProTable<MenuController.MenuFields>
      rowKey={'menuId'}
      actionRef={actionRef}
      search={false}
      toolBarRender={() => [
        <Truly key="add" truly={isTrue('administration:menu:add')}>
          <EditForm
            type="add"
            title="新增菜单"
            appList={appList || []}
            appId={selectedAppId}
            onOk={() => {
              actionRef.current?.reload();
            }}
          >
            <Button type="primary" icon={<PlusOutlined />}>
              新增
            </Button>
          </EditForm>
        </Truly>,
        <Button key="expand" icon={<SwapOutlined />} onClick={onExpand}>
          展开/折叠
        </Button>,
      ]}
      columns={columns}
      pagination={false}
      request={async () => {
        if (!selectedAppId) return { data: [] };
        const { data: preMenuList = [] } = await MenuController.getListApi({
          appId: selectedAppId,
        });
        const menuList = preMenuList.map((menu) => {
          // eslint-disable-next-line @typescript-eslint/no-unused-vars
          const { children, ...rest } = menu || {};
          return rest;
        });
        setTableList(menuList);
        const data = getTreeFromList<MenuController.MenuFields>(menuList, {
          idKey: 'menuId',
          parentIdKey: 'parentId',
        });
        return {
          data,
        };
      }}
      expandable={{
        expandRowByClick: false,
        expandedRowKeys,
        indentSize: 36,
        onExpandedRowsChange(rows: any) {
          setExpandedRowKeys(rows);
        },
      }}
      scroll={{ x: 0 }}
      headerTitle={
        <Select
          placeholder="请选择应用名称"
          style={{ width: 280 }}
          options={appList || []}
          value={selectedAppId}
          showSearch={true}
          onChange={(appId) => {
            setSelectedAppId(appId);
            actionRef.current?.reload();
          }}
          filterOption={(input, option) => {
            const { label } = option || {};
            return (label || '').includes(input);
          }}
        />
      }
    />
  );
};

export default User;
