import BaseTable, { ActionType, ProColumns } from '../../components/BaseTable';
import { ImportOutlined, PlusOutlined } from '@ant-design/icons';
import { ParamsType } from '@ant-design/pro-components';
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,
  OPTIONS_ORG_EQUAL_DEGREE,
  OPTIONS_ORG_LEVEL,
} from '../../constants/options';
import { CommonController, OrgController } 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<OrgController.OrgFields[]>(
    [],
  );
  /**
   * @name 批量启用/批量停用
   * @param selectedRows
   * @param orgStatus
   * @param optionName
   */
  const onBatch = (
    selectedRows: OrgController.OrgFields[],
    orgStatus: string,
    optionName: string,
  ) => {
    const { label } =
      OPTIONS_APPROVAL.find((item) => item.value !== orgStatus) || {};
    const flag = selectedRows.some((item) => item.orgStatus === orgStatus);
    if (flag) {
      return message.warning(`请勾选状态为${label}的数据`);
    }
    Modal.confirm({
      content: `是否确认执行批量${optionName}操作？`,
      maskClosable: true,
      onOk: async () => {
        const orgCodes = (selectedRows || [])
          .map(({ orgCode }) => {
            return orgCode;
          })
          .join(',');
        await OrgController.batchApi({ orgCodes, orgStatus });
        actionRef.current?.reload();
      },
      okText: '确定',
      cancelText: '取消',
    });
  };

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

  /**
   * @name 获取列表数据
   */
  async function getBaseData(params: ParamsType) {
    const { current: pageNum } = params;
    const pageParams = {
      pageNum,
      ...params,
    };
    const res = await OrgController.getListApi(pageParams);
    const { total, data } = res || {};
    actionRef.current?.clearSelected?.();
    return {
      data,
      total,
    };
  }
  const { data: orgList } = useRequest(() =>
    CommonController.getOrgOptionsApi('all'),
  );

  const columns: ProColumns<OrgController.OrgFields>[] = [
    {
      title: '机构名称',
      dataIndex: 'orgName',
      hideInSearch: true,
      width: 200,
      ellipsis: true,
    },
    {
      title: '机构名称',
      dataIndex: 'orgCode',
      hideInTable: true,
      valueType: 'select',
      fieldProps: {
        showSearch: true,
        options: orgList,
      },
    },
    {
      title: '机构联系电话',
      dataIndex: 'orgPhone',
      hideInSearch: true,
    },
    {
      title: '等级',
      dataIndex: 'orgLevel',
      valueType: 'select',
      request: async () => OPTIONS_ORG_LEVEL,
    },
    {
      title: '等次',
      dataIndex: 'orgDegree',
      valueType: 'select',
      request: async () => OPTIONS_ORG_EQUAL_DEGREE,
    },
    {
      title: '医护人员',
      dataIndex: 'docCounts',
      hideInSearch: true,
    },
    {
      title: '科室',
      dataIndex: 'deptCounts',
      hideInSearch: true,
    },
    {
      title: '床位',
      dataIndex: 'bedCounts',
      hideInSearch: true,
    },
    {
      title: '状态',
      dataIndex: 'orgStatus',
      valueType: 'select',
      hideInTable: true,
      request: async () => OPTIONS_APPROVAL,
    },
    {
      title: '状态',
      dataIndex: 'orgStatus',
      valueType: 'select',
      hideInSearch: true,
      render: (text, record) => {
        const { label, color } =
          OPTIONS_APPROVAL.find((item) => record.orgStatus === item.value) ||
          {};
        return <Tag color={color}>{label || '待审核'}</Tag>;
      },
    },
    {
      title: '版本号',
      dataIndex: 'version',
      // request: async () => OPTIONS_ORG_STATUS,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => (
        <Space>
          <EditForm
            key="view"
            type="view"
            title="查看详情"
            value={record}
            flag={false}
            trigger={<a>查看</a>}
            // onSubmit={() => {
            //   actionRef.current?.reload();
            // }}
          />
          <Truly truly={isTrue('masterdata:org:edit')}>
            <EditForm
              key="edit"
              type="update"
              title="编辑机构"
              value={record}
              trigger={<a>编辑</a>}
              onSubmit={() => {
                actionRef.current?.reload();
              }}
            />
          </Truly>
        </Space>
      ),
    },
  ];

  return (
    <div style={{ width: '100%' }} ref={widthRef}>
      <BaseTable<OrgController.OrgFields>
        rowKey={'orgCode'}
        actionRef={actionRef}
        search={{ span: 6 }}
        rowSelection={{
          onChange(keys, selectedRows) {
            setSelectedRows(selectedRows);
          },
        }}
        style={{ marginBottom: 50 }}
        tableAlertRender={false}
        toolBarRender={() => [
          <Truly truly={isTrue('masterdata:org:add')} key="add">
            <EditForm
              key="add"
              type="add"
              title="新增机构"
              trigger={
                <Button type="primary" icon={<PlusOutlined />}>
                  新增
                </Button>
              }
              onSubmit={() => {
                actionRef.current?.reload();
              }}
            />
          </Truly>,
          <Truly truly={isTrue('masterdata:org: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:org:enable',
          'masterdata:org:deactivate',
          'masterdata:org:approval',
          'masterdata:org:del',
        )}
      >
        <FooterDiv size={size?.width} selectedRowsNumber={selectedRows.length}>
          <Space>
            <Truly truly={isTrue('masterdata:org:enable')}>
              <Button
                type="primary"
                key="enable"
                disabled={selectedRows.length <= 0}
                onClick={() => onBatch(selectedRows, '1', '启用')}
              >
                批量启用
              </Button>
            </Truly>
            <Truly truly={isTrue('masterdata:org:deactivate')}>
              <Button
                key="deactivate"
                danger
                disabled={selectedRows.length <= 0}
                onClick={() => onBatch(selectedRows, '2', '停用')}
              >
                批量停用
              </Button>
            </Truly>
            <Truly truly={isTrue('masterdata:org: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:org:del')}>
              <Button
                type="primary"
                key="del"
                danger
                disabled={selectedRows.length <= 0}
                onClick={() => onDel(selectedRows)}
              >
                批量删除
              </Button>
            </Truly>
          </Space>
        </FooterDiv>
      </Truly>
    </div>
  );
};

export default User;
