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

// 数据类型
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 [fileList, setFileList] = useState<
    { id: number; uid: number; url: string; name: 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,
        address: res.result.address || detail?.address,
        attachmentList: res.result.attachmentList || undefined,
      });
      setDetail(res.result);
      const fileList =
        res.result.attachmentList?.map((v) => ({
          id: Math.random(),
          uid: Math.random(),
          name: v.url.split('/')[v.url.split('/').length - 1],
          url: v.url,
        })) || [];
      setFileList(fileList);
    }
  };
  // 获取加盟列表
  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 attachmentUploadSuccess = (
    value: { id: number; uid: number; url: string; name: string }[],
  ) => {
    setFileList(value);
    form.setFieldValue(
      'attachmentList',
      value.map((v) => ({
        type: ['.doc', '.docx', '.xls', '.xlsx', '.ppt', '.pptx', '.pdf'].includes(
          v.url.match(/\.[^.]+$/)?.[0] as any,
        )
          ? 1
          : 0,
        url: v.url,
      })),
    );
  };

  // 确认事件
  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,
      ...address,
      ...values,
    });
    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>
          <div style={{ display: 'flex' }}>
            <Form.Item
              label='网点地址'
              name='address'
              rules={[{ required: true, message: '请选择网点地址' }]}
              style={{ width: '80%', marginLeft: '5%' }}
            >
              <Input placeholder='请选择网点地址' maxLength={50} allowClear />
            </Form.Item>
            <Button
              type='primary'
              onClick={() => {
                setOpenAddress(true);
              }}
              style={{ transform: 'translateX(-50px)' }}
            >
              选择位置
            </Button>
          </div>
          <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.Item label='营业执照'>
            <Image src={detail?.licenseImg} width={50} height={50} />
          </Form.Item>
          <Form.Item label='附件' name='attachmentList'>
            <Uploader
              fileUpload
              listType='text'
              defaultFileList={fileList}
              fileLength={10}
              fileSize={50}
              onChange={attachmentUploadSuccess}
              fileType={[
                'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                'application/msword',
                'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
                'application/vnd.ms-excel',
                'application/pdf',
                'application/vnd.ms-powerpoint',
                'application/vnd.openxmlformats-officedocument.presentationml.presentation',
                'image/png',
                'image/jpeg',
                'image/jpg',
                'image/gif',
                'image/bmp',
              ]}
            >
              <Button type='primary' icon={<UploadOutlined />}>
                上传
              </Button>
            </Uploader>
          </Form.Item>
          <Form.Item label='备注' name='remark'>
            <Input.TextArea placeholder='请输入备注' maxLength={70} showCount rows={4} />
          </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;
