import { computed, defineComponent, onMounted, onUnmounted, reactive } from "vue";
import styles from "./index.module.less";
import iconQuestion from "./images/icon-question.png";
import iconArrow from "./images/icon-arrow.png";
import iconSuccess from "./images/icon-success.png";
import iconError from "./images/icon-error.png";
import iconWarning from "./images/icon-warning.png";
import iconClose from "./images/icon-close.png";
import iconCloseRed from "./images/icon-close-red.png";
import { NScrollbar, NSpin } from "naive-ui";
import { eventGlobal, getUploadCatch, saveUploadCatch, uploadState } from "./state";
import { api_musicalScoreConversionRecordPage, api_musicalScoreConversionRecordRemove } from "../../api";
import { debounce } from "lodash";

export default defineComponent({
  name: "upload-to-tasks",
  setup() {
    // 等待中 WAITING 转换中:CONVERSION, 转换成功:SUCCESS, 转换失败:FAIL
    const state = reactive({
      showUploadList: false,
      timer: null as any,
      functionTimer: null as any,
    });

    /** 是否有等待转换数据 */
    const isWaiting = computed(() => {
      const list = uploadState.uploadList || [];
      let count = 0;
      list.forEach((item: any) => {
        if (item.status === "CONVERSION" || item.status === "WAITING") {
          count++;
        }
      });
      return count > 0 ? true : false;
    });

    /** 统计任务数 */
    const taskStatNums = computed(() => {
      const list = uploadState.uploadList || [];
      const nums = {
        success: 0,
        error: 0,
        waiting: 0,
      };
      list.forEach((item: any) => {
        if (item.status === "CONVERSION" || item.status === "WAITING") {
          nums.waiting++;
        } else if (item.status === "SUCCESS") {
          nums.success++;
        } else if (item.status === "FAIL") {
          nums.error++;
        }
      });

      return nums;
    });

    const getRecordList = async (type?: string) => {
      try {
        const params: any = {
          page: 1,
          rows: -1,
        };
        if (type === "ids") {
          const ids: string[] = [];
          uploadState.uploadList.forEach((item: any) => {
            // if (item.status === "CONVERSION" || item.status === "WAITING") {
            ids.push(item.id);
            // }
          });
          params.idList = ids;
        } else {
          params.statusList = ["WAITING", "CONVERSION"];
        }
        const { data } = await api_musicalScoreConversionRecordPage(params);
        const temps = data.rows || [];

        const result: any = [];
        let tempSuccess = 0;
        temps.forEach((item: any) => {
          result.push({
            id: item.id,
            musicSheetCreationId: item.musicSheetCreationId,
            status: item.status,
            fileName: item.fileName,
            fileUrl: item.fileUrl,
          });
          if (item.status === "SUCCESS") {
            tempSuccess++;
          }
        });

        if (taskStatNums.value.success !== tempSuccess) {
          eventGlobal.emit("resetList");
        }

        uploadState.uploadList = result;

        // 储存
        saveUploadCatch(result);
      } catch {
        //
      }
    };

    const onOperation = async (item: any, type: string) => {
      try {
        if (type === "remove") {
          await api_musicalScoreConversionRecordRemove(item.id);
          const index = uploadState.uploadList.findIndex((child: any) => child.id === item.id);
          uploadState.uploadList.splice(index, 1);
          saveUploadCatch();
          return;
        } else if (type === "look") {
          window.parent.postMessage(
            {
              api: "notation_open",
              url: `${location.origin}/notation/#/?v=${Date.now()}&id=${item.musicSheetCreationId}`,
            },
            "*"
          );
        }
      } catch {}
    };

    const __init = () => {
      state.timer = setInterval(() => {
        if (isWaiting.value) {
          getRecordList("ids");
        }
      }, 5000);
    };
    const getListDebounce = () => {
      debounce(() => getRecordList("ids"), 500);
    };

    onMounted(() => {
      // 获取丝缓存数据
      const taskUploadMusic = getUploadCatch();
      if (taskUploadMusic.length > 0) {
        uploadState.uploadList = taskUploadMusic;
        getRecordList("ids");
      } else {
        getRecordList();
      }

      // 上传文件成功之后刷新列表
      eventGlobal.on("resetUploadTask", getListDebounce);

      // 开启定时器
      __init();
    });

    onUnmounted(() => {
      eventGlobal.off("resetUploadTask", getListDebounce);
      clearInterval(state.timer);
    });
    return () => (
      <div class={styles.uploadToTasks} style={{ display: uploadState.uploadList.length > 0 ? "block" : "none" }}>
        <NScrollbar class={styles.uploadList} style={{ display: state.showUploadList ? "block" : "none" }}>
          {uploadState.uploadList.map((item: any) => (
            <>
              {item.status === "SUCCESS" && (
                <div class={[styles.uploadItem, styles.uploadSuccess]}>
                  <div class={styles.info}>
                    <img class={styles.icon} src={iconSuccess} />
                    <p class={styles.message}>{item.fileName}</p>
                  </div>

                  <div class={styles.status} onClick={() => onOperation(item, "look")}>
                    <span class={styles.text}>点击查看</span>
                  </div>
                </div>
              )}
              {item.status === "FAIL" && (
                <div class={[styles.uploadItem, styles.uploadError]}>
                  <div class={styles.info}>
                    <img class={styles.icon} src={iconError} />
                    <p class={styles.message}>{item.fileName}</p>
                  </div>

                  <div class={styles.status} onClick={() => onOperation(item, "remove")}>
                    <img class={styles.iconClose} src={iconCloseRed} />
                  </div>
                </div>
              )}

              {item.status === "WAITING" && (
                <div class={[styles.uploadItem, styles.uploadWaiting]}>
                  <div class={styles.info}>
                    <img class={styles.icon} src={iconWarning} />
                    <p class={styles.message}>{item.fileName}</p>
                  </div>

                  <div class={styles.status} onClick={() => onOperation(item, "remove")}>
                    <img class={styles.iconClose} src={iconClose} />
                    <span class={styles.text}>等待上传</span>
                  </div>
                </div>
              )}
              {item.status === "CONVERSION" && (
                <div class={[styles.uploadItem, styles.uploadLoading]}>
                  <div class={styles.info}>
                    <NSpin class={styles.icon} />
                    <p class={styles.message}>{item.fileName}</p>
                  </div>

                  <div class={styles.status} onClick={() => onOperation(item, "remove")}>
                    <img class={styles.iconClose} src={iconClose} />
                  </div>
                </div>
              )}
            </>
          ))}
        </NScrollbar>
        <div onClick={() => (state.showUploadList = !state.showUploadList)}>
          {isWaiting.value ? (
            <div class={styles.loadingSection}>
              <div class={styles.loadingText}>
                <img class={styles.iconQuestion} src={iconQuestion} />
                <p>
                  剩余<span class={styles.error}>{taskStatNums.value.waiting}</span>个文件正在上传中…
                </p>
              </div>

              <img class={[styles.arrow, state.showUploadList && styles.arrowDown]} src={iconArrow} />
            </div>
          ) : (
            <div class={styles.succesSection}>
              <p>
                上传完成，<span class={styles.success}>成功{taskStatNums.value.success}</span> <span class={styles.error}>失败{taskStatNums.value.error}</span>
              </p>
              <img class={[styles.arrow, state.showUploadList && styles.arrowDown]} src={iconArrow} />
            </div>
          )}
        </div>
      </div>
    );
  },
});
