import React, { useEffect, useState } from 'react';
import { Form, Input, message, Modal, ModalProps, Select } from 'antd';
import { InterListType, InterReqType } from '~/api/interface';
import { mallOrderListType, updateGoodsOrderType } from '~/api/interface/activityManage';
import { Uploader } from '~/components/uploader';
import { UploadOutlined } from '@ant-design/icons';
import { ActivityManageAPI } from '~/api';

// 详情类型
type DetailType = InterListType<mallOrderListType>[0];
// 请求数据
type ReqType = InterReqType<updateGoodsOrderType>;

const AddEditModalView: React.FC<ModalProps & { onCancel: () => void; data?: DetailType }> = ({
  open,
  title,
  onCancel,
  data,
}) => {
  // 店铺图片列表
  const [imageList, setImageList] = useState<any>([]);
  // 表单数据
  const [form] = Form.useForm<ReqType>();
  // 关闭弹窗
  const handleCancel = () => {
    onCancel?.();
  };
  // 快递列表
  const [kdnDicList, setKdnDicList] = useState<
    {
      label: string;
      value: string;
    }[]
  >([]);
  // 获取快递字典
  const getKdnDicList = async () => {
    const res = await ActivityManageAPI.listKdnDic();
    if (res && res.code === '200') {
      setKdnDicList((res.result || [])?.map((i) => ({ label: i?.exName, value: i?.exCode })));
      // console.log('获取快递字典 --->', res.result);
    }
  };
  // 确定事件
  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 ActivityManageAPI.updateGoodsOrder({
      ...data,
      ...values,
      sendStatus: 1,
    });
    if (res && res.code === '200') {
      (window as any).getMessageNumber();
      message.success('发货成功');
      handleCancel();
    }
  };
  // 组件挂载
  useEffect(() => {
    getKdnDicList().then();
    if (!open) return;
    form.setFieldsValue(data);
    try {
      setImageList(
        (JSON.parse(data?.goodsUrl || `[]`) || [])?.map((i: { url: string }, j: number) => ({
          id: j,
          url: i,
        })),
      );
    } catch (e) {
      setImageList([]);
    }
  }, [open]);
  return (
    <Modal open={open} title={title} onCancel={handleCancel} onOk={handleOk}>
      <Form form={form} labelCol={{ span: 4 }} wrapperCol={{ span: 14 }}>
        <Form.Item
          label='商品名称'
          name='goods'
          rules={[{ required: true, message: '请输入商品名称' }]}
        >
          <Input placeholder={'请输入商品名称'} maxLength={25} allowClear disabled />
        </Form.Item>
        <Form.Item
          label='商品图片'
          name='goodsUrl'
          rules={[{ required: true, message: '请上传商品图片' }]}
        >
          <Uploader
            fileUpload
            listType='picture-card'
            defaultFileList={imageList}
            disabled={true}
            fileLength={1}
            fileSize={10}
          >
            <UploadOutlined />
          </Uploader>
        </Form.Item>
        <Form.Item
          label='消耗积分'
          name='needPoints'
          rules={[
            { required: true, message: '请输入消耗积分' },
            { pattern: /^[1-9]\d*$/, message: '请输入正整数' },
            {
              validator: (_rule, value) => {
                if (value > 99999999) {
                  return Promise.reject('最大不能超过99999999');
                }
                return Promise.resolve();
              },
            },
          ]}
        >
          <Input
            placeholder={'请输入消耗积分'}
            maxLength={25}
            allowClear
            type={'number'}
            disabled
          />
        </Form.Item>
        <Form.Item
          label='快递公司'
          name='trackintCompany'
          rules={[{ required: true, message: '请选择快递公司' }]}
        >
          <Select placeholder={'请输入商品名称'} options={kdnDicList} allowClear />
        </Form.Item>
        <Form.Item
          label='快递单号'
          name='trackingNumber'
          rules={[{ required: true, message: '请输入快递单号' }]}
        >
          <Input placeholder={'请输入快递单号'} maxLength={25} allowClear />
        </Form.Item>
        <Form.Item
          label='发货运营'
          name='sendUserName'
          rules={[{ required: true, message: '请输入发货运营姓名' }]}
        >
          <Input placeholder={'请输入发货运营姓名'} maxLength={25} allowClear />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default AddEditModalView;
