import { Cascader, Form, Input, message, Modal, ModalProps, Switch } from 'antd';
import { FC, useEffect } from 'react';
import districtData from '~/assets/json/district.json';
import { InterDataType, InterReqType } from '~/api/interface';
import { addressInsetType, addressListType } from '~/api/interface/systemManageType';
import { SystemManageAPI } from '~/api';

interface selfProps {
  onOk: () => void;
  onCancel: () => void;
  currentAddressItem?: addressType[0] | undefined;
}
//新增地址参数类型
type addAddressParameterType = Exclude<InterReqType<addressInsetType>, undefined>;
//地址列表返回类型
type addressType = InterDataType<addressListType>;

const AddOrEditAddressModal: FC<ModalProps & selfProps> = ({
  open,
  onCancel,
  onOk,
  currentAddressItem,
}) => {
  const [form] = Form.useForm<
    Omit<addAddressParameterType, 'takeRegion' | 'type' | 'districtCode'> & {
      takeRegion: string[];
      type: boolean;
      districtCode: number[];
    }
  >();

  const handleOk = () => {
    form.validateFields().then((values) => {
      SystemManageAPI[currentAddressItem ? 'editAddress' : 'addressInset']({
        ...values,
        districtCode: values.districtCode[2].toString(),
        takeRegion: getDistrictName(values.districtCode),
        type: !values.type ? 1 : 0,
        id: currentAddressItem ? currentAddressItem.id : undefined,
      }).then(({ code }) => {
        if (code === '200') {
          message.success('新增地址成功');
          form.resetFields();
          onOk();
        }
      });
    });
  };
  const handleCancel = () => {
    onCancel();
  };
  //根据省市区code查询省市区名称
  const getDistrictName = (codeArr: number[]) => {
    const getFlatDistrictData = (districtData: any[]) => {
      return districtData.reduce((pre: any, cur: any) => {
        pre.push(cur);
        if (cur.childInfo) {
          pre.push(...getFlatDistrictData(cur.childInfo));
        }
        return pre;
      }, []);
    };
    const flatDistrictData: any = getFlatDistrictData(districtData);
    return codeArr.map((v) => flatDistrictData.find((i: any) => i.id === v)?.name).join('/');
  };

  useEffect(() => {
    if (currentAddressItem) {
      form.setFieldsValue({
        takeName: currentAddressItem.takeName,
        takePhone: currentAddressItem.takePhone,
        districtCode: [
          Number(currentAddressItem.districtCode.substring(0, 2) + '0000'),
          Number(currentAddressItem.districtCode.substring(0, 4) + '00'),
          Number(currentAddressItem.districtCode),
        ],
        takeAddress: currentAddressItem.takeAddress,
        type: !currentAddressItem.type,
      });
    }
  }, [currentAddressItem]);

  return (
    <Modal
      open={open}
      title={currentAddressItem ? '编辑地址' : '新增地址'}
      onOk={handleOk}
      onCancel={handleCancel}
    >
      <Form labelCol={{ span: 4 }} wrapperCol={{ span: 20 }} form={form}>
        <Form.Item label='姓名' name='takeName' rules={[{ required: true, message: '请输入姓名' }]}>
          <Input placeholder='请输入姓名' maxLength={30} />
        </Form.Item>
        <Form.Item
          label='手机号'
          name='takePhone'
          rules={[
            { required: true, message: '请输入手机号' },
            // 校验手机号
            () => ({
              validator(_, value) {
                if (!value || /^1[3-9]\d{9}$/.test(value)) {
                  return Promise.resolve();
                }
                return Promise.reject('请输入正确的手机号');
              },
            }),
          ]}
        >
          <Input placeholder='请输入手机号' maxLength={11} />
        </Form.Item>
        <Form.Item
          label='所在地区'
          name='districtCode'
          rules={[{ required: true, message: '请选择所在地区' }]}
        >
          <Cascader
            placeholder='请选择所在地区'
            options={districtData}
            fieldNames={{ label: 'name', value: 'id', children: 'childInfo' }}
          />
        </Form.Item>
        <Form.Item
          label='详细地址'
          name='takeAddress'
          rules={[{ required: true, message: '请输入详细地址' }]}
        >
          <Input.TextArea rows={4} showCount placeholder='请输入详细地址' maxLength={70} />
        </Form.Item>
        <Form.Item label='设为默认地址' name='type' valuePropName='checked'>
          <Switch />
        </Form.Item>
      </Form>
    </Modal>
  );
};
export default AddOrEditAddressModal;
