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

// 请求的表单类型
type ReqType = InterReqType<updateMallType>;

const AddEditModalView: React.FC<ModalProps & { data: ReqType; onCancel: () => void }> = ({
  open,
  title,
  onCancel,
  data,
}) => {
  // 表单数据
  const [form] = Form.useForm<ReqType>();
  // 店铺图片列表
  const [imageList, setImageList] = useState<any>([]);
  // 店铺图片列表上传
  const imageListChange = (value: any) => {
    setImageList(value);
    form.setFieldValue('goodsUrl', JSON.stringify(value?.map((i: { url: string }) => i?.url)));
  };
  // 关闭弹窗
  const handleCancel = () => {
    form.resetFields();
    setImageList([]);
    onCancel?.();
  };
  // 确认事件
  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[data?.id ? 'updateMall' : 'insertMall']({
      ...data,
      ...values,
    });
    if (res && res.code === '200') {
      message.success(data?.id ? '修改成功' : '添加成功');
      handleCancel();
    }
  };
  // 组件挂载
  useEffect(() => {
    if (!data) return;
    form.setFieldsValue(data);
    try {
      setImageList(
        (JSON.parse(data.goodsUrl || `[]`) || [])?.map((i: { url: string }, j: number) => ({
          id: j,
          url: i,
        })),
      );
    } catch (e) {
      setImageList([]);
    }
    // console.log('组件挂载 --->', data);
  }, [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 />
        </Form.Item>
        <Form.Item
          label='商品图片'
          name='goodsUrl'
          rules={[{ required: true, message: '请上传商品图片' }]}
        >
          <Uploader
            fileUpload
            listType='picture-card'
            defaultFileList={imageList}
            onChange={imageListChange}
            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'} />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default AddEditModalView;
