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

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

  const [selectRows, setSelectRows] = useState<ConfigController.ConfigFields[]>(
    [],
  );
  const { data: appList } = useRequest(CommonController.getAppSelectApi);

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

  const onBatchDelete = () => {
    Modal.confirm({
      title: '操作提示',
      content: `是否确认批量删除操作？只会删除系统内置为"否"的数据项。`,
      maskClosable: true,
      onOk: async () => {
        const keys = selectRows
          .filter((item) => item.configType === 'N')
          .map((item) => item.configId);
        await ConfigController.delApi(keys);
        actionRef.current?.reload();
      },
      okText: '确定',
      cancelText: '取消',
    });
  };

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

  const columns: ProColumns<ConfigController.ConfigFields>[] = [
    {
      title: '参数主键',
      dataIndex: 'configId',
      hideInSearch: true,
      width: 240,
      ellipsis: true,
    },
    {
      title: '应用名称',
      dataIndex: 'appId',
      valueType: 'select',
      hideInSearch: true,
      fieldProps: {
        options: appList || [],
      },
      width: 240,
      ellipsis: true,
    },
    {
      title: '参数名称',
      dataIndex: 'configName',
      width: 240,
      ellipsis: true,
    },
    {
      title: '参数键名',
      dataIndex: 'configKey',
      width: 240,
      ellipsis: true,
    },
    {
      title: '参数键值',
      dataIndex: 'configValue',
      hideInSearch: true,
      width: 240,
      ellipsis: true,
    },
    {
      title: '系统内置',
      dataIndex: 'configType',
      valueType: 'select',
      fieldProps: {
        options: OPTIONS.OPTIONS_CONFIG,
      },
      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:config:update',
        'sysSetting:config:delete',
      ),
      render: (_, record) => (
        <Space>
          <Truly truly={isTrue('sysSetting:config:update')}>
            <EditForm
              type="update"
              title="编辑参数"
              appList={appList || []}
              value={record}
              trigger={<a>编辑</a>}
              onOk={() => {
                actionRef.current?.reload();
              }}
            ></EditForm>
          </Truly>
          <Truly
            truly={
              isTrue('sysSetting:config:delete') && record.configType === 'N'
            }
          >
            <a onClick={() => onDelete(record)} style={{ color: '#FF4D4F' }}>
              删除
            </a>
          </Truly>
        </Space>
      ),
    },
  ];

  return (
    <ProTable<ConfigController.ConfigFields>
      rowKey={'configId'}
      formRef={formRef}
      actionRef={actionRef}
      search={{ span: 6 }}
      rowSelection={{
        onChange: (selectKeys, selectRows) => setSelectRows(selectRows),
      }}
      tableAlertRender={false}
      tableAlertOptionRender={false}
      toolBarRender={() => [
        <Truly key="add" truly={isTrue('sysSetting:config:add')}>
          <EditForm
            type="add"
            title="新增参数"
            appList={appList || []}
            trigger={
              <Button type="primary" icon={<PlusOutlined />}>
                新增
              </Button>
            }
            onOk={() => {
              actionRef.current?.reload();
            }}
          ></EditForm>
        </Truly>,
        <Truly key="export" truly={isTrue('sysSetting:config:export')}>
          <Button type="primary" icon={<ExportOutlined />} onClick={onExport}>
            导出
          </Button>
        </Truly>,
        <Truly key="delete" truly={isTrue('sysSetting:config:delete')}>
          <Button
            type="primary"
            danger
            icon={<DeleteOutlined />}
            onClick={() => onBatchDelete()}
            disabled={
              selectRows.filter((item) => item.configType === 'N').length === 0
            }
          >
            批量删除
          </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 ConfigController.getListApi({
          ...rest,
          pageNum,
          pageSize,
        });
        setQuery(rest);
        actionRef.current?.clearSelected?.();
        return {
          data,
          total,
        };
      }}
    />
  );
};

export default User;
