import { Checkbox } from "antd";
import {
  forwardRef,
  useCallback,
  useEffect,
  useImperativeHandle,
  useMemo,
  useState,
} from "react";
import { CheckboxValueType } from "antd/lib/checkbox/Group";
import style from "./index.module.scss";
import { DAGE_FILE_CHECKBOX_OPTIONS } from "./constants";
import { DageFileCheckboxMethods, DageFileCheckboxProps } from "./types";
import {
  DageFileResponseType,
  DageUpload,
  DageUploadType,
} from "../DageUpload";

export const DageFileCheckbox = forwardRef<
  DageFileCheckboxMethods,
  DageFileCheckboxProps
>(({ value, action, disabled, onChange, onFileChange }, ref) => {
  const checkboxVal = useMemo(() => (value ? value.split(",") : []), [value]);
  const [modelFiles, setModelFiles] = useState<DageFileResponseType[]>([]);
  const [imgFiles, setImgFiles] = useState<DageFileResponseType[]>([]);
  const [videoFiles, setVideoFiles] = useState<DageFileResponseType[]>([]);
  const [audioFiles, setAudioFiles] = useState<DageFileResponseType[]>([]);

  useImperativeHandle(ref, () => ({
    async validate() {
      if (hasModel && !modelFiles.length) {
        throw new Error("模型文件不能为空");
      } else if (hasImg && !imgFiles.length) {
        throw new Error("图片文件不能为空");
      } else if (hasAudio && !videoFiles.length) {
        throw new Error("视频文件不能为空");
      } else if (hasVideo && !audioFiles.length) {
        throw new Error("音频文件不能为空");
      }
    },
    setFileList(list) {
      const stack: Record<string, DageFileResponseType[]> = {
        [DageUploadType.MODEL]: [],
        [DageUploadType.IMG]: [],
        [DageUploadType.AUDIO]: [],
        [DageUploadType.VIDEO]: [],
      };

      list.forEach((item) => {
        stack[item.dType].push(item);
      });

      Object.keys(stack).forEach((key) => {
        const list = stack[key];
        if (!list.length) return;
        switch (key) {
          case DageUploadType.MODEL:
            setModelFiles(list);
            break;
          case DageUploadType.IMG:
            setImgFiles(list);
            break;
          case DageUploadType.AUDIO:
            setAudioFiles(list);
            break;
          case DageUploadType.VIDEO:
            setVideoFiles(list);
            break;
        }
      });
    },
  }));

  const hasModel = useMemo(
    () => checkboxVal.includes(DageUploadType.MODEL),
    [checkboxVal]
  );
  const hasImg = useMemo(
    () => checkboxVal.includes(DageUploadType.IMG),
    [checkboxVal]
  );
  const hasAudio = useMemo(
    () => checkboxVal.includes(DageUploadType.AUDIO),
    [checkboxVal]
  );
  const hasVideo = useMemo(
    () => checkboxVal.includes(DageUploadType.VIDEO),
    [checkboxVal]
  );

  const handleCheckbox = useCallback(
    (val: CheckboxValueType[]) => {
      onChange?.(val.join(","));
    },
    [onChange]
  );

  const handleFileChange = useCallback(
    (
      method: (v: DageFileResponseType[]) => void,
      list: DageFileResponseType[]
    ) => {
      console.log(list);
      method(list);
    },
    []
  );

  useEffect(() => {
    onFileChange?.([
      ...(hasModel ? modelFiles : []),
      ...(hasImg ? imgFiles : []),
      ...(hasVideo ? videoFiles : []),
      ...(hasAudio ? audioFiles : []),
    ]);
  }, [
    modelFiles,
    imgFiles,
    videoFiles,
    audioFiles,
    hasModel,
    hasImg,
    hasVideo,
    hasAudio,
    onFileChange,
  ]);

  return (
    <div className={style.dageFileCheckbox}>
      <Checkbox.Group
        disabled={disabled}
        className={style.dageFileCheckboxGroup}
        value={checkboxVal}
        options={DAGE_FILE_CHECKBOX_OPTIONS}
        onChange={handleCheckbox}
      />

      <div className={style.dageFileContainer}>
        {hasModel && (
          <div className={style.dageFileItem}>
            <span>模型：</span>
            <DageUpload
              disabled={disabled}
              value={modelFiles}
              action={action}
              type={DageUploadType.MODEL}
              maxCount={1}
              maxSize={500}
              tips="仅支持4dage格式的模型文件，大小不能超过500M"
              onChange={handleFileChange.bind(undefined, setModelFiles)}
            />
          </div>
        )}
        {hasImg && (
          <div className={style.dageFileItem}>
            <span>图片：</span>
            <DageUpload
              disabled={disabled}
              value={imgFiles}
              action={action}
              type={DageUploadType.IMG}
              maxCount={9}
              maxSize={20}
              tips="支持png、jpg和jpeg格式；最大20M，最多9张"
              onChange={handleFileChange.bind(undefined, setImgFiles)}
            />
          </div>
        )}
        {hasAudio && (
          <div className={style.dageFileItem}>
            <span>音频：</span>
            <DageUpload
              disabled={disabled}
              value={audioFiles}
              action={action}
              type={DageUploadType.AUDIO}
              maxCount={1}
              maxSize={10}
              tips="仅支持MP3格式的音频文件，大小不得超过10MB"
              onChange={handleFileChange.bind(undefined, setAudioFiles)}
            />
          </div>
        )}
        {hasVideo && (
          <div className={style.dageFileItem}>
            <span>视频：</span>
            <DageUpload
              disabled={disabled}
              value={videoFiles}
              action={action}
              type={DageUploadType.VIDEO}
              maxCount={1}
              maxSize={500}
              tips="仅支持MP4格式的视频文件，大小不得超过500MB"
              onChange={handleFileChange.bind(undefined, setVideoFiles)}
            />
          </div>
        )}
      </div>
    </div>
  );
});

export * from "./types";
export * from "./constants";
