import { computed, defineComponent, onMounted, reactive, ref } from 'vue';
import styles from './index.module.less';
import { NIcon, NSpin, NScrollbar, NModal, NImage, NTooltip } from 'naive-ui';
import {
  lessonCoursewareDetail,
  lessonCoursewarePage,
  tagUseCourseware
} from '../../api';
import SelectLessonware from './select-lessonware';
import TheEmpty from '/src/components/TheEmpty';
import { usePrepareStore } from '/src/store/modules/prepareLessons';
import { useUserStore } from '/src/store/modules/users';
import { useRoute } from 'vue-router';
import { eventGlobal } from '/src/utils';
// import TheNoticeBar from '/src/components/TheNoticeBar';
import { getSubjectList2 } from '/src/api/user';
import LessonsGuide from '@/custom-plugins/guide-page/lessons-guide';
import { modalClickMask } from '/src/state';

export default defineComponent({
  name: 'directory-main',
  props: {
    sidebarShow: {
      type: Boolean,
      default: true
    }
  },
  setup(props) {
    const route = useRoute();
    const prepareStore = usePrepareStore();
    const userStore = useUserStore();
    const show = ref(true);
    const forms = reactive({
      lastUseCoursewareId: route.query.lastUseCoursewareId
        ? route.query.lastUseCoursewareId + ''
        : null, // 专辑编号
      unit: route.query.unit ? route.query.unit + '' : null, // 声部
      showSelectBookStatus: false,
      coursewareStatus: false
    });

    const getLessonCourseware = async () => {
      try {
        const { data } = await lessonCoursewarePage({
          page: 1,
          rows: 99,
          type: 'COURSEWARE',
          enableFlag: 1
        });
        const result = data.rows || [];
        if (result.length > 0) {
          // 判断是否有默认数据
          const selectItem = result.find(
            (item: any) =>
              item.id ===
              (forms.lastUseCoursewareId ||
                userStore.getUserInfo?.lastUseCoursewareId)
          );
          let id: any = null;
          let instrumentIds: any = null;
          if (selectItem) {
            prepareStore.setBaseCourseware(selectItem);
            id = selectItem.id;
            instrumentIds = selectItem.instrumentIds;
          } else {
            prepareStore.setBaseCourseware(result[0]);
            id = result[0]?.id;
            instrumentIds = result[0].instrumentIds;
          }
          setLastUseCoursewareId(id);

          if (instrumentIds) {
            const { data } = await getSubjectList2({ instrumentIds });
            prepareStore.setInstrumentList(data);
          }
        }

        forms.showSelectBookStatus = true;
      } catch {
        //
      }
    };

    const getLessonCoursewareDetail = async () => {
      try {
        const baseCourseware: any = prepareStore.getBaseCourseware;
        if (!baseCourseware.id) return;
        const { data } = await lessonCoursewareDetail({
          id: baseCourseware.id
        });
        const tempList: any = data.lessonList || [];
        const defaultUnitIds = formatParentId(forms.unit, tempList);
        tempList.forEach((item: any, index: number) => {
          item.selected = false;
          // 处理从备课页面带过来的参数
          if (defaultUnitIds.length > 1) {
            if (item.id === defaultUnitIds[0]) {
              item.selected = true;
              item.knowledgeList.forEach((know: any) => {
                if (know.id === defaultUnitIds[1]) {
                  prepareStore.setSelectKey(know?.id);
                  prepareStore.setLessonCoursewareId(know?.lessonCoursewareId);
                  prepareStore.setLessonCoursewareDetailId(
                    know?.lessonCoursewareDetailId
                  );
                }
              });
            }
          } else {
            if (index === 0) {
              item.selected = true;
              const temp = item['knowledgeList'][0];
              prepareStore.setSelectKey(temp?.id);
              prepareStore.setLessonCoursewareId(temp?.lessonCoursewareId);
              prepareStore.setLessonCoursewareDetailId(
                temp?.lessonCoursewareDetailId
              );
            }
          }
        });
        prepareStore.setTreeList(tempList);

        const tempInstrumentId = prepareStore.getInstrumentId;
        if (tempInstrumentId) {
          const instrumentList = prepareStore.getFormatInstrumentList;
          let status = false;
          instrumentList.forEach((item: any) => {
            if (item.instruments?.length > 0) {
              item.instruments.forEach((child: any) => {
                if (child.value == tempInstrumentId) {
                  status = true;
                }
              });
            }
            if (item.value == tempInstrumentId) {
              status = true;
            }
          });
          if (!status) {
            onShowDefaultInstrument();
          }
        } else {
          onShowDefaultInstrument();
        }
      } catch {
        //
      }
    };

    const onShowDefaultInstrument = () => {
      // 默认选中第一个声部
      const instrumentList = prepareStore.getFormatInstrumentList;
      if (instrumentList.length > 0) {
        const tempList = instrumentList[0];
        if (tempList.instruments.length > 1) {
          const childTempList = tempList.instruments[0];
          prepareStore.setInstrumentId(childTempList.value);
        } else {
          prepareStore.setInstrumentId(tempList.value);
        }
      }
    };

    const formatParentId = (id: any, list: any, ids = [] as any) => {
      for (const item of list) {
        if (item.knowledgeList && item.knowledgeList.length > 0) {
          const cIds: any = formatParentId(id, item.knowledgeList, [
            ...ids,
            item.id
          ]);
          if (cIds.includes(id)) {
            return cIds;
          }
        }
        if (item.id === id) {
          return [...ids, id];
        }
      }
      return ids;
    };

    const setLastUseCoursewareId = async (id: any) => {
      try {
        await tagUseCourseware({ coursewareId: id });
        userStore.getInfo();
      } catch {
        //
      }
    };

    const clickDetail = (child: any) => {
      prepareStore.setSelectKey(child.id);
      prepareStore.setLessonCoursewareId(child.lessonCoursewareId);
      prepareStore.setLessonCoursewareDetailId(child.lessonCoursewareDetailId);
    };

    const onChangeClass = async (item: any) => {
      show.value = true;
      forms.lastUseCoursewareId = item.lastUseCoursewareId;
      forms.unit = item.unit;
      await getLessonCourseware();
      await getLessonCoursewareDetail();
      show.value = false;
    };

    const changeCourseware = async (item: any) => {
      prepareStore.setBaseCourseware(item);
      // prepareStore.setSubjectList(item.subjectList);
      if (item.instrumentIds) {
        const { data } = await getSubjectList2({
          instrumentIds: item.instrumentIds
        });
        prepareStore.setInstrumentList(data);

        let status = false;
        let tempInstrumentId: any = null;
        data.forEach((item: any, index: number) => {
          if (Array.isArray(item.instruments)) {
            item.instruments.forEach((child: any, j: number) => {
              if (child.id === prepareStore.getInstrumentId) {
                status = true;
              }
              if (index === 0 && j === 0) {
                tempInstrumentId = child.id;
              }
            });
          }
        });
        await getLessonCoursewareDetail();
        // 判断教材里面是否有当前选择的声部，如果没有则默认选择第一个

        if (status) {
          const instrumentId = tempInstrumentId;
          prepareStore.setInstrumentId(instrumentId);
        } else {
          onShowDefaultInstrument();
        }
      }

      setLastUseCoursewareId(item.id);
    };

    const formatInstrumentNames = computed(() => {
      const names = prepareStore.getBaseCourseware.instrumentNames;
      if (!names) {
        return '';
      }
      return names.split(',').join('、');
    });

    onMounted(async () => {
      show.value = true;
      await getLessonCourseware();
      await getLessonCoursewareDetail();
      show.value = false;

      // 切换班级时触发
      eventGlobal.on('onChangeClass', async (item: any) => {
        onChangeClass(item);
      });
    });
    return () => (
      <>
        <div class={styles.directoryList}>
          {forms.showSelectBookStatus &&
            (prepareStore.getBaseCourseware.id ? (
              <div id="lessons-0" class={styles['select-directory-info']}>
                <div
                  class={styles.itemImg}
                  onClick={() => (forms.coursewareStatus = true)}>
                  <NImage
                    objectFit="cover"
                    src={prepareStore.getBaseCourseware.coverImg}
                    lazy
                    previewDisabled={true}
                    onLoad={(e: any) => {
                      (e.target as any).dataset.loaded = 'true';
                    }}
                  />
                </div>
                <div class={styles.itemContent}>
                  <h2>
                    {/* <TheNoticeBar text={prepareStore.getBaseCourseware.name} /> */}
                    <NTooltip showArrow={false} class={styles.theTooltip} placement="top-start">
                      {{
                        trigger: () => prepareStore.getBaseCourseware.name,
                        default: () => prepareStore.getBaseCourseware.name
                      }}
                    </NTooltip>
                  </h2>
                  <div class={styles.subjects}>
                    {/* <TheNoticeBar text={formatInstrumentNames.value} /> */}
                    <NTooltip showArrow={false} class={styles.theTooltip} placement="top-start">
                      {{
                        trigger: () => formatInstrumentNames.value,
                        default: () => formatInstrumentNames.value
                      }}
                    </NTooltip>
                  </div>
                  <div
                    class={styles.changeDir}
                    onClick={() => (forms.coursewareStatus = true)}>
                    <svg
                      width="11px"
                      height="10px"
                      viewBox="0 0 11 10"
                      version="1.1"
                      xmlns="http://www.w3.org/2000/svg">
                      <title>切片</title>
                      <g
                        stroke="none"
                        stroke-width="1"
                        fill="none"
                        fill-rule="evenodd">
                        <g
                          transform="translate(-279.000000, -210.000000)"
                          fill="#0378EC"
                          fill-rule="nonzero">
                          <g transform="translate(132.000000, 96.000000)">
                            <g transform="translate(32.000000, 24.000000)">
                              <g transform="translate(103.000000, 10.000000)">
                                <g transform="translate(0.000000, 71.000000)">
                                  <g transform="translate(12.000000, 9.000000)">
                                    <path d="M10.4116565,3.89985699 C10.6551462,3.89985699 10.8747497,3.75140792 10.9680437,3.52360884 C11.0613377,3.29606287 11.0096883,3.03384082 10.8376072,2.85944797 L8.08018279,0.0692888872 C7.98888976,-0.0230962957 7.8410701,-0.0230962957 7.74977708,0.0692888872 L7.22840639,0.59689687 C7.13711336,0.689282053 7.13711336,0.838996672 7.22840639,0.931255299 L8.95772133,2.68113191 L0.230858792,2.68113191 C0.103423738,2.68113191 0,2.78566638 0,2.91475252 L0,3.66636293 C0,3.79532253 0.10329868,3.89998355 0.230858792,3.89998355 L10.4116565,3.89998355 L10.4116565,3.89985699 Z M10.877501,6.10001645 L0.699579677,6.10001645 C0.456089932,6.10001645 0.236486444,6.24846552 0.143192479,6.4762646 C0.0498985147,6.70381057 0.101547854,6.96603263 0.273628948,7.14042548 L3.03105338,9.93071111 C3.12234641,10.0230963 3.27016607,10.0230963 3.36145909,9.93071111 L3.88282978,9.40310313 C3.97412281,9.31071795 3.97412281,9.16100333 3.88282978,9.0687447 L2.15351484,7.31874154 L10.877501,7.31874154 C11.0065618,7.31874154 11.1111111,7.21281496 11.1111111,7.08233671 L11.1111111,6.33654783 C11.1111111,6.20594302 11.0065618,6.10001645 10.877501,6.10001645 Z"></path>
                                  </g>
                                </g>
                              </g>
                            </g>
                          </g>
                        </g>
                      </g>
                    </svg>
                    <span>切换教材</span>
                  </div>
                </div>
              </div>
            ) : (
              <div
                id="lessons-0"
                class={styles['select-directory']}
                onClick={() => (forms.coursewareStatus = true)}>
                <span
                  class={['cr-ellipsis']}
                  title={prepareStore.getBaseCourseware.name}>
                  {prepareStore.getBaseCourseware.name || '请选择教材'}
                </span>
                <NIcon class={styles.iconArrow}>
                  <svg
                    width="11px"
                    height="15px"
                    viewBox="0 0 11 15"
                    version="1.1"
                    xmlns="http://www.w3.org/2000/svg">
                    <g
                      stroke="none"
                      stroke-width="1"
                      fill="none"
                      fill-rule="evenodd"
                      opacity="0.699999988">
                      <g
                        transform="translate(-445.000000, -137.000000)"
                        fill="#131415">
                        <g transform="translate(152.000000, 120.000000)">
                          <path
                            d="M299.326227,20.2118001 L304.934089,28.4366632 C305.245211,28.8929759 305.127511,29.515105 304.671198,29.8262273 C304.505147,29.9394437 304.308836,30 304.107861,30 L292.892139,30 C292.339854,30 291.892139,29.5522847 291.892139,29 C291.892139,28.7990254 291.952695,28.6027139 292.065911,28.4366632 L297.673773,20.2118001 C297.984895,19.7554873 298.607024,19.6377872 299.063337,19.9489096 C299.16663,20.0193364 299.255801,20.1085074 299.326227,20.2118001 Z"
                            id="三角形"
                            transform="translate(298.500000, 24.500000) rotate(-270.000000) translate(-298.500000, -24.500000) "></path>
                        </g>
                      </g>
                    </g>
                  </svg>
                </NIcon>
              </div>
            ))}

          <NScrollbar class={styles.scrollBar}>
            <NSpin show={show.value}>
              <div
                class={[
                  styles.listSection,
                  !show.value && prepareStore.getTreeList.length <= 0
                    ? styles.emptySection
                    : ''
                ]}>
                {prepareStore.getTreeList.map((item: any, index: number) => (
                  <div class={styles.treeParent} key={'parent' + index}>
                    <div
                      class={[styles.treeItem, styles.parentItem]}
                      onClick={() => {
                        prepareStore.getTreeList.forEach((child: any) => {
                          if (item.id !== child.id) {
                            child.selected = false;
                          }
                        });
                        item.selected = item.selected ? false : true;
                      }}>
                      {item.knowledgeList && item.knowledgeList.length > 0 && (
                        <span
                          class={[
                            styles.arrow,
                            item.selected ? styles.arrowSelect : ''
                          ]}></span>
                      )}
                      <p
                        class={[
                          styles.title,
                          item.selected ? styles.titleSelect : ''
                        ]}>
                        <span
                          class={[
                            styles.dir,
                            item.selected ? styles.dirSelect : ''
                          ]}></span>
                        {item.name}
                      </p>
                    </div>

                    {item.selected &&
                      item.knowledgeList &&
                      item.knowledgeList.map((child: any, j: number) => (
                        <div
                          key={'child' + j}
                          class={[
                            styles.treeItem,
                            styles.childItem,
                            styles.animation,
                            prepareStore.getSelectKey === child.id
                              ? styles.childSelect
                              : ''
                          ]}
                          onClick={() => {
                            if (prepareStore.getIsEditResource) {
                              eventGlobal.emit('pageBeforeLeave', () =>
                                clickDetail(child)
                              );
                            } else {
                              clickDetail(child);
                            }
                          }}>
                          <span class={styles.childArrow}></span>
                          <p class={styles.title}>{child.name}</p>
                        </div>
                      ))}
                  </div>
                ))}
              </div>
              {!show.value && prepareStore.getTreeList.length <= 0 && (
                <TheEmpty />
              )}
            </NSpin>
          </NScrollbar>

          {/* 选择教材 */}
          <NModal
            maskClosable={modalClickMask}
            v-model:show={forms.coursewareStatus}
            preset="card"
            showIcon={false}
            class={['modalTitle background', styles.coursewareModal]}
            title={'切换教材'}
            blockScroll={false}>
            <SelectLessonware
              onClose={() => (forms.coursewareStatus = false)}
              onConfirm={(item: any) => {
                if (prepareStore.getIsEditResource) {
                  eventGlobal.emit('pageBeforeLeave', () =>
                    changeCourseware(item)
                  );
                } else {
                  changeCourseware(item);
                }
              }}
            />
          </NModal>
        </div>
        {forms.showSelectBookStatus && !props.sidebarShow && (
          <LessonsGuide></LessonsGuide>
        )}
      </>
    );
  }
});
