import BaseFormSelect from '@/components/BaseFormSelect';
import {
  ModalForm,
  ProFormDependency,
  ProFormRadio,
} from '@ant-design/pro-components';
import BaseFormText from '@/components/BaseFormText';
import BaseFormTextArea from '@/components/BaseFormTextArea';
import BaseFormDatePicker from '@/components/BaseFormDatePicker';
import validatorRules from '@cowin/validator-rules';
import { Col, Form, Row } from 'antd';
import React from 'react';
import { OPTIONS_ORG_STATUS } from '../../../../constants/options';
import { CommonController, DeptController } from '../../../../services';

interface ModalEditFormProps {
  title: string;
  trigger: JSX.Element;
  type: 'add' | 'view' | 'update';
  initValues?: DeptController.DeptFields;
  onSubmit: () => void;
}

const ModalEditForm: React.FC<ModalEditFormProps> = (props) => {
  const { title, type, trigger, onSubmit, initValues } = props;
  const [form] = Form.useForm<DeptController.DeptFields>();

  async function onFinish(values: DeptController.DeptFields) {
    if (type === 'add') {
      const params = {
        ...values,
      };
      await DeptController.addApi(params);
    } else if (type === 'update') {
      // 清空select类型组件会导致表单字段缺失，此处需要重新赋值
      const initData = {
        insSupDeptCode: null,
        deptOpenDate: null,
        staDeptCode: null,
      };
      await DeptController.updateApi({
        ...initValues,
        ...initData,
        ...values,
      });
    }
    onSubmit();
    return true;
  }

  return (
    <ModalForm<DeptController.DeptFields>
      layout="horizontal"
      labelCol={{ span: 6 }}
      wrapperCol={{ span: 18 }}
      width={1200}
      title={title}
      form={form}
      trigger={trigger}
      disabled={type === 'view'}
      autoFocusFirstInput
      modalProps={{
        destroyOnClose: true,
      }}
      submitTimeout={2000}
      onFinish={onFinish}
    >
      <Row gutter={0}>
        <Col span={12}>
          <BaseFormSelect
            label="机构名称"
            name="orgCode"
            showSearch
            disabled={type !== 'add'}
            initialValue={initValues?.orgCode}
            request={async () => CommonController.getOrgOptionsApi()}
            rules={[{ required: true }]}
          />
        </Col>
        <Col span={12}>
          <BaseFormText
            label="科室名称"
            name="deptName"
            initialValue={initValues?.deptName}
            rules={[{ required: true }]}
          />
        </Col>
      </Row>
      <Row gutter={0}>
        <Col span={12}>
          <BaseFormText
            label="内部科室编码"
            name="insDeptCode"
            disabled={type !== 'add'}
            initialValue={initValues?.insDeptCode}
            rules={[{ required: true }]}
          />
        </Col>
        <Col span={12}>
          <BaseFormSelect
            label="标准科室编码"
            name="staDeptCode"
            initialValue={initValues?.staDeptCode}
            fieldProps={{ fetchDataOnSearch: false }}
            request={async () =>
              CommonController.getSelectionsApi('QY99.00.018')
            }
          />
        </Col>
      </Row>
      <Row gutter={0}>
        <Col span={12}>
          <ProFormDependency name={['orgCode']}>
            {({ orgCode }) => {
              return (
                <BaseFormSelect
                  label="上级科室"
                  name="insSupDeptCode"
                  initialValue={initValues?.insSupDeptCode}
                  params={{ orgCode }}
                  fieldProps={{ fetchDataOnSearch: false }}
                  request={async ({ orgCode }) => {
                    if (!orgCode) return [];
                    return CommonController.getDeptOptionsApi({ orgCode });
                  }}
                />
              );
            }}
          </ProFormDependency>
        </Col>
        <Col span={12}>
          <BaseFormDatePicker
            label="科室开设时间"
            name="deptOpenDate"
            initialValue={initValues?.deptOpenDate}
            width="lg"
          />
        </Col>
      </Row>
      <Row gutter={0}>
        <Col span={12}>
          <BaseFormText
            label="科室所属病区编码"
            name="wardCode"
            initialValue={initValues?.wardCode}
          />
        </Col>
        <Col span={12}>
          <BaseFormText
            label="科室所属病区名称"
            name="wardName"
            initialValue={initValues?.wardName}
          />
        </Col>
      </Row>
      <Row gutter={0}>
        <Col span={12}>
          <BaseFormText
            label="科室联系电话"
            name="deptPhone"
            initialValue={initValues?.deptPhone}
            rules={[
              {
                validator: (rules, value, fn) => {
                  if (!value) return fn();
                  if (value.startsWith('0')) {
                    const res = validatorRules('Telephone', value);
                    if (!res.checkState) {
                      fn(res.message);
                    } else {
                      fn();
                    }
                  } else {
                    const res = validatorRules('Phone', value);
                    if (!res.checkState) {
                      fn(res.message);
                    } else {
                      fn();
                    }
                  }
                },
              },
            ]}
          />
        </Col>
        <Col span={12}>
          <BaseFormText
            label="科室地址"
            name="deptAddress"
            initialValue={initValues?.deptAddress}
          />
        </Col>
      </Row>
      <Row gutter={0}>
        <Col span={12}>
          <BaseFormText
            label="版本号"
            name="version"
            initialValue={initValues?.version}
            labelCol={{ span: 6 }}
            rules={[{ required: true }]}
          />
        </Col>
        <Col span={12}>
          <ProFormRadio.Group
            name="deptStatus"
            disabled
            initialValue={
              initValues?.deptStatus === '4'
                ? '3'
                : initValues?.deptStatus
                ? initValues?.deptStatus
                : '3'
            }
            label="科室状态"
            options={OPTIONS_ORG_STATUS}
            rules={[
              {
                required: true,
              },
            ]}
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 18 }}
          />
        </Col>
      </Row>
      <Row gutter={0}>
        <Col span={24}>
          <BaseFormTextArea
            label="科室简介"
            name="deptDesc"
            initialValue={initValues?.deptDesc}
            labelCol={{ span: 3 }}
            wrapperCol={{ span: 21 }}
          />
        </Col>
      </Row>
    </ModalForm>
  );
};

export default ModalEditForm;
