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

// 表格数据类型
type TableType = InterListType<queryCurriculumInfoListType>;
// 请求数据的类型
type ReqType = InterReqType<addCurriculumType>;
// 列表类型
type ListType = Array<
  InterDataType<selectCurriculumClassifyType>[0] & {
    children?: InterDataType<selectCurriculumClassifyType>;
  }
>;
// 课程类型列表
const courseAttributeList = [
  { label: '免费', value: 0 },
  { label: '积分兑换', value: 1 },
  { label: '付费', value: 2 },
];

// 传参类型
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 [curriculumClassifyList, setCurriculumClassifyList] = useState<ListType>();
  // 当前选择的课程类型
  const [courseAttributeSelect, setCourseAttributeSelect] = useState<number>(0);
  // 表单钩子
  const [form] = Form.useForm<ReqType>();
  // 封面图文件
  const [imageFileUrl, setImageFileUrl] = useState<string>();
  // 视频文件
  const [videoFileUrl, setVideoFileUrl] = useState<string>();
  // 关闭弹窗
  const handleCancel = () => {
    setImageFileUrl(undefined);
    setVideoFileUrl(undefined);
    form.resetFields();
    setCourseAttributeSelect(0);
    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 oneCourseId = curriculumClassifyList?.find((i) => i.id === values?.courseId?.[0]);
    const twoCourseId = oneCourseId?.children?.find((i) => i.id === values?.courseId?.[1]);
    const res = await MallManageAPI[data?.id ? 'updateCurriculum' : 'addCurriculum']({
      ...values,
      oneCourseId: Number(oneCourseId?.oneCourseId),
      twoCourseId: Number(twoCourseId?.twoCourseId),
      id: data?.id ? data?.id : undefined,
    });
    if (res && res.code === '200') {
      message.success('操作成功');
      handleCancel();
    }
  };
  // 获取课程分类
  const getCurriculumClassify = async () => {
    const res = await PilotTrainAPI.selectCurriculumClassify();
    if (res && res.code === '200') {
      const list = res.result
        ?.filter((i) => !i.twoCourseId)
        ?.map((i) => {
          const children = res.result?.filter(
            (k) => k.oneCourseId === i.oneCourseId && k.twoCourseId,
          );
          return {
            ...i,
            children: children?.length ? children : undefined,
          };
        });
      setCurriculumClassifyList(list);
      // 回显数据
      // 加载出数据再操作
      if (!data) return;
      // console.log(data);
      const oneCourseId = list?.find((i) => i.oneCourseId === data?.oneCourseId);
      const twoCourseId = oneCourseId?.children?.find((i) => i.twoCourseId === data?.twoCourseId);
      // 回显数据
      form.setFieldsValue({
        ...data,
        courseId: [oneCourseId?.id, twoCourseId?.id] as any,
      });
      setCourseAttributeSelect(data?.courseAttribute || 0);
    }
  };
  // componentDidMount
  useEffect(() => {
    if (!open) return;
    // 获取课程类型
    getCurriculumClassify().then();
  }, [open]);
  return (
    <Modal
      open={open}
      title={title}
      onCancel={handleCancel}
      onOk={handleOk}
      destroyOnClose
      width={600}
    >
      <Form
        name='addForm'
        form={form}
        labelAlign='left'
        autoComplete='new-password'
        labelCol={{ span: 3 }}
        wrapperCol={{ span: 10 }}
      >
        <Form.Item
          label='课程类型'
          name='courseId'
          rules={[{ required: true, message: '请选择课程类型' }]}
        >
          <Cascader
            placeholder={'请选择课程类型'}
            options={curriculumClassifyList}
            allowClear
            fieldNames={{ label: 'name', value: 'id' }}
          />
        </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' }}
          wrapperCol={{ span: 12 }}
        >
          <div style={{ minHeight: '100px' }}>
            <Uploader
              listType={'picture-card'}
              fileUpload
              fileLength={1}
              fileSize={10}
              fileType={['image/png', 'image/jpeg', 'image/jpg', 'image/gif', 'image/bmp']}
              onChange={(e) => {
                setImageFileUrl(e[0]?.url || undefined);
                form.setFieldValue('surfaceUrl', e[0]?.url);
              }}
              defaultFileList={
                imageFileUrl || data?.surfaceUrl ? [{ url: imageFileUrl || data?.surfaceUrl }] : []
              }
            >
              <PlusOutlined />
            </Uploader>
            <div
              style={{
                opacity: '0.68',
                position: 'absolute',
                top: 0,
                right: 0,
                fontSize: '10px',
                width: '200px',
              }}
            >
              添加图片
              <br />
              建议尺寸750*420或比例16:9，小于5M的 JPG、PNG格式图片
            </div>
          </div>
        </Form.Item>
        <Form.Item
          label='课程视频'
          name='videoUrl'
          rules={[{ required: true, message: '请上传课程视频' }]}
          style={{ marginBottom: '-40px' }}
          wrapperCol={{ span: 12 }}
        >
          <div style={{ minHeight: '100px' }}>
            <Uploader
              listType={'picture-card'}
              fileUpload
              fileLength={1}
              fileType={['video/mp4', 'video/avi', 'video/wmv', 'video/rmvb']}
              fileSize={512}
              onChange={(e) => {
                setVideoFileUrl(e[0]?.url || undefined);
                form.setFieldValue('videoUrl', e[0]?.url);
              }}
              defaultFileList={
                videoFileUrl || data?.videoUrl ? [{ url: videoFileUrl || data?.videoUrl }] : []
              }
            >
              <PlusOutlined />
            </Uploader>
            <div
              style={{
                opacity: '0.68',
                position: 'absolute',
                top: 0,
                right: 0,
                fontSize: '10px',
                width: '200px',
              }}
            >
              从本地上传视频
              <br />
              支持mp4，avi，wmv，mov，flv， rmvb，3gp，m4v，mkv格式； 文件最大不超过1G。
            </div>
          </div>
        </Form.Item>
        <Form.Item
          label='课程属性'
          name='courseAttribute'
          rules={[{ required: true, message: '请选择课程属性' }]}
          wrapperCol={{ span: 20 }}
          initialValue={0}
        >
          <Radio.Group
            options={courseAttributeList}
            onChange={(e) => setCourseAttributeSelect(e?.target?.value)}
          />
        </Form.Item>
        {courseAttributeSelect === 1 && (
          <Form.Item
            label='课程积分'
            name='requireIntegral'
            rules={[{ required: true, message: '请输入课程积分' }]}
            wrapperCol={{ span: 20 }}
            initialValue={1}
          >
            <InputNumber min={1} max={999999} precision={2} />
          </Form.Item>
        )}
        {courseAttributeSelect === 2 && (
          <Form.Item
            label='课程金额'
            name='requireAmout'
            rules={[{ required: true, message: '请输入课程金额' }]}
            wrapperCol={{ span: 20 }}
            initialValue={1}
          >
            <InputNumber min={1} max={999999} precision={2} />
          </Form.Item>
        )}
        <Form.Item
          label='设置为热门课程'
          name='isHot'
          rules={[{ required: true, message: '请选择是否设置为热门课程' }]}
          labelCol={{ span: 5 }}
          initialValue={0}
        >
          <Radio.Group
            options={[
              { value: 0, label: '否' },
              { value: 1, label: '是' },
            ]}
          />
        </Form.Item>
        <Form.Item
          label='课程详情'
          name='detailContent'
          rules={[{ required: false, message: '请填写详情' }]}
          wrapperCol={{ span: 20 }}
        >
          <RichText
            richTextContent={form.getFieldValue('detailContent') || data?.detailContent}
            onChange={(e) => form.setFieldValue('detailContent', e)}
            height={250}
          />
        </Form.Item>
      </Form>
    </Modal>
  );
};

export default AddEditModal;
