import { NButton, NUpload, UploadCustomRequestOptions, useMessage } from "naive-ui";
import { defineComponent, reactive, ref } from "vue";
import styles from "./index.module.less";
import iconUpload from "../upload-to-tasks/images/icon-upload.png";
import { getUploadSign, onFileUpload, onOnlyFileUpload } from "/src/utils/oss-file-upload";
import { api_musicalScoreConversionRecordSave } from "../../api";
import { uploadState, eventGlobal } from "../upload-to-tasks/state";
import requestOrigin from "umi-request";

export default defineComponent({
  name: "upload-file",
  setup() {
    const message = useMessage();
    const inputRef = ref();
    const state = reactive({
      fileList: [] as any,
      uploading: false,
    }) as any;

    /** 选择文件 */
    const handleSelectFiles = async (e: Event) => {
      state.uploading = true;
      try {
        const files = (e.target as HTMLInputElement).files || [];
        // console.log("🚀 ~ files:", files);
        if (files.length > 5) {
          message.error("最多选择5个文件");
          state.uploading = false;

          return;
        }

        for (let index = 0; index < files.length; index++) {
          const file = files[index];
          const type = file.type.includes("png") || file.type.includes("jpg") || file.type.includes("jpeg") ? "IMG" : file.type.includes("xml") ? "XML" : file.type.includes("application/pdf") ? "pdf" : "other";
          if (type === "other") {
            message.error(`文件格式不支持`);
            state.uploading = false;
            return false;
          }
          let isLt2M = true;
          const size = 50; //type === "IMG" ? 5 : type === "XML" ? 20 : 500;
          if (size) {
            isLt2M = file.size / 1024 / 1024 < size;
            if (!isLt2M) {
              const typeStr = type === "IMG" ? "图片" : type === "XML" ? "XMl" : "";
              message.error(`${typeStr}大小不能超过${size}M`);
              state.uploading = false;
              return false;
            }
          }
        }

        for (let index = 0; index < files.length; index++) {
          const file = files[index];
          const name = file.name;
          // const suffix = name.slice(name.lastIndexOf("."));
          const fileName = name;
          const obj = {
            filename: fileName,
            bucketName: "gyt",
            postData: {
              filename: fileName,
              acl: "public-read",
              key: fileName,
              unknowValueField: [],
            },
          };
          const { data } = await getUploadSign(obj);

          const fileParams = {
            policy: data.policy,
            signature: data.signature,
            key: fileName,
            KSSAccessKeyId: data.kssAccessKeyId,
            acl: "public-read",
            name: fileName,
            file: file,
          };
          onOnlyFileUpload("action", fileParams).then(async (res: any) => {
            let status = true;
            const type = file.type.includes("png") || file.type.includes("jpg") || file.type.includes("jpeg") ? "IMG" : file.type.includes("xml") ? "XML" : file.type.includes("application/pdf") ? "pdf" : "other";
            if (type === "XML") {
              console.log(file, "files");
              try {
                const result = await requestOrigin.get(res, {
                  mode: "cors",
                });
                // console.log(result, "result");
                let abc: any = new DOMParser().parseFromString(result, "text/xml");
                const title = abc.querySelector("parsererror");
                console.log(abc, "abc", title);
                status = title ? false : true;
              } catch {
                //
              }
            }
            // 判断xml是否生成失败
            const result = await api_musicalScoreConversionRecordSave([{ fileName, fileUrl: res, status: status ? null : "FAIL" }]);
            uploadState.uploadList.push({
              fileName,
              fileUrl: res,
              musicSheetCreationId: "",
              id: result.data[0],
              status: "WAITING",
            });

            eventGlobal.emit("resetUploadTask");
          });
        }

        // 上传完成之后清空数据
        inputRef.value.value = "";
      } catch {}

      state.uploading = false;
    };

    return () => (
      <div class={styles.uploadFile}>
        <div>
          <NButton
            type="primary"
            loading={state.uploading}
            onClick={() => {
              inputRef.value.click();
            }}
          >
            <img src={iconUpload} class={styles.iconUpload} />
            上传曲谱
          </NButton>
          <input style={{ display: "none" }} ref={inputRef} type="file" accept=".jpg,.png,.jpeg,.xml,application/pdf" multiple onChange={handleSelectFiles} />
        </div>
        <p class={styles.tips}>(仅支持上传.PDF、JPG、PNG、XML格式文件)</p>
      </div>
    );
  },
});
