import { ImportOutlined, PlusOutlined } from '@ant-design/icons';
import { ParamsType } from '@ant-design/pro-components';
import BaseTable, { ActionType, ProColumns } from '../../components/BaseTable';
import { useRequest, useSize } from 'ahooks';
import { Button, Modal, Space, Tag, message } from 'antd';
import React, { useRef, useState } from 'react';
import FooterDiv from '../../components/FooterDiv';
import Truly from '../../components/Truly';
import { OPTIONS_APPROVAL } from '../../constants/options';
import { CommonController, DeptController } from '../../services';
import { isSomeTrue, isTrue } from '../../utils/auth';
import BatchForm from './components/BatchForm';
import EditForm from './components/EditForm';
import ImportForm from './components/ImportForm';

const User: React.FC<unknown> = () => {
  const actionRef = useRef<ActionType>();
  const widthRef = useRef(null);
  const size = useSize(widthRef);
  const [selectedRows, setSelectedRows] = useState<DeptController.DeptFields[]>(
    [],
  );
  /**
   * @name 获取列表数据
   */
  async function getBaseData(params: ParamsType) {
    const { current: pageNum } = params;
    const PegParams = {
      ...params,
      pageNum,
    };
    const res = await DeptController.getListApi(PegParams);
    const { total, data } = res || {};
    actionRef.current?.clearSelected?.();
    return {
      data,
      total,
    };
  }

  /**
   * @name 批量启用/批量停用/批量审批/批量驳回
   * @param selectedRows
   * @param docStatus
   */
  const onBatch = (
    selectedRows: DeptController.DeptFields[],
    deptStatus: string,
    optionName: string,
  ) => {
    const { label } =
      OPTIONS_APPROVAL.find((item) => item.value !== deptStatus) || {};
    const flag = selectedRows.some((item) => item.deptStatus === deptStatus);
    if (flag) {
      return message.warning(`请勾选状态为${label}的数据`);
    }
    Modal.confirm({
      content: `是否确认执行批量${optionName}操作？`,
      maskClosable: true,
      onOk: async () => {
        const depts = selectedRows.map(({ orgCode, insDeptCode }) => {
          return { orgCode, deptCode: insDeptCode };
        });
        await DeptController.batchApi({ depts, deptStatus });
        actionRef.current?.reload();
      },
      okText: '确定',
      cancelText: '取消',
    });
  };

  /**
   * @name 批量删除
   * @param selectedRows
   */
  const onDel = (selectedRows: DeptController.DeptFields[]) => {
    Modal.confirm({
      content: `是否确认执行批量删除操作？`,
      maskClosable: true,
      onOk: async () => {
        const depts = selectedRows.map(({ orgCode, insDeptCode }) => {
          return { orgCode, deptCode: insDeptCode };
        });
        await DeptController.delApi(depts);
        actionRef.current?.reload();
      },
      okText: '确定',
      cancelText: '取消',
    });
  };

  const { data: orgList } = useRequest(CommonController.getOrgOptionsApi);

  const columns: ProColumns<DeptController.DeptFields>[] = [
    {
      title: '机构名称',
      dataIndex: 'orgName',
      hideInSearch: true,
      width: 300,
      ellipsis: true,
    },
    {
      title: '机构名称',
      dataIndex: 'orgCode',
      hideInTable: true,
      valueType: 'select',
      fieldProps: {
        showSearch: true,
        options: orgList,
      },
    },
    {
      title: '科室名称',
      dataIndex: 'deptName',
    },
    {
      title: '内部代码',
      dataIndex: 'insDeptCode',
      hideInSearch: true,
    },
    {
      title: '标准代码',
      dataIndex: 'staDeptCode',
      hideInSearch: true,
    },
    {
      title: '下级科室数',
      dataIndex: 'subCounts',
      hideInSearch: true,
    },
    {
      title: '联系电话',
      dataIndex: 'deptPhone',
      hideInSearch: true,
    },
    {
      title: '病区名称',
      dataIndex: 'wardName',
      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'deptStatus',
      valueType: 'select',
      hideInTable: true,
      request: async () => OPTIONS_APPROVAL,
    },
    {
      title: '状态',
      dataIndex: 'deptStatus',
      valueType: 'select',
      hideInSearch: true,
      render: (text, record) => {
        const { label, color } =
          OPTIONS_APPROVAL.find((item) => record.deptStatus === item.value) ||
          {};
        return <Tag color={color ? color : 'orange'}>{label || '待审核'}</Tag>;
      },
    },
    {
      title: '版本号',
      dataIndex: 'version',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <Space>
          <EditForm
            title="查看科室"
            type="view"
            initValues={record}
            onSubmit={() => {}}
            trigger={<a>查看</a>}
          ></EditForm>
          <Truly truly={isTrue('masterdata:dept:edit')}>
            <EditForm
              title="编辑科室"
              type="update"
              initValues={record}
              onSubmit={() => actionRef.current?.reload()}
              trigger={<a>编辑</a>}
            ></EditForm>
          </Truly>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ width: '100%' }} ref={widthRef}>
      <BaseTable<DeptController.DeptFields>
        rowKey={(record) => `${record.orgCode} + ${record.insDeptCode}`}
        actionRef={actionRef}
        search={{ span: 6 }}
        rowSelection={{
          onChange(keys, selectedRows) {
            setSelectedRows(selectedRows);
          },
        }}
        style={{ marginBottom: 50 }}
        tableAlertRender={false}
        toolBarRender={() => [
          <Truly truly={isTrue('masterdata:dept:add')} key="add">
            <EditForm
              title="新增科室"
              type="add"
              onSubmit={() => actionRef.current?.reload()}
              trigger={
                <Button key="add" type="primary" icon={<PlusOutlined />}>
                  新增
                </Button>
              }
            ></EditForm>
          </Truly>,
          <Truly truly={isTrue('masterdata:dept:import')} key="import">
            <ImportForm
              key="import"
              title="导入科室信息"
              trigger={
                <Button type="primary" icon={<ImportOutlined />}>
                  导入
                </Button>
              }
              onSubmit={() => {
                actionRef.current?.reload();
              }}
            />
          </Truly>,
        ]}
        columns={columns}
        pagination={{
          defaultPageSize: 10,
          showQuickJumper: true,
          showSizeChanger: true,
          hideOnSinglePage: true,
        }}
        request={(params) => getBaseData(params)}
      />

      <Truly
        truly={isSomeTrue(
          'masterdata:dept:enable',
          'masterdata:dept:deactivate',
          'masterdata:dept:approval',
          'masterdata:dept:del',
        )}
      >
        <FooterDiv size={size?.width} selectedRowsNumber={selectedRows.length}>
          <Space>
            <Truly truly={isTrue('masterdata:dept:enable')}>
              <Button
                type="primary"
                key="enable"
                disabled={selectedRows.length <= 0}
                onClick={() => onBatch(selectedRows, '1', '启用')}
              >
                批量启用
              </Button>
            </Truly>
            <Truly truly={isTrue('masterdata:dept:deactivate')}>
              <Button
                key="deactivate"
                danger
                disabled={selectedRows.length <= 0}
                onClick={() => onBatch(selectedRows, '2', '停用')}
              >
                批量停用
              </Button>
            </Truly>
            <Truly truly={isTrue('masterdata:dept:approval')}>
              <BatchForm
                title="批量审批"
                key="approval"
                selectedRows={selectedRows}
                trigger={
                  <Button type="primary" disabled={selectedRows.length <= 0}>
                    批量审批
                  </Button>
                }
                onSubmit={() => {
                  actionRef.current?.reload();
                }}
              />
            </Truly>
            <Truly truly={isTrue('masterdata:dept:del')}>
              <Button
                type="primary"
                key="del"
                danger
                disabled={selectedRows.length <= 0}
                onClick={() => onDel(selectedRows)}
              >
                批量删除
              </Button>
            </Truly>
          </Space>
        </FooterDiv>
      </Truly>
    </div>
  );
};

export default User;
