import React, { useEffect } from 'react';
import { Form, Input, message, Modal, ModalProps } from 'antd';
import { InterListType, InterReqType } from '~/api/interface';
import { industryListPagesType, industryUpdateType } from '~/api/interface/categoryManage';
import { PlusOutlined } from '@ant-design/icons';
import { Uploader } from '~/components/uploader';
import { CategoryManageAPI } from '~/api';

// 列表的类型
type TableType = InterListType<industryListPagesType>;
// 表单参数
type ReqType = InterReqType<industryUpdateType>;
// 参数类型
interface selfProps {
  data?: TableType[0];
  onCancel: () => void;
}

const AddEditModalView: React.FC<ModalProps & selfProps> = ({ open, title, onCancel, data }) => {
  // 表格数据类型
  const [form] = Form.useForm<ReqType>();
  // 关闭事件
  const handleCancel = () => {
    form.resetFields();
    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 CategoryManageAPI[data?.id ? 'industryUpdate' : 'industryInsert']({
      ...values,
      id: data?.id || undefined,
      saleState: 1,
    });
    if (res && res.code === '200') {
      message.success('操作成功').then();
      handleCancel();
    }
  };
  // componentDidMount
  useEffect(() => {
    if (!open) return;
    if (!data) return;
    form.setFieldsValue(data);
    // console.log('data --->', data);
  }, [open]);
  return (
    <Modal title={title} open={open} onCancel={handleCancel} onOk={handleOk} destroyOnClose>
      <Form form={form} labelAlign='right' labelCol={{ span: 4 }} wrapperCol={{ span: 10 }}>
        <Form.Item
          label='分类名称'
          name='typeName'
          rules={[{ required: true, message: '请输入分类名称' }]}
        >
          <Input placeholder='请输入分类名称' maxLength={15} allowClear />
        </Form.Item>
        <Form.Item
          label='分类图标'
          name='typeImg'
          rules={[{ required: true, message: '请上传分类图标' }]}
        >
          <Uploader
            listType={'picture-card'}
            fileUpload
            fileLength={1}
            fileSize={10}
            fileType={['image/png', 'image/jpeg', 'image/jpg', 'image/gif', 'image/bmp']}
            onChange={(e) => form.setFieldValue('typeImg', e.at(0) ? e.at(0)?.url : undefined)}
            defaultFileList={data?.typeImg ? [{ url: data?.typeImg }] : []}
          >
            <PlusOutlined />
          </Uploader>
        </Form.Item>
        <Form.Item
          label='分类描述'
          name='description'
          rules={[{ required: true, message: '请输入分类描述' }]}
        >
          <Input placeholder='请输入分类名称' maxLength={25} allowClear />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default AddEditModalView;
