import { defineComponent, nextTick, onMounted, onUnmounted, reactive, ref, watch } from "vue";
import styles from "./index.module.less";
import { NRadio, NSpace, NSpin, useDialog } from "naive-ui";
import { getImage } from "../home/images";
import TheCreate from "./component/the-create";
import { storeData } from "/src/store";
import { api_musicSheetCreationPage, api_musicSheetCreationRemove } from "../api";
import ABCJS from "abcjs";
import { usePageVisibility } from "@vant/use";
import UploadToResources from "../component/upload-to-resources";
import { getQuery } from "/src/utils/queryString";
import { browser } from "/src/utils";
import UploadToTasks from "../component/upload-to-tasks";
import UploadFile from "../component/upload-file";
import { eventGlobal, saveUploadCatch, uploadState } from "../component/upload-to-tasks/state";
import { formateAbc, renderMeasures } from "../home/runtime";
import requestOrigin from "umi-request";

export default defineComponent({
  name: "Create",
  setup() {
    const query = getQuery();
    const dialog = useDialog();
    console.log(storeData.user);
    const forms = reactive({
      teacherId: storeData.user.id,
      page: 1,
      keyword: "",
      rows: 20,
    });
    const data = reactive({
      list: [] as any[],
      addShow: query.addShow ? true : false,
      loading: false,
      finish: false,
      isCreated: false,
      uploadShow: false,
      item: {} as any,
    });
    const getList = async () => {
      data.loading = true;
      const res = await api_musicSheetCreationPage({ ...forms });
      if (res?.code == 200) {
        if (data.isCreated) {
          data.isCreated = false;
          handleOpenNotaion(res.data.rows[0]);
        }
        data.list = data.list.concat(res.data.rows);
        data.finish = res.data.rows.length < forms.rows;
      }
      data.loading = false;
    };
    const handleReset = () => {
      forms.page = 1;
      data.finish = false;
      data.list = [];
      getList();
    };
    const pageVisibility = usePageVisibility();
    watch(pageVisibility, (val) => {
      if (val === "visible") {
        handleReset();
      }
    });

    const handleDelte = (item: any) => {
      const checked = ref(true);
      dialog.warning({
        autoFocus: false,
        class: "deleteDialog",
        title: "删除曲谱",
        content: () => (
          <div onClick={() => (checked.value = !checked.value)}>
            <NRadio checked={checked.value}>同步删除我的资源中的该曲目</NRadio>
          </div>
        ),
        // content: () => <div>确认删除当前曲谱?</div>,
        positiveText: "取消",
        positiveButtonProps: {
          type: "default",
        },
        negativeText: "删除",
        negativeButtonProps: {
          type: "primary",
          ghost: false,
        },
        onPositiveClick: () => {},
        onNegativeClick: async () => {
          await api_musicSheetCreationRemove(item.id, checked.value ? 1 : 0);
          handleReset();

          // 删除上传记录里面的数据
          const index = uploadState.uploadList.findIndex((upload: any) => upload.musicSheetCreationId === item.id);
          if (index !== -1) {
            uploadState.uploadList.splice(index, 1);

            saveUploadCatch();
          }
        },
      });
    };
    const loadingRef = ref();

    const messageEvent = (params?: any) => {
      // 在老师端里面关闭要刷新
      if (params.data?.api == "reload") {
        handleReset();
      }
    };
    onMounted(() => {
      getList();
      if (loadingRef.value) {
        const obv = new IntersectionObserver((entries) => {
          if (entries[0].isIntersecting) {
            if (data.finish || data.loading) return;
            forms.page++;
            getList();
          }
        });
        obv.observe(loadingRef.value?.$el);
      }

      window.addEventListener("message", (params?: any) => {
        messageEvent(params);
      });

      eventGlobal.on("resetList", handleReset);
    });

    onUnmounted(() => {
      window.removeEventListener("message", messageEvent);
      eventGlobal.off("resetList", handleReset);
    });
    const handleOpenNotaion = (item: any) => {
      window.parent.postMessage(
        {
          api: "notation_open",
          url: `${location.origin}/notation/#/?v=${Date.now()}&id=${item.id}`,
        },
        "*"
      );
    };
    const productSvg = (abc: string, id: string) => {
      const a = ABCJS.renderAbc(id, abc, { selectTypes: false, add_classes: true })[0];
      return a;
    };

    const handleSuccess = () => {
      data.list.find((item: any) => item.id === data.item.id).uploadStatus = "YES";
    };
    return () => (
      <div class={styles.wrap}>
        <UploadFile />

        <div class={styles.wrapBox}>
          <div class={styles.itemWrap}>
            <div class={styles.itemWrapBox}>
              <div class={styles.createItem} onClick={() => (data.addShow = true)}>
                <img src={getImage("icon_29.png")} />
                <div>新建乐谱</div>
              </div>
            </div>
          </div>

          {data.list.map((item, index: number) => (
            <div class={styles.itemWrap}>
              <div class={styles.itemWrapBox}>
                <div class={styles.item} onClick={() => handleOpenNotaion(item)}>
                  <div class={[styles.imgBox]} id={"item_" + index}>
                    <img
                      src={getImage("icon_staff.png")}
                      onLoad={async () => {
                        // console.log(item.creationConfig, "1212");
                        if (!item.creationConfig) {
                          try {
                            const result = await requestOrigin.get(item.xml, {
                              mode: "cors",
                            });
                            let abc: any = new DOMParser().parseFromString(result, "text/xml");
                            const title = abc.querySelector("movement-title");
                            // xmlParse.getElementsByTagName("words");
                            // const title = abc.getElementsByTagName("movement-title");
                            if (title && title.textContent.trim() !== item?.name) {
                              title.textContent = item.name;
                            }

                            abc = (window as any).vertaal(abc, { p: "f", t: 1, u: 0, v: 3, mnum: 0 });
                            const r: any = ABCJS.renderAbc("importRef", abc[0], { responsive: "resize" }); //ABCJS.renderAbc("item_" + index, abc[0], { selectTypes: false, add_classes: true })[0];
                            const abcd = formateAbc(r[0], { subjectCode: "acoustic_grand_piano" });
                            const config = renderMeasures(abcd, {
                              hiddenIndex: true,
                              showTitle: true,
                              showCreator: true,
                            });
                            item.visualObj = productSvg(config, "item_" + index);
                          } catch (e) {
                            console.log(e, "1222222");
                          }
                        } else {
                          item.visualObj = productSvg(item.creationConfig, "item_" + index);
                        }
                      }}
                    />
                  </div>
                  <div class={styles.itemBottom}>
                    <div class={styles.bottombox}>
                      <div class={styles.bottomLeft}>
                        <div class={styles.itemtitle}>
                          <span>{item.name || `未命名乐谱-${index + 1}`}</span>
                        </div>
                        <div class={styles.time}>{item.updateTime}</div>
                      </div>
                      {item.uploadStatus !== "YES" && (
                        <img
                          class={styles.bottomBtn}
                          src={getImage("icon_29_2.png")}
                          onClick={(e: Event) => {
                            e.stopPropagation();
                            data.item = { ...item };
                            nextTick(() => {
                              data.uploadShow = true;
                            });
                          }}
                        />
                      )}
                      <img
                        class={styles.bottomBtn}
                        src={getImage("icon_29_3.png")}
                        onClick={(e: Event) => {
                          e.stopPropagation();
                          handleDelte(item);
                        }}
                      />
                    </div>
                  </div>
                  {item.uploadStatus === "YES" && <img class={styles.btn} src={getImage("icon_29_4.png")} />}
                  {item.uploadStatus === "UPDATE" && <img class={styles.btn} src={getImage("icon_29_5.png")} />}
                </div>
              </div>
            </div>
          ))}

          <div id="importRef" class={styles.importRef} style={{ display: "none" }}></div>
        </div>
        {!data.finish && (
          <NSpace ref={loadingRef} justify="center" style={{ padding: "30px" }}>
            <NSpin size="large" />
          </NSpace>
        )}

        <TheCreate
          v-model:show={data.addShow}
          onCreate={() => {
            data.addShow = false;
          }}
        />

        <UploadToResources v-model:show={data.uploadShow} item={data.item} onSuccess={() => handleSuccess()} />

        <UploadToTasks />
      </div>
    );
  },
});
