import {
  DeleteOutlined,
  ExportOutlined,
  ImportOutlined,
  PlusOutlined,
  RedoOutlined,
} from '@ant-design/icons';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import { Button, FormInstance, Modal, Space, Switch, Tag } from 'antd';
import React, { useRef, useState } from 'react';
import { Link } from 'umi';
import Truly from '../../components/Truly';
import { OPTIONS } from '../../constants';
import { DictDataController, DictTypeController } from '../../services';
import { isFalse, isTrue } from '../../utils/auth';
import EditForm from './EditForm';
import ImportModal from './ImportModal';
import { pathHolder } from '../../utils/route';

const View: React.FC<unknown> = () => {
  const formRef = useRef<FormInstance<DictDataController.DictTypeFields>>();
  const actionRef = useRef<ActionType>();
  const [query, setQuery] = useState<any>();
  const [selectRows, setSelectRows] = useState<
    DictDataController.DictTypeFields[]
  >([]);

  const onDelete = (record: DictDataController.DictTypeFields) => {
    Modal.confirm({
      title: '操作提示',
      content: `是否确认删除字典名称为"${record.dictName}"的数据项？`,
      maskClosable: true,
      onOk: async () => {
        await DictTypeController.delApi([record.dictId]);
        actionRef.current?.reload();
      },
      okText: '确定',
      cancelText: '取消',
    });
  };

  const onBatchDelete = () => {
    Modal.confirm({
      title: '操作提示',
      content: `是否确认批量删除操作？`,
      maskClosable: true,
      onOk: async () => {
        const keys = selectRows.map((item) => item.dictId);
        await DictTypeController.delApi(keys);
        actionRef.current?.reload();
      },
      okText: '确定',
      cancelText: '取消',
    });
  };

  const onRefreshCache = async () => {
    await DictTypeController.refreshCacheApi();
    actionRef.current?.reload();
  };

  const onExport = async () => {
    Modal.confirm({
      title: '操作提示',
      content: '是否确认导出全部数据？',
      maskClosable: true,
      onOk: async () => {
        await DictTypeController.exportExcelApi({ ...query });
      },
      okText: '确定',
      cancelText: '取消',
    });
  };

  const columns: ProColumns<DictDataController.DictTypeFields>[] = [
    {
      title: '字典名称',
      dataIndex: 'dictName',
      width: 240,
      ellipsis: true,
    },
    {
      title: '字典类型',
      dataIndex: 'dictType',
      width: 240,
      ellipsis: true,
      render: (text, record) => {
        return (
          <Link
            to={`${pathHolder('/sysSetting/dict/data')}?dictType=${
              record.dictType
            }`}
          >
            {record.dictType}
          </Link>
        );
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInTable: true,
      valueType: 'select',
      fieldProps: {
        options: OPTIONS.OPTIONS_STATUS,
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInSearch: true,
      render: (_, record) => {
        if (isTrue('sysSetting:dict:status:change')) {
          return (
            <Switch
              size="small"
              checked={Boolean(1 - Number(record.status))}
              onChange={async () => {
                const {
                  dictId,
                  dictType,
                  dictName,
                  status: preStatus,
                } = record;
                const status = preStatus === '0' ? '1' : '0';
                await DictTypeController.updateApi({
                  dictId,
                  status,
                  dictType,
                  dictName,
                });
                actionRef.current?.reload();
              }}
            />
          );
        } else if (record.status === '0') {
          return <Tag color="blue">启用</Tag>;
        }
        return <Tag color="red">停用</Tag>;
      },
      width: 240,
      ellipsis: true,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      hideInSearch: true,
      width: 240,
      ellipsis: true,
    },
    {
      title: '创建时间',
      key: 'showTime',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInSearch: true,
      width: 240,
      ellipsis: true,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      valueType: 'dateRange',
      hideInTable: true,
      search: {
        transform: (value) => {
          return {
            beginTime: value[0],
            endTime: value[1],
          };
        },
      },
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 120,
      fixed: 'right',
      hideInTable: isFalse('sysSetting:dict:update', 'sysSetting:dict:delete'),
      render: (_, record) => (
        <Space>
          <Truly truly={isTrue('sysSetting:dict:update')}>
            <EditForm
              type="update"
              title="编辑字典类型"
              value={record}
              trigger={<a>编辑</a>}
              onOk={() => {
                actionRef.current?.reload();
              }}
            ></EditForm>
          </Truly>
          <Truly truly={isTrue('sysSetting:dict:delete')}>
            <a onClick={() => onDelete(record)} style={{ color: '#FF4D4F' }}>
              删除
            </a>
          </Truly>
        </Space>
      ),
    },
  ];

  return (
    <ProTable<DictDataController.DictTypeFields>
      rowKey={'dictId'}
      actionRef={actionRef}
      formRef={formRef}
      search={{ span: 6 }}
      rowSelection={{
        fixed: true,
        onChange: (selectKeys, selectRows) => setSelectRows(selectRows),
      }}
      tableAlertRender={false}
      tableAlertOptionRender={false}
      toolBarRender={() => [
        <Truly key="add" truly={isTrue('sysSetting:dict:add')}>
          <EditForm
            type="add"
            title="新增字典类型"
            trigger={
              <Button type="primary" icon={<PlusOutlined />}>
                新增
              </Button>
            }
            onOk={() => {
              actionRef.current?.reload();
            }}
          ></EditForm>
        </Truly>,
        <Truly key="export" truly={isTrue('sysSetting:dict:cache')}>
          <Button
            type="primary"
            icon={<RedoOutlined />}
            onClick={onRefreshCache}
          >
            刷新缓存
          </Button>
        </Truly>,
        <Truly key="export" truly={isTrue('sysSetting:dict:export')}>
          <Button type="primary" icon={<ExportOutlined />} onClick={onExport}>
            导出
          </Button>
        </Truly>,
        <Truly key="import" truly={isTrue('sysSetting:dict:import')}>
          <ImportModal
            reloadTable={actionRef.current?.reload}
            trigger={
              <Button type="primary" icon={<ImportOutlined />}>
                导入
              </Button>
            }
          />
        </Truly>,
        <Truly key="delete" truly={isTrue('sysSetting:dict:delete')}>
          <Button
            type="primary"
            danger
            disabled={selectRows.length === 0}
            icon={<DeleteOutlined />}
            onClick={() => onBatchDelete()}
          >
            批量删除
          </Button>
        </Truly>,
      ]}
      columns={columns}
      pagination={{
        showQuickJumper: true,
        showSizeChanger: true,
        hideOnSinglePage: true,
        defaultCurrent: 1,
        defaultPageSize: 10,
      }}
      scroll={{ x: 0 }}
      request={async (params) => {
        const { current: pageNum, pageSize, ...rest } = params;
        const querys = {
          ...rest,
          pageNum,
          pageSize,
        };
        setQuery(rest);
        const { total = 0, data = [] } = await DictTypeController.getListApi(
          querys,
        );
        actionRef.current?.clearSelected?.();
        return {
          data,
          total,
        };
      }}
    />
  );
};

export default View;
