import { ImportOutlined, PlusOutlined } from '@ant-design/icons';
import { ParamsType, ProFormInstance } from '@ant-design/pro-components';
import BaseTable, { ProColumns, ActionType } 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,
  OPTIONS_BATCH,
  OPTIONS_BED_TYPE,
} from '../../constants/options';
import { BedController, CommonController } from '../../services';
import { isSomeTrue, isTrue } from '../../utils/auth';
import BatchForm from './components/BatchForm';
import EditForm from './components/EditForm';
import ImportForm from './components/ImportForm';

const Bed: React.FC<unknown> = () => {
  const actionRef = useRef<ActionType>();
  const formRef = useRef<ProFormInstance>();
  const widthRef = useRef(null);
  const size = useSize(widthRef);
  const [selectedRows, setSelectedRows] = useState<BedController.BedFields[]>(
    [],
  );

  const { data: orgList } = useRequest(CommonController.getOrgOptionsApi);
  const { data: deptList, run: getDeptOptions } = useRequest(
    CommonController.getDeptOptionsApi,
    {
      manual: true,
      onSuccess() {
        formRef.current?.setFieldValue('deptCode', undefined);
      },
    },
  );

  const columns: ProColumns<BedController.BedFields>[] = [
    {
      title: '床位编码',
      dataIndex: 'bedCode',
    },
    {
      title: '床号',
      dataIndex: 'bedNo',
      hideInSearch: true,
    },
    {
      title: '机构名称',
      dataIndex: 'orgCode',
      valueType: 'select',
      hideInTable: true,
      fieldProps: {
        options: orgList || [],
        showSearch: true,
        onChange: (orgCode: string) => {
          getDeptOptions({ orgCode });
        },
      },
    },
    {
      title: '机构名称',
      dataIndex: 'orgName',
      hideInSearch: true,
    },
    {
      title: '科室名称',
      dataIndex: 'deptCode',
      valueType: 'select',
      hideInTable: true,
      fieldProps: {
        options: deptList || [],
        showSearch: true,
      },
    },
    {
      title: '科室名称',
      dataIndex: 'deptName',
      hideInSearch: true,
    },
    {
      title: '床位类型',
      dataIndex: 'bedClass',
      valueType: 'select',
      hideInTable: true,
      request: async () => OPTIONS_BED_TYPE,
    },
    {
      title: '床位类型',
      dataIndex: 'bedClass',
      hideInSearch: true,
      render: (_, record) => {
        const { label } =
          OPTIONS_BED_TYPE.find((item) => item.value === record.bedClass) || {};
        return label || '-';
      },
    },
    {
      title: '状态',
      dataIndex: 'bedStatus',
      valueType: 'select',
      hideInTable: true,
      request: async () => OPTIONS_APPROVAL,
    },
    {
      title: '状态',
      dataIndex: 'bedStatus',
      hideInSearch: true,
      render: (_, record) => {
        const { label, color } =
          OPTIONS_APPROVAL.find((item) => item.value === record.bedStatus) ||
          {};
        if (label) {
          return <Tag color={color}>{label || ''}</Tag>;
        }
        return '-';
      },
    },
    {
      title: '版本号',
      dataIndex: 'version',
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      width: 160,
      render: (_, record) => (
        <Space>
          <EditForm
            key="view"
            type="view"
            title="查看床位详情"
            value={record}
            orgList={orgList || []}
            trigger={<a key="view">查看</a>}
          />
          <Truly truly={isTrue('masterdata:bed:edit')}>
            <EditForm
              key="update"
              type="update"
              title="编辑床位"
              value={record}
              orgList={orgList || []}
              trigger={<a key="update">编辑</a>}
              onSubmit={() => {
                actionRef.current?.reload();
              }}
            />
          </Truly>
        </Space>
      ),
    },
  ];
  /**
   * @name 批量启用/批量停用/批量审批/批量驳回
   * @param selectedRows
   * @param bedStatus
   */
  const onBatch = (
    selectedRows: BedController.BedFields[],
    bedStatus: string,
  ) => {
    if (bedStatus === '1') {
      const isCancel = selectedRows.some((item) => item.bedStatus !== '2');
      if (isCancel) {
        return message.warning('请勾选状态为已停用的数据！');
      }
    } else if (bedStatus === '2') {
      const isCancel = selectedRows.some((item) => item.bedStatus !== '1');
      if (isCancel) {
        return message.warning('请勾选状态为已启用的数据！');
      }
    }
    const { label } =
      OPTIONS_BATCH.find((item) => item.value === bedStatus) || {};
    Modal.confirm({
      content: `是否确认执行批量${label}操作？`,
      maskClosable: true,
      onOk: async () => {
        const beds = selectedRows.map(({ bedCode, deptCode, orgCode }) => {
          return { bedCode, deptCode, orgCode };
        });
        await BedController.batchApi({ beds, bedStatus });
        actionRef.current?.reload();
      },
      okText: '确定',
      cancelText: '取消',
    });
  };
  const onDel = (selectedRows: BedController.BedFields[]) => {
    Modal.confirm({
      content: `是否确认执行批量删除操作？`,
      maskClosable: true,
      onOk: async () => {
        const beds = (selectedRows || []).map(
          ({ orgCode, deptCode, bedCode }) => {
            return { orgCode, deptCode, bedCode };
          },
        );
        await BedController.delApi(beds);
        actionRef.current?.reload();
      },
      okText: '确定',
      cancelText: '取消',
    });
  };
  return (
    <div style={{ width: '100%' }} ref={widthRef}>
      <BaseTable<BedController.BedFields>
        rowKey={(record) => {
          return `${record.deptCode}-${record.bedCode}`;
        }}
        actionRef={actionRef}
        formRef={formRef}
        search={{ span: 6 }}
        rowSelection={{
          onChange(keys, selectedRows) {
            setSelectedRows(selectedRows);
          },
        }}
        onReset={() => {
          getDeptOptions({ type: 'clear' });
        }}
        style={{ marginBottom: 50 }}
        tableAlertRender={false}
        toolBarRender={() => [
          <Truly truly={isTrue('masterdata:bed:add')} key="add">
            <EditForm
              key="add"
              type="add"
              title="新增床位"
              orgList={orgList || []}
              trigger={
                <Button type="primary" icon={<PlusOutlined />}>
                  新增
                </Button>
              }
              onSubmit={() => {
                actionRef.current?.reload();
              }}
            />
          </Truly>,
          <Truly truly={isTrue('masterdata:bed:import')} key="import">
            <ImportForm
              key="import"
              title="导入床位数据"
              orgList={orgList || []}
              trigger={
                <Button type="primary" icon={<ImportOutlined />}>
                  导入
                </Button>
              }
              onSubmit={() => {
                actionRef.current?.reload();
              }}
            />
          </Truly>,
        ]}
        columns={columns}
        pagination={{
          defaultPageSize: 10,
          showQuickJumper: true,
          showSizeChanger: true,
          hideOnSinglePage: true,
        }}
        request={async (params: ParamsType) => {
          const { current: pageNum = 1, ...rest } = params;
          const pageParams = {
            ...rest,
            pageNum,
          };
          const res = await BedController.getListApi(pageParams);
          const { total, data } = res || {};
          actionRef.current?.clearSelected?.();
          return {
            data,
            total,
          };
        }}
      />
      <Truly
        truly={isSomeTrue(
          'masterdata:bed:enable',
          'masterdata:bed:deactivate',
          'masterdata:bed:approval',
          'masterdata:bed:del',
        )}
      >
        <FooterDiv size={size?.width} selectedRowsNumber={selectedRows.length}>
          <Space>
            <Truly truly={isTrue('masterdata:bed:enable')}>
              <Button
                type="primary"
                key="enable"
                disabled={selectedRows.length <= 0}
                onClick={() => onBatch(selectedRows, '1')}
              >
                批量启用
              </Button>
            </Truly>
            <Truly truly={isTrue('masterdata:bed:deactivate')}>
              <Button
                key="deactivate"
                danger
                disabled={selectedRows.length <= 0}
                onClick={() => onBatch(selectedRows, '2')}
              >
                批量停用
              </Button>
            </Truly>
            <Truly truly={isTrue('masterdata:bed: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:bed:del')}>
              <Button
                key="del"
                type="primary"
                danger
                disabled={selectedRows.length <= 0}
                onClick={() => onDel(selectedRows)}
              >
                批量删除
              </Button>
            </Truly>
          </Space>
        </FooterDiv>
      </Truly>
    </div>
  );
};

export default Bed;
