import { FC, useEffect, useState } from 'react';
import {
  editUserApplyTag,
  editUserApplyTagDetails,
  listUserApplyTag,
} from '~/api/interface/customManageType';
import { InterDataType, InterListType, InterReqType } from '~/api/interface';
import { Button, Form, Input, message, Modal, Rate, Select, Space } from 'antd';
import { CustomManageAPI } from '~/api';
import SelectMapModal from '~/components/select-map';

// 数据类型
type DataType = InterDataType<editUserApplyTagDetails>;
// 列表的类型
type TableType = InterListType<listUserApplyTag>;
// 请求的表单类型
type ReqType = InterReqType<editUserApplyTag>;
// 传参类型
interface propType {
  title: string;
  open: boolean;
  closed: any;
  data?: TableType[0];
}

const AddEditModal: FC<propType> = (props) => {
  // 参数
  const { title, open, closed, data } = props;
  // 表单数据
  const [form] = Form.useForm<ReqType>();
  // 详情数据
  const [detail, setDetail] = useState<DataType>();
  // 是否选择地址弹窗
  const [openAddress, setOpenAddress] = useState<boolean>(false);
  // 加盟列表
  const [cooperationList, setCooperationList] = useState<{ label: string; value: number }[]>([]);
  // 选择的地址
  const [address, setAddress] = useState<{ lat: number; lon: number; address: string }>();
  // 关闭弹窗
  const handleCancel = () => {
    form.resetFields();
    closed();
  };
  // 获取审批详情
  const getApplyTagDetails = async () => {
    const res = await CustomManageAPI.editUserApplyTagDetails({
      id: Number(data?.id),
    });
    if (res && res.code === '200') {
      form.setFieldsValue({
        ...res.result,
        name: res.result.name || data?.companyName,
      });
      setDetail(res.result);
      // console.log('获取审批详情 -->', res.result);
    }
  };
  // 获取加盟列表
  const getCooperationList = async () => {
    const res = await CustomManageAPI.cooperationListTag({});
    if (res && res.code === '200') {
      const list = res.result || [];
      setCooperationList(list.map((i) => ({ label: i.tagName, value: i.id })));
    }
  };
  // 确认事件
  const handleOk = () => {
    form
      .validateFields()
      .then(async (values) => {
        await handleSubmit(values);
      })
      .catch((err) => {
        message
          .warning({
            content: err.errorFields[0].errors[0],
          })
          .then();
      });
  };
  // 提交事件
  const handleSubmit = async (values: ReqType) => {
    const res = await CustomManageAPI.editUserApplyTag({
      id: Number(data?.id),
      ...detail,
      ...values,
      ...address,
    });
    if (res && res.code === '200') {
      message.success('操作成功');
      handleCancel();
    }
  };
  // componentDidMount
  useEffect(() => {
    if (!open) return;
    getCooperationList().then();
    if (!data) return;
    getApplyTagDetails().then();
    // console.log('data --->', data);
  }, [open]);
  return (
    <>
      <Modal open={open} title={title} onCancel={handleCancel} onOk={handleOk} destroyOnClose>
        <Form form={form} labelCol={{ span: 5 }} wrapperCol={{ span: 16 }}>
          <Form.Item
            label='网点名称'
            name='name'
            rules={[{ required: true, message: '请输入网点名称' }]}
          >
            <Input placeholder={'请输入企业名称'} maxLength={25} allowClear />
          </Form.Item>
          <Form.Item
            label='加盟类型'
            name='cooperationTagId'
            rules={[{ required: true, message: '请选择加盟类型' }]}
          >
            <Select placeholder='请选择加盟类型' allowClear options={cooperationList} disabled />
          </Form.Item>
          <Form.Item
            label='网点地址'
            name='address'
            rules={[{ required: true, message: '请选择网点地址' }]}
          >
            <Space.Compact style={{ width: '100%' }}>
              <Input
                placeholder='请选择网点地址'
                maxLength={50}
                allowClear
                disabled
                value={form.getFieldValue('address') || detail?.address}
              />
              <Button
                type='primary'
                onClick={() => {
                  setOpenAddress(true);
                }}
              >
                选择位置
              </Button>
            </Space.Compact>
          </Form.Item>
          <Form.Item
            label='服务资质'
            name='content'
            rules={[{ required: true, message: '请输入服务资质' }]}
          >
            <Input.TextArea
              placeholder={'请输入服务资质（“；”号换行）'}
              maxLength={140}
              allowClear
              showCount
            />
          </Form.Item>
          <Form.Item
            label='服务评分'
            name='score'
            initialValue={5}
            rules={[{ required: true, message: '请选择服务评分' }]}
          >
            <Rate allowClear />
          </Form.Item>
        </Form>
      </Modal>
      <SelectMapModal
        title={'选择位置'}
        open={openAddress}
        closed={() => {
          setOpenAddress(false);
        }}
        submit={(e: { lat: number; lon: number; address: string }) => {
          form.setFieldValue('address', e.address);
          setAddress(e);
          setOpenAddress(false);
        }}
      />
    </>
  );
};

export default AddEditModal;
