import { InterListType, InterReqType } from '~/api/interface';
import React, { useEffect } from 'react';
import { Cascader, Form, Input, message, Modal } from 'antd';
import { Uploader } from '~/components/uploader';
import { PlusOutlined } from '@ant-design/icons';
import { MallManageAPI } from '~/api';
import { addCurriculumType, queryCurriculumInfoListType } from '~/api/interface/mallManageType';
import RichText from '~/components/richText';

// 表格数据类型
type TableType = InterListType<queryCurriculumInfoListType>;
// 请求数据的类型
type ReqType = InterReqType<addCurriculumType>;

// 传参类型
interface propType {
  title: string;
  open: boolean;
  closed: any;
  data?: TableType[0];
}

const AddEditModal: React.FC<propType> = (props) => {
  AddEditModal.defaultProps = {
    data: undefined,
  };
  // 参数
  const { title, open, closed, data } = props;
  // 课程类型列表
  const [curriculumSkillList, setCurriculumSkillList] = React.useState<
    {
      value: number;
      label: string;
      children?: Array<{
        value: number;
        label: string;
      }>;
    }[]
  >([]);
  // 表单钩子
  const [form] = Form.useForm<ReqType>();
  // 关闭弹窗
  const handleCancel = () => {
    form.resetFields();
    closed();
  };
  // 确认事件
  const handleOk = () => {
    form
      .validateFields()
      .then(async (values) => {
        // console.log('确认事件 --->', values);
        await handleSubmit(values);
      })
      .catch((err) => {
        message
          .warning({
            content: err.errorFields[0].errors[0],
          })
          .then();
      });
  };
  // 提交事件
  const handleSubmit = async (values: ReqType) => {
    const res = await MallManageAPI[data?.id ? 'updateCurriculum' : 'addCurriculum']({
      ...values,
      flightSkills: Number((values?.flightSkills as unknown as number[])?.at(-1)),
      categoriesId: Number((values?.flightSkills as unknown as number[])?.at(-1)),
      id: data?.id ? data?.id : null,
    });
    if (res && res.code === '200') {
      message.success('操作成功');
      handleCancel();
    }
  };
  // 获取课程类型
  const getCurriculumSkillList = async () => {
    const res = await MallManageAPI.queryCategoryInfoByType({
      type: 3,
    });
    if (res && res.code === '200') {
      const arr =
        res.result
          ?.filter((i) => i.categoriesInfoListDTO)
          .map((i) => ({
            label: i.name,
            value: i.directoryId,
            children: i.categoriesInfoListDTO?.map((j) => ({ label: j.name, value: j.id })),
          })) || [];
      setCurriculumSkillList(arr);
      // 回显数据
      // 加载出数据再操作
      if (!data) return;
      // console.log(data);
      // 反向找数据回显
      const flightSkillsName1 = arr?.find((i) =>
        i.children?.find((j) => j.value === data?.categoriesId),
      );
      // 回显数据
      form.setFieldsValue({
        ...data,
        flightSkills: [flightSkillsName1?.value, data?.categoriesId],
      });
    }
  };
  // componentDidMount
  useEffect(() => {
    if (!open) return;
    // 获取课程类型
    getCurriculumSkillList().then();
  }, [open]);
  return (
    <Modal
      open={open}
      title={title}
      onCancel={handleCancel}
      onOk={handleOk}
      destroyOnClose
      width={600}
    >
      <Form
        name='addForm'
        form={form}
        labelAlign='right'
        autoComplete='new-password'
        labelCol={{ span: 3 }}
        wrapperCol={{ span: 10 }}
      >
        <Form.Item
          label='课程类型'
          name='flightSkills'
          rules={[{ required: true, message: '请选择课程类型' }]}
        >
          <Cascader placeholder={'请选择课程类型'} options={curriculumSkillList} allowClear />
        </Form.Item>
        <Form.Item
          label='课程名称'
          name='curriculumName'
          rules={[{ required: true, message: '请输入课程名称' }]}
        >
          <Input placeholder={'请输入课程名称'} maxLength={20} allowClear />
        </Form.Item>
        <Form.Item
          label='课程描述'
          name='curriculumDesc'
          rules={[{ required: true, message: '请输入课程描述' }]}
        >
          <Input.TextArea placeholder={'请输入课程描述'} maxLength={20} allowClear showCount />
        </Form.Item>
        <Form.Item
          label='课程封面'
          name='surfaceUrl'
          rules={[{ required: true, message: '请上传课程封面' }]}
          style={{ marginBottom: '-40px' }}
        >
          <Uploader
            listType={'picture-card'}
            fileUpload
            fileLength={1}
            fileSize={10}
            fileType={['image/png', 'image/jpeg', 'image/jpg', 'image/gif', 'image/bmp']}
            onChange={(e) => form.setFieldValue('surfaceUrl', e[0].url)}
            defaultFileList={data?.surfaceUrl ? [{ url: data?.surfaceUrl }] : []}
          >
            <PlusOutlined />
          </Uploader>
          <div style={{ opacity: '0.68', transform: 'scale(0.86) translate(60px, -68px)' }}>
            添加图片
            <br />
            建议尺寸750*420或比例16:9，小于5M的 JPG、PNG格式图片
          </div>
        </Form.Item>
        <Form.Item
          label='课程上传'
          name='videoUrl'
          rules={[{ required: false, message: '请上传课程上传' }]}
          style={{ marginBottom: '-40px' }}
        >
          <Uploader
            listType={'picture-card'}
            fileUpload
            fileLength={1}
            fileType={['video/mp4', 'video/avi', 'video/wmv', 'video/rmvb']}
            fileSize={512}
            onChange={(e) => form.setFieldValue('videoUrl', e[0].url)}
            defaultFileList={data?.videoUrl ? [{ url: data?.videoUrl }] : []}
          >
            <PlusOutlined />
          </Uploader>
          <div style={{ opacity: '0.68', transform: 'scale(0.86) translate(60px, -68px)' }}>
            从本地上传视频
            <br />
            支持mp4，avi，wmv，mov，flv， rmvb，3gp，m4v，mkv格式； 文件最大不超过1G。
          </div>
        </Form.Item>
        <Form.Item
          label='课程详情'
          name='detailContent'
          rules={[{ required: false, message: '请填写详情' }]}
          wrapperCol={{ span: 20 }}
        >
          <RichText
            richTextContent={form.getFieldValue('detailContent')}
            onChange={(e) => form.setFieldValue('detailContent', e)}
            height={250}
          />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default AddEditModal;
