import {
  DeleteOutlined,
  DoubleLeftOutlined,
  ExportOutlined,
  PlusOutlined,
} from '@ant-design/icons';
import ProTable, { ProColumns, ActionType } from '@ant-design/pro-table';
import { useRequest } from 'ahooks';
import { Button, FormInstance, Modal, Space, Switch, Tag } from 'antd';
import React, { useRef, useState } from 'react';
import { history, useLocation } from 'umi';
import Truly from '../../../components/Truly';
import { OPTIONS } from '../../../constants';
import { DictDataController } from '../../../services';
import { isFalse, isTrue } from '../../../utils/auth';
import EditForm from './EditForm';

const View: React.FC<unknown> = () => {
  const formRef = useRef<FormInstance<DictDataController.DictDataFields>>();
  const actionRef = useRef<ActionType>();
  const { query: urlQuerys } = useLocation() as any;
  const { dictType } = urlQuerys || {};
  const [formDictType, setFormDictType] =
    useState<DictDataController.DictDataFields['dictType']>('');
  const [query, setQuery] = useState<any>();

  const { data: dictTypeList } = useRequest(
    DictDataController.getDictTypeListApi,
  );

  const [selectRows, setSelectRows] = useState<
    DictDataController.DictDataFields[]
  >([]);

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

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

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

  const columns: ProColumns<DictDataController.DictDataFields>[] = [
    {
      title: '字典类型',
      dataIndex: 'dictType',
      hideInTable: true,
      valueType: 'select',
      initialValue: dictType,
      fieldProps: {
        showSearch: true,
        options: dictTypeList || [],
      },
    },
    {
      title: '字典编号',
      dataIndex: 'dictCode',
      hideInSearch: true,
      width: 240,
      ellipsis: true,
    },
    {
      title: '字典标签',
      dataIndex: 'dictLabel',
      width: 240,
      ellipsis: true,
    },
    {
      title: '字典键值',
      dataIndex: 'dictValue',
      hideInSearch: true,
      width: 240,
      ellipsis: true,
    },
    {
      title: '字典排序',
      dataIndex: 'dictSort',
      hideInSearch: true,
      width: 240,
      ellipsis: true,
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInTable: true,
      valueType: 'select',
      fieldProps: {
        options: OPTIONS.OPTIONS_STATUS,
      },
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInSearch: true,
      width: 240,
      ellipsis: true,
      render: (_, record) => {
        if (isTrue('sysSetting:dict:data:status:change')) {
          return (
            <Switch
              size="small"
              checked={Boolean(1 - Number(record.status))}
              onChange={async () => {
                const {
                  dictCode,
                  dictType,
                  dictLabel,
                  dictValue,
                  status: preStatus,
                } = record;
                const status = preStatus === '0' ? '1' : '0';
                await DictDataController.updateApi({
                  dictCode,
                  status,
                  dictType,
                  dictLabel,
                  dictValue,
                });
                actionRef.current?.reload();
              }}
            />
          );
        } else if (record.status === '0') {
          return <Tag color="blue">启用</Tag>;
        }
        return <Tag color="red">停用</Tag>;
      },
    },
    {
      title: '备注',
      dataIndex: 'remark',
      hideInSearch: true,
      width: 240,
      ellipsis: true,
    },
    {
      title: '创建时间',
      key: 'showTime',
      dataIndex: 'createTime',
      valueType: 'dateTime',
      hideInSearch: true,
      width: 240,
      ellipsis: true,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 120,
      fixed: 'right',
      hideInTable: isFalse(
        'sysSetting:dict:data:update',
        'sysSetting:dict:data:delete',
      ),
      render: (_, record) => (
        <Space>
          <Truly truly={isTrue('sysSetting:dict:data:update')}>
            <EditForm
              type="update"
              title="编辑字典"
              dictTypeList={dictTypeList || []}
              value={record}
              trigger={<a>编辑</a>}
              onOk={() => {
                actionRef.current?.reload();
              }}
            ></EditForm>
          </Truly>
          <Truly truly={isTrue('sysSetting:dict:data:delete')}>
            <a style={{ color: '#FF4D4F' }} onClick={() => onDelete(record)}>
              删除
            </a>
          </Truly>
        </Space>
      ),
    },
  ];

  return (
    <ProTable<DictDataController.DictDataFields>
      rowKey={'dictCode'}
      formRef={formRef}
      actionRef={actionRef}
      search={{ span: 6 }}
      rowSelection={{
        fixed: true,
        onChange: (selectKeys, selectRows) => setSelectRows(selectRows),
      }}
      tableAlertRender={false}
      tableAlertOptionRender={false}
      toolBarRender={() => [
        <Button
          type="primary"
          key="back"
          icon={<DoubleLeftOutlined />}
          onClick={() => {
            history.go(-1);
          }}
        >
          返回上级
        </Button>,
        <Truly key="add" truly={isTrue('sysSetting:dict:data:add')}>
          <EditForm
            type="add"
            title="新增字典"
            dictType={formDictType}
            dictTypeList={dictTypeList || []}
            trigger={
              <Button type="primary" icon={<PlusOutlined />}>
                新增
              </Button>
            }
            onOpen={() => {
              setFormDictType(formRef.current?.getFieldValue('dictType'));
            }}
            onOk={() => {
              actionRef.current?.reload();
            }}
          ></EditForm>
        </Truly>,
        <Truly key="export" truly={isTrue('sysSetting:dict:data:export')}>
          <Button type="primary" icon={<ExportOutlined />} onClick={onExport}>
            导出
          </Button>
        </Truly>,
        <Truly key="delete" truly={isTrue('sysSetting:dict:data:delete')}>
          <Button
            type="primary"
            danger
            disabled={selectRows.length === 0}
            icon={<DeleteOutlined />}
            onClick={() => onBatchDelete()}
          >
            批量删除
          </Button>
        </Truly>,
      ]}
      columns={columns}
      pagination={{
        defaultPageSize: 10,
        showQuickJumper: true,
        showSizeChanger: true,
        hideOnSinglePage: true,
      }}
      scroll={{ x: 0 }}
      request={async (params) => {
        const { current: pageNum, pageSize, ...rest } = params;
        const { total = 0, data = [] } = await DictDataController.getListApi({
          ...rest,
          pageNum,
          pageSize,
        });
        setQuery(rest);
        actionRef.current?.clearSelected?.();
        return {
          data,
          total,
        };
      }}
    />
  );
};

export default View;
