import React, { FC, useEffect, useState } from 'react';
import { Form, Input, Modal, message, ModalProps } from 'antd';
import { Uploader } from '~/components/uploader';
import { UploadOutlined } from '@ant-design/icons';
import { ProduceManageAPI } from '~/api';
import { InterDataType } from '~/api/interface';
import { ProductSpecListType } from '~/api/interface/produceManageType';

//产品规格返回类型
type specType = InterDataType<ProductSpecListType>['list'];

interface PropsType {
  onCancel: () => void;
  onOk: () => void;
  data: specType[0] | undefined;
  productSkuId: number;
}

const AddOrEditProduceSpecModal: FC<ModalProps & PropsType> = ({
  open,
  onCancel,
  data,
  onOk,
  productSkuId,
}) => {
  // 表格事件
  const [form] = Form.useForm();
  //文件列表
  const [fileList, setFileList] = useState<
    {
      id: number;
      name: string;
      uid: number;
      url: string;
    }[]
  >([]);
  // 关闭弹窗
  const handleClosed = () => {
    form.resetFields();
    setFileList([]);
    onCancel();
  };
  // 触发表单验证
  const handleSubmit = () => {
    form
      .validateFields()
      .then((values) => {
        const obj = { ...data, ...values, productSkuId };
        ProduceManageAPI[!obj.id ? 'addProductSpec' : 'editProductSpec'](obj).then(({ code }) => {
          if (code === '200') {
            message.success('操作成功');
            form.resetFields();
            setFileList([]);
            onOk();
          }
        });
      })
      .catch((err) => {
        message.warning(err.errorFields[0].errors[0]).then();
      });
  };
  //上传成功
  const uploadSuccess = (
    value: {
      id: number;
      name: string;
      uid: number;
      url: string;
    }[],
  ) => {
    form.setFieldsValue({
      specImage: value[0].url,
    });
  };
  // componentsDidMounted
  useEffect(() => {
    if (data) {
      form.setFieldsValue({
        ...data,
      });
      setFileList([
        {
          uid: Math.random(),
          name: 'img',
          id: Math.random(),
          url: data.specImage,
        },
      ]);
    } else {
      form.resetFields();
      setFileList([]);
    }
  }, [data]);
  return (
    <div>
      <Modal
        open={open}
        title='新增'
        onCancel={handleClosed}
        onOk={handleSubmit}
        destroyOnClose
        width={800}
      >
        <Form
          name='form'
          form={form}
          layout='horizontal'
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 16 }}
        >
          <Form.Item
            name='specName'
            label='规格名称'
            rules={[{ required: true, message: '请输入规格名称' }]}
          >
            <Input placeholder='请输入规格名称' allowClear maxLength={30} />
          </Form.Item>
          <Form.Item
            name='specImage'
            label='规格图片'
            rules={[{ required: true, message: '请上传规格图片' }]}
          >
            <Uploader
              fileUpload
              listType='picture-card'
              onChange={uploadSuccess}
              defaultFileList={fileList}
            >
              <UploadOutlined />
            </Uploader>
          </Form.Item>
          <Form.Item
            name='partNo'
            label='产品料号'
            rules={[{ required: true, message: '请输入产品料号' }]}
          >
            <Input placeholder='请输入产品料号' allowClear maxLength={50} />
          </Form.Item>
          <Form.Item
            name='versionDesc'
            label='版本描述'
            rules={[{ required: true, message: '请输入版本描述' }]}
          >
            <Input placeholder='请输入版本描述' allowClear maxLength={50} />
          </Form.Item>
        </Form>
      </Modal>
    </div>
  );
};
export default AddOrEditProduceSpecModal;
