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_BATCH,
  OPTIONS_SEX_COMPLETE,
} from '../../constants/options';
import { CommonController, DoctorController } from '../../services';
import { isSomeTrue, isTrue } from '../../utils/auth';
import BatchForm from './components/BatchForm';
import EditForm from './components/EditForm';
import EditLicenseForm from './components/EditLicenseForm';
import ImportForm from './components/ImportForm';

const Doctor: React.FC<unknown> = () => {
  const actionRef = useRef<ActionType>();
  const widthRef = useRef(null);
  const size = useSize(widthRef);
  const [selectedRows, setSelectedRows] = useState<
    DoctorController.DoctorFields[]
  >([]);

  const { data: orgList } = useRequest(CommonController.getOrgOptionsApi);
  const columns: ProColumns<DoctorController.DoctorFields>[] = [
    {
      title: '机构名称',
      dataIndex: 'orgCode',
      hideInTable: true,
      valueType: 'select',
      fieldProps: {
        options: orgList || [],
        showSearch: true,
      },
    },
    {
      title: '姓名',
      dataIndex: 'name',
    },
    {
      title: '性别',
      dataIndex: 'sexCode',
      hideInSearch: true,
      render: (text, record) => {
        const { label } =
          OPTIONS_SEX_COMPLETE.find((item) => item.value === record.sexCode) ||
          {};
        return label || '-';
      },
    },
    {
      title: '出生日期',
      dataIndex: 'birthDate',
      hideInSearch: true,
    },
    {
      title: '执业点位',
      dataIndex: 'jobCount',
      hideInSearch: true,
      render: (_, record) => {
        return (
          <Truly
            truly={isTrue('masterdata:doctor:licence')}
            falsyRender={<span>{record.jobCount}</span>}
          >
            <EditLicenseForm
              orgList={orgList || []}
              values={record}
              key="licence"
              trigger={
                <Button type="link" style={{ padding: 4 }}>
                  {record.jobCount}
                </Button>
              }
              onSubmit={() => {
                actionRef.current?.reload();
              }}
            />
          </Truly>
        );
      },
    },
    {
      title: '身份证件号',
      dataIndex: 'idno',
    },
    {
      title: '状态',
      dataIndex: 'docStatus',
      valueType: 'select',
      hideInTable: true,
      request: async () => OPTIONS_APPROVAL,
    },
    {
      title: '状态',
      dataIndex: 'docStatus',
      hideInSearch: true,
      render: (_, record) => {
        const { label, color } =
          OPTIONS_APPROVAL.find((item) => item.value === record.docStatus) ||
          {};
        if (label) {
          return <Tag color={color}>{label || ''}</Tag>;
        }
        return '-';
      },
    },
    {
      title: '版本号',
      dataIndex: 'version',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 300,
      render: (_, record) => (
        <Space>
          <EditForm
            title="查看医护信息"
            type="view"
            values={record}
            trigger={<a key="view">查看</a>}
          />
          <Truly truly={isTrue('masterdata:doctor:edit')}>
            <EditForm
              title="编辑医护信息"
              type="update"
              key="edit"
              values={record}
              trigger={<a>编辑</a>}
              onSubmit={() => {
                actionRef.current?.reload();
              }}
            />
          </Truly>
          <Truly truly={isTrue('masterdata:doctor:licence')}>
            <EditLicenseForm
              values={record}
              key="licence"
              orgList={orgList || []}
              trigger={<a>新增执业执照</a>}
              onSubmit={() => {
                actionRef.current?.reload();
              }}
            />
          </Truly>
        </Space>
      ),
    },
  ];

  /**
   * @name 批量启用/批量停用/批量审批/批量驳回
   * @param selectedRows
   * @param docStatus
   */
  const onBatch = (
    selectedRows: DoctorController.DoctorFields[],
    docStatus: string,
  ) => {
    if (docStatus === '1') {
      const isCancel = selectedRows.some((item) => item.docStatus !== '2');
      if (isCancel) {
        return message.warning('请勾选状态为已停用的数据！');
      }
    } else if (docStatus === '2') {
      const isCancel = selectedRows.some((item) => item.docStatus !== '1');
      if (isCancel) {
        return message.warning('请勾选状态为已启用的数据！');
      }
    }
    const { label } =
      OPTIONS_BATCH.find((item) => item.value === docStatus) || {};
    Modal.confirm({
      content: `是否确认执行批量${label}操作？`,
      maskClosable: true,
      onOk: async () => {
        const docCodes = selectedRows.map((item) => item.uuid).join(',');
        await DoctorController.batchApi({ docCodes, docStatus });
        actionRef.current?.reload();
      },
      okText: '确定',
      cancelText: '取消',
    });
  };

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

  return (
    <div style={{ width: '100%' }} ref={widthRef}>
      <BaseTable<DoctorController.DoctorFields>
        rowKey={'uuid'}
        actionRef={actionRef}
        search={{ span: 6 }}
        rowSelection={{
          onChange(keys, selectedRows) {
            setSelectedRows(selectedRows);
          },
        }}
        style={{ marginBottom: 50 }}
        tableAlertRender={false}
        toolBarRender={() => [
          <Truly truly={isTrue('masterdata:doctor:add')} key="add">
            <EditForm
              title="新增医护信息"
              key="add"
              type="add"
              trigger={
                <Button icon={<PlusOutlined />} type="primary">
                  新增
                </Button>
              }
              onSubmit={() => {
                actionRef.current?.reload();
              }}
            />
          </Truly>,
          <Truly truly={isTrue('masterdata:doctor:import')} key="import">
            <ImportForm
              key="import"
              title="导入医护信息"
              trigger={
                <Button type="primary" icon={<ImportOutlined />}>
                  导入
                </Button>
              }
              orgList={orgList || []}
              onSubmit={() => {
                actionRef.current?.reload();
              }}
            />
          </Truly>,
        ]}
        columns={columns}
        pagination={{
          defaultPageSize: 10,
          showQuickJumper: true,
          showSizeChanger: true,
          hideOnSinglePage: true,
        }}
        request={async (params: ParamsType) => {
          const { current: pageNum, ...rest } = params;
          const { data = [], total = 0 } = await DoctorController.getListApi({
            ...rest,
            pageNum,
          });
          actionRef.current?.clearSelected?.();
          return {
            data,
            total,
          };
        }}
      />
      <Truly
        truly={isSomeTrue(
          'masterdata:doctor:enable',
          'masterdata:doctor:deactivate',
          'masterdata:doctor:approval',
          'masterdata:doctor:del',
        )}
      >
        <FooterDiv size={size?.width} selectedRowsNumber={selectedRows.length}>
          <Space>
            <Truly truly={isTrue('masterdata:doctor:enable')}>
              <Button
                type="primary"
                key="enable"
                disabled={selectedRows.length <= 0}
                onClick={() => onBatch(selectedRows, '1')}
              >
                批量启用
              </Button>
            </Truly>
            <Truly truly={isTrue('masterdata:doctor:deactivate')}>
              <Button
                key="deactivate"
                danger
                disabled={selectedRows.length <= 0}
                onClick={() => onBatch(selectedRows, '2')}
              >
                批量停用
              </Button>
            </Truly>
            <Truly truly={isTrue('masterdata:doctor: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:doctor:del')}>
              <Button
                type="primary"
                key="del"
                danger
                disabled={selectedRows.length <= 0}
                onClick={() => onDel(selectedRows)}
              >
                批量删除
              </Button>
            </Truly>
          </Space>
        </FooterDiv>
      </Truly>
    </div>
  );
};

export default Doctor;
