import { defineComponent, nextTick, onMounted, onUnmounted, reactive, ref, watch } from "vue";
import styles from "./index.module.less";
import { NButton, NCheckbox, 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 { useRouter } from "vue-router";
import ABCJS from "abcjs";
import { usePageVisibility } from "@vant/use";

export default defineComponent({
  name: "Create",
  setup() {
    const router = useRouter();
    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: false,
      loading: false,
      finish: false,
      isCreated: false,
    });
    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 style={{ paddingRight: "calc(var(--n-close-size) + 6px)" }}>确认删除当前曲谱?</div>,
        positiveText: "取消",
        positiveButtonProps: {
          type: "default",
        },
        negativeText: "删除",
        negativeButtonProps: {
          type: "primary",
          ghost: false,
        },
        onPositiveClick: () => {},
        onNegativeClick: async () => {
          await api_musicSheetCreationRemove(item.id);
          handleReset();
        },
      });
    };
    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);
      });
    });

    onUnmounted(() => {
      window.removeEventListener("message", messageEvent);
    });
    const handleOpenNotaion = (item: any) => {
      window.parent.postMessage(
        {
          api: "notation_open",
          url: `${location.origin}/notation/#/?v=1.0.2&id=${item.id}`,
        },
        "*"
      );
    };
    const productSvg = (abc: string, id: string) => {
      if (abc) {
        const a = ABCJS.renderAbc(id, abc, { selectTypes: false, add_classes: true });
      }
    };
    return () => (
      <div class={styles.wrap}>
        <NSpace size={18}>
          <div class={styles.createItem} onClick={() => (data.addShow = true)}>
            <img src={getImage("icon_29.png")} />
            <div>新建乐谱</div>
          </div>

          {data.list.map((item, index: number) => (
            <div class={styles.item} onClick={() => handleOpenNotaion(item)}>
              <div class={styles.imgBox} id={"item_" + index}>
                <img
                  src={getImage("icon_staff.png")}
                  onLoad={() => {
                    productSvg(item.creationConfig, "item_" + index);
                  }}
                />
              </div>
              <div class={styles.itemBottom}>
                <div class={styles.bottombox}>
                  <div class={styles.bottomLeft}>
                    <div class={styles.itemtitle}>
                      <img class={styles.icon_29} src={getImage("icon_29_1.png")} />
                      <span>{item.name}</span>
                    </div>
                    <div class={styles.time}>{item.updateTime}</div>
                  </div>
                  {/* <img
										style={{ pointerEvents: "none", opacity: 0.3 }}
										class={styles.bottomBtn}
										src={getImage("icon_29_2.png")}
									/> */}
                  <img
                    class={styles.bottomBtn}
                    src={getImage("icon_29_3.png")}
                    onClick={(e: Event) => {
                      e.stopPropagation();
                      handleDelte(item);
                    }}
                  />
                </div>
              </div>
              {/* <img class={styles.btn} src={getImage("icon_29_4.png")} /> */}
            </div>
          ))}
        </NSpace>
        {!data.finish && (
          <NSpace ref={loadingRef} justify="center" style={{ padding: "30px" }}>
            <NSpin size="large" />
          </NSpace>
        )}

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