import BaseFormSelect from '../../../../components/BaseFormSelect';
import BaseFormDatePicker from '../../../../components/BaseFormDatePicker';
import {
  ModalForm,
  ProFormDependency,
  ProFormMoney,
  ProFormRadio,
} from '@ant-design/pro-components';
import BaseFormText from '../../../../components/BaseFormText';
import validatorRules from '@cowin/validator-rules';
import { Col, Form, Row, message } from 'antd';
import React, { useRef } from 'react';
import {
  OPTIONS_ORG_EQUAL_DEGREE,
  OPTIONS_ORG_LEVEL,
  OPTIONS_ORG_STATUS,
  OPTIONS_ORG_TYPE,
} from '../../../../constants/options';
import {
  CommonController,
  OrgController,
  RegionController,
} from '../../../../services';
interface EditFormProps {
  title: string;
  type: 'add' | 'update' | 'view';
  trigger: JSX.Element;
  value?: OrgController.OrgFields;
  flag?: boolean;
  onSubmit?: () => void;
}

const getRegionList = async (code: string) => {
  const res = await RegionController.getListApi({
    supRegionCode: code,
  });
  const { data } = res || {};
  return (data || []).map((item) => {
    return {
      ...item,
      value: item.regionCode,
      label: item.regionName,
    };
  });
};

const EditForm: React.FC<EditFormProps> = (props) => {
  const { trigger, type, title, value, onSubmit } = props;
  const [form] = Form.useForm<OrgController.OrgFields>();
  const ref = useRef<Record<string, boolean>>({});

  return (
    <ModalForm<OrgController.OrgFields>
      layout="horizontal"
      labelCol={{ span: 3 }}
      wrapperCol={{ span: 21 }}
      width={1200}
      title={title}
      trigger={trigger}
      form={form}
      disabled={type === 'view'}
      autoFocusFirstInput
      modalProps={{
        destroyOnClose: true,
      }}
      onOpenChange={() => {
        // 将地区选择的记录信息还原
        Object.keys(ref.current).forEach((key) => {
          ref.current[key] = false;
        });
      }}
      submitTimeout={2000}
      onFinish={async () => {
        const values = await form.validateFields();
        if (type === 'add') {
          await OrgController.addApi({ ...values });
        } else if (type === 'update') {
          // 保留值为undefined的字段，将值编辑为null，否则通过请求函数时，会被忽略
          const updateValues = Object.entries(values).reduce(
            (ret, [key, value]) => {
              return {
                ...ret,
                [key]: value === undefined ? null : value,
              };
            },
            { ...value },
          );
          await OrgController.updateApi(updateValues);
        }
        message.success('提交成功');
        onSubmit?.();
        return true;
      }}
    >
      <Row gutter={0}>
        <Col span={12}>
          <BaseFormText
            label="机构名称"
            name="orgName"
            initialValue={value?.orgName}
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 18 }}
            rules={[
              {
                required: true,
              },
            ]}
          />
        </Col>
        <Col span={12}>
          <BaseFormText
            label="机构简称"
            name="orgDesc"
            initialValue={value?.orgDesc}
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 18 }}
            rules={[
              {
                required: true,
              },
            ]}
          />
        </Col>
      </Row>
      <Row gutter={0}>
        <Col span={12}>
          <BaseFormText
            label="组织机构代码"
            name="orgCode"
            disabled={type !== 'add'}
            initialValue={value?.orgCode}
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 18 }}
            rules={[
              {
                required: true,
              },
            ]}
          />
        </Col>
        <Col span={12}>
          <BaseFormSelect
            label="机构大类"
            name="orgType"
            initialValue={value?.orgType}
            options={OPTIONS_ORG_TYPE}
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 18 }}
            rules={[
              {
                required: true,
              },
            ]}
          />
        </Col>
      </Row>
      <Row gutter={0}>
        <Col span={6}>
          <BaseFormSelect
            label="机构地址"
            placeholder="所属区划省"
            name="belProvince"
            initialValue={value?.belProvince}
            fieldProps={{ fetchDataOnSearch: false }}
            request={async () => await getRegionList('0')}
            labelCol={{ span: 12 }}
            wrapperCol={{ span: 12 }}
          ></BaseFormSelect>
        </Col>
        <Col span={3}>
          <ProFormDependency name={['belProvince']}>
            {({ belProvince }) => {
              return (
                <BaseFormSelect
                  placeholder="所属区划市"
                  name="belCity"
                  initialValue={value?.belCity}
                  params={{ belProvince }}
                  fieldProps={{ fetchDataOnSearch: false }}
                  request={async ({ belProvince }) =>
                    getRegionList(belProvince).then((regionList) => {
                      if (!ref.current.belCity) {
                        ref.current.belCity = true;
                      } else {
                        form.setFieldValue('belCity', undefined);
                      }
                      return belProvince ? regionList : [];
                    })
                  }
                  wrapperCol={{ span: 24 }}
                ></BaseFormSelect>
              );
            }}
          </ProFormDependency>
        </Col>
        <Col span={3}>
          <ProFormDependency name={['belCity']}>
            {({ belCity }) => {
              return (
                <BaseFormSelect
                  placeholder="所属区划县"
                  name="belCountyarea"
                  initialValue={value?.belCountyarea}
                  params={{ belCity }}
                  fieldProps={{ fetchDataOnSearch: false }}
                  request={async ({ belCity }) =>
                    getRegionList(belCity).then((regionList) => {
                      if (!ref.current.belCountyarea) {
                        ref.current.belCountyarea = true;
                      } else {
                        form.setFieldValue('belCountyarea', undefined);
                      }
                      return belCity ? regionList : [];
                    })
                  }
                  wrapperCol={{ span: 24 }}
                ></BaseFormSelect>
              );
            }}
          </ProFormDependency>
        </Col>
        <Col span={3}>
          <ProFormDependency name={['belCountyarea']}>
            {({ belCountyarea }) => {
              return (
                <BaseFormSelect
                  placeholder="所属区划乡镇"
                  name="belTown"
                  initialValue={value?.belTown}
                  params={{ belCountyarea }}
                  fieldProps={{ fetchDataOnSearch: false }}
                  request={async ({ belCountyarea }) =>
                    getRegionList(belCountyarea).then((regionList) => {
                      if (!ref.current.belTown) {
                        ref.current.belTown = true;
                      } else {
                        form.setFieldValue('belTown', undefined);
                      }
                      return belCountyarea ? regionList : [];
                    })
                  }
                  wrapperCol={{ span: 24 }}
                ></BaseFormSelect>
              );
            }}
          </ProFormDependency>
        </Col>
        <Col span={3}>
          <ProFormDependency name={['belTown']}>
            {({ belTown }) => {
              return (
                <BaseFormSelect
                  placeholder="所属区划村"
                  name="belVillages"
                  initialValue={value?.belVillages}
                  params={{ belTown }}
                  fieldProps={{ fetchDataOnSearch: false }}
                  request={async ({ belTown }) =>
                    getRegionList(belTown).then((regionList) => {
                      if (!ref.current.belVillages) {
                        ref.current.belVillages = true;
                      } else {
                        form.setFieldValue('belVillages', undefined);
                      }
                      return belTown ? regionList : [];
                    })
                  }
                  wrapperCol={{ span: 24 }}
                ></BaseFormSelect>
              );
            }}
          </ProFormDependency>
        </Col>
      </Row>
      <BaseFormText
        label="机构地址全称"
        name="orgFullName"
        initialValue={value?.orgFullName}
      />

      <Row gutter={0}>
        <Col span={6}>
          <BaseFormSelect
            label="管辖区域"
            placeholder="所属区划省"
            labelCol={{ span: 12 }}
            wrapperCol={{ span: 12 }}
            name="manProvince"
            initialValue={value?.manProvince}
            fieldProps={{ fetchDataOnSearch: false }}
            request={async () => getRegionList('0')}
          />
        </Col>
        <Col span={3}>
          <ProFormDependency name={['manProvince']}>
            {({ manProvince }) => {
              return (
                <BaseFormSelect
                  placeholder="所属区划市"
                  labelCol={{ span: 0 }}
                  wrapperCol={{ span: 24 }}
                  name="manCity"
                  initialValue={value?.manCity}
                  params={{ manProvince }}
                  fieldProps={{ fetchDataOnSearch: false }}
                  request={async ({ manProvince }) =>
                    getRegionList(manProvince).then((regionList) => {
                      if (!ref.current.manCity) {
                        ref.current.manCity = true;
                      } else {
                        form.setFieldValue('manCity', undefined);
                      }
                      return manProvince ? regionList : [];
                    })
                  }
                ></BaseFormSelect>
              );
            }}
          </ProFormDependency>
        </Col>
        <Col span={3}>
          <ProFormDependency name={['manCity']}>
            {({ manCity }) => {
              return (
                <BaseFormSelect
                  placeholder="所属区划县"
                  labelCol={{ span: 0 }}
                  wrapperCol={{ span: 24 }}
                  name="manCountyarea"
                  initialValue={value?.manCountyarea}
                  params={{ manCity }}
                  fieldProps={{ fetchDataOnSearch: false }}
                  request={async ({ manCity }) =>
                    getRegionList(manCity).then((regionList) => {
                      if (!ref.current.manCountyarea) {
                        ref.current.manCountyarea = true;
                      } else {
                        form.setFieldValue('manCountyarea', undefined);
                      }
                      return manCity ? regionList : [];
                    })
                  }
                ></BaseFormSelect>
              );
            }}
          </ProFormDependency>
        </Col>
        <Col span={3}>
          <ProFormDependency name={['manCountyarea']}>
            {({ manCountyarea }) => {
              return (
                <BaseFormSelect
                  placeholder="所属区划乡镇"
                  labelCol={{ span: 0 }}
                  wrapperCol={{ span: 24 }}
                  name="manTown"
                  initialValue={value?.manTown}
                  params={{ manCountyarea }}
                  fieldProps={{ fetchDataOnSearch: false }}
                  request={async ({ manCountyarea }) =>
                    getRegionList(manCountyarea).then((regionList) => {
                      if (!ref.current.manTown) {
                        ref.current.manTown = true;
                      } else {
                        form.setFieldValue('manTown', undefined);
                      }
                      return manCountyarea ? regionList : [];
                    })
                  }
                ></BaseFormSelect>
              );
            }}
          </ProFormDependency>
        </Col>
        <Col span={3}>
          <ProFormDependency name={['manTown']}>
            {({ manTown }) => {
              return (
                <BaseFormSelect
                  placeholder="所属区划村"
                  labelCol={{ span: 0 }}
                  wrapperCol={{ span: 24 }}
                  name="manVillages"
                  initialValue={value?.manVillages}
                  params={{ manTown }}
                  fieldProps={{ fetchDataOnSearch: false }}
                  request={async ({ manTown }) =>
                    getRegionList(manTown).then((regionList) => {
                      if (!ref.current.manVillages) {
                        ref.current.manVillages = true;
                      } else {
                        form.setFieldValue('manVillages', undefined);
                      }
                      return manTown ? regionList : [];
                    })
                  }
                ></BaseFormSelect>
              );
            }}
          </ProFormDependency>
        </Col>
      </Row>
      <Row gutter={0}>
        <Col span={12}>
          <BaseFormSelect
            showSearch
            fieldProps={{
              fetchDataOnSearch: false,
            }}
            label="上级机构"
            name="supOrgCode"
            initialValue={value?.supOrgCode}
            request={async () => CommonController.getOrgOptionsApi()}
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 18 }}
          ></BaseFormSelect>
        </Col>
        <Col span={12}>
          <BaseFormText
            label="联系电话"
            name="orgPhone"
            initialValue={value?.orgPhone}
            rules={[
              { required: true },
              {
                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();
                    }
                  }
                },
              },
            ]}
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 18 }}
          />
        </Col>
      </Row>
      <Row gutter={0}>
        <Col span={12}>
          <BaseFormText
            label="法人姓名"
            name="orgResName"
            initialValue={value?.orgResName}
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 18 }}
            rules={[
              {
                required: true,
              },
            ]}
          />
        </Col>
        <Col span={12}>
          <BaseFormText
            label="法人电话"
            name="orgResPhone"
            initialValue={value?.orgResPhone}
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 18 }}
            rules={[
              { required: true },
              {
                validator: (rules, value, fn) => {
                  if (!value) return fn();
                  const res = validatorRules('Phone', value);
                  if (!res.checkState) {
                    fn(res.message);
                  } else {
                    fn();
                  }
                },
              },
            ]}
          />
        </Col>
      </Row>
      <Row gutter={0}>
        <Col span={12}>
          <BaseFormSelect
            showSearch
            label="机构类别"
            name="orgClassCode"
            initialValue={value?.orgClassCode}
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 18 }}
            request={async () =>
              CommonController.getSelectionsApi('QY99.00.014')
            }
          ></BaseFormSelect>
        </Col>
        <Col span={12}>
          <BaseFormSelect
            showSearch
            label="经济类型"
            name="ecoClassCoecoClassCode"
            initialValue={value?.ecoClassCoecoClassCode}
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 18 }}
            request={async () =>
              CommonController.getSelectionsApi('GB/T 12402-2000')
            }
          ></BaseFormSelect>
        </Col>
      </Row>
      <ProFormDependency name={['orgType']}>
        {({ orgType }) => {
          if (orgType === '1') {
            form.setFieldValue('orgDegree', undefined);
            form.setFieldValue('orgLevel', undefined);
          }
          return (
            <Row gutter={0}>
              <Col span={12}>
                <ProFormRadio.Group
                  name="orgDegree"
                  initialValue={value?.orgDegree}
                  label="机构等次"
                  labelCol={{ span: 6 }}
                  wrapperCol={{ span: 18 }}
                  options={OPTIONS_ORG_EQUAL_DEGREE}
                  disabled={orgType === '1'}
                  rules={[
                    {
                      required: orgType !== '1',
                    },
                  ]}
                />
              </Col>
              <Col span={12}>
                <ProFormRadio.Group
                  name="orgLevel"
                  initialValue={value?.orgLevel}
                  label="机构等级"
                  labelCol={{ span: 6 }}
                  wrapperCol={{ span: 18 }}
                  options={OPTIONS_ORG_LEVEL}
                  disabled={orgType === '1'}
                  rules={[
                    {
                      required: orgType !== '1',
                    },
                  ]}
                />
              </Col>
            </Row>
          );
        }}
      </ProFormDependency>

      <Row gutter={0}>
        <Col span={12}>
          <ProFormRadio.Group
            name="orgStatus"
            disabled
            initialValue={
              value?.orgStatus === '4'
                ? '3'
                : value?.orgStatus
                ? value?.orgStatus
                : '3'
            }
            label="机构状态"
            options={OPTIONS_ORG_STATUS}
            rules={[
              {
                required: true,
              },
            ]}
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 18 }}
          />
        </Col>
        <Col span={12}>
          <BaseFormText
            label="邮政编码"
            name="postCode"
            initialValue={value?.postCode}
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 18 }}
            rules={[
              {
                validator: (rules, value, fn) => {
                  if (!value) return fn();
                  const res = validatorRules('PostalCode', value);
                  if (!res.checkState) {
                    fn(res.message);
                  } else {
                    fn();
                  }
                },
              },
            ]}
          />
        </Col>
      </Row>
      <Row gutter={0}>
        <Col span={12}>
          <BaseFormText
            label="机构经度"
            name="orgLongitude"
            initialValue={value?.orgLongitude}
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 18 }}
            rules={[
              {
                validator: (rules, value, fn) => {
                  if (!value) return fn();
                  // 经度：要求经度整数部分为0-180小数部分为0到4位！
                  const reg =
                    /^[\-\+]?(0(\.\d{1,10})?|([1-9](\d)?)(\.\d{1,10})?|1[0-7]\d{1}(\.\d{1,10})?|180\.0{1,10})$/;
                  if (reg.test(value)) {
                    fn('经度格式校验错误');
                  } else {
                    fn();
                  }
                },
              },
            ]}
          />
        </Col>
        <Col span={12}>
          <BaseFormText
            label="机构纬度"
            name="orgLatitude"
            initialValue={value?.orgLatitude}
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 18 }}
            rules={[
              {
                validator: (rules, value, fn) => {
                  if (!value) return fn();
                  // 要求纬度整数部分为0-90小数部分为0到4位！
                  const reg =
                    /^[\-\+]?((0|([1-8]\d?))(\.\d{1,10})?|90(\.0{1,10})?)$/;
                  if (reg.test(value)) {
                    fn('纬度格式校验错误');
                  } else {
                    fn();
                  }
                },
              },
            ]}
          />
        </Col>
      </Row>
      <Row gutter={0}>
        <Col span={12}>
          <BaseFormDatePicker
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 18 }}
            name="openingDate"
            initialValue={value?.openingDate}
            label="开业日期"
            width="lg"
          />
        </Col>
        <Col span={12}>
          <ProFormMoney
            placeholder={'亲输入注册资金'}
            name="registeredCapital"
            initialValue={value?.registeredCapital}
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 18 }}
            min={0}
          />
        </Col>
      </Row>
      <Row gutter={0}>
        <Col span={12}>
          <BaseFormText
            label="社会信用代码"
            name="socialCreditCode"
            initialValue={value?.socialCreditCode}
            labelCol={{ span: 6 }}
            wrapperCol={{ span: 18 }}
            rules={[
              {
                required: true,
              },
              {
                validator: (rules, value, fn) => {
                  if (!value) return fn();
                  const res = validatorRules('SocialCode', value);
                  if (!res.checkState) {
                    fn(res.message);
                  } else {
                    fn();
                  }
                },
              },
            ]}
          />
        </Col>
        <Col span={12}>
          <BaseFormText
            label="版本号"
            name="version"
            initialValue={value?.version}
            labelCol={{ span: 6 }}
            rules={[{ required: true }]}
          />
        </Col>
      </Row>
    </ModalForm>
  );
};

export default EditForm;
