import React, { useEffect } from 'react';
import { Form, Input, message, Modal, ModalProps } from 'antd';
import { InterDataType, InterReqType } from '~/api/interface';
import {
  addCurriculumClassifyType,
  selectCurriculumClassifyType,
} from '~/api/interface/pilotTrainType';
import { PlusOutlined } from '@ant-design/icons';
import { Uploader } from '~/components/uploader';
import { PilotTrainAPI } from '~/api';

// 类型
type customProps = {
  data?: InterDataType<selectCurriculumClassifyType>[0];
  onCancel?: () => void;
  isSub: boolean;
};
// 表单类型
type ReqType = InterReqType<addCurriculumClassifyType>;

const AddEditModalView: React.FC<ModalProps & customProps> = (props) => {
  // 表单钩子
  const [form] = Form.useForm<ReqType>();
  // 确认事件
  const handleOk = () => {
    form
      .validateFields()
      .then(async (values) => {
        // console.log('确认事件 --->', props?.data);
        if (!props?.isSub) {
          await handleSubmitMain(values);
        } else {
          await handleSubmitSecond(values);
        }
      })
      .catch(async (err) => {
        message.warning({
          content: err.errorFields[0].errors[0],
        });
      });
  };
  // 主分类提交数据
  const handleSubmitMain = async (values: ReqType) => {
    const res = await PilotTrainAPI[
      props?.data?.id ? 'updateCurriculumClassify' : 'addCurriculumClassify'
    ]({
      ...props?.data,
      ...values,
    });
    if (res && res.code === '200') {
      handleCancel();
      message.success('操作成功');
      // console.log('提交数据 --->', res);
    }
  };
  // 子分类提交数据
  const handleSubmitSecond = async (values: ReqType) => {
    const res = await PilotTrainAPI[
      !props?.data?.twoCourseId ? 'addCurriculumClassify' : 'updateCurriculumClassify'
    ]({
      ...props?.data,
      ...values,
    });
    if (res && res.code === '200') {
      handleCancel();
      message.success('操作成功');
      // console.log('提交数据 --->', res);
    }
  };
  // 关闭弹窗
  const handleCancel = () => {
    form.resetFields();
    props.onCancel?.();
  };
  // 组件挂载
  useEffect(() => {
    if (!props.open || !props.data) return;
    // 新增子分类时不执行
    if (props?.isSub) return;
    form.setFieldsValue(props.data);
  }, [props]);
  return (
    <Modal {...props} destroyOnClose onOk={handleOk}>
      <Form
        name='addForm'
        form={form}
        labelAlign='right'
        autoComplete='new-password'
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 12 }}
        style={{ marginBottom: '25px' }}
      >
        <Form.Item
          label='分类名称'
          name='name'
          rules={[{ required: true, message: '请输入分类名称' }]}
        >
          <Input placeholder={'请输入分类名称'} maxLength={20} allowClear />
        </Form.Item>
        {!props?.isSub && (
          <Form.Item
            label='分类图标'
            name='classifyUrl'
            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('classifyUrl', e[0].url)}
              defaultFileList={props?.data?.classifyUrl ? [{ url: props?.data?.classifyUrl }] : []}
            >
              <PlusOutlined />
            </Uploader>
          </Form.Item>
        )}
        <Form.Item
          label='分类描述'
          name='classifyDesc'
          rules={[{ required: false, message: '请输入分类描述' }]}
        >
          <Input.TextArea placeholder={'请输入分类描述'} maxLength={50} allowClear showCount />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default AddEditModalView;
