import { defineComponent, onMounted, reactive, watch } from 'vue';
import ResourceSearchGroup from './resource-search-group';
import { NModal, NScrollbar, NSpin } from 'naive-ui';
import styles from './index.module.less';
import CardType from '/src/components/card-type';
import TheEmpty from '/src/components/TheEmpty';
import { useThrottleFn } from '@vueuse/core';
import { usePrepareStore } from '/src/store/modules/prepareLessons';
import { musicSheetPage } from '/src/views/prepare-lessons/api';
import TrainUpdate from '/src/views/attend-class/model/train-update';
import requestOrigin from 'umi-request';
import CardPreview from '/src/components/card-preview';
import { evaluateDifficult } from '/src/utils/contants';
import { eventGlobal } from '/src/utils';
export default defineComponent({
  name: 'share-resources',
  setup() {
    const prepareStore = usePrepareStore();
    const state = reactive({
      loading: false,
      finshed: false, // 是否加载完
      pagination: {
        page: 1,
        rows: 20
      },
      searchGroup: {
        name: '',
        musicSheetCategoriesId: '',
        status: 1,
        versionFlag: false,
        musicSubject: null
      },
      tableList: [] as any,
      editStatus: false,
      editItem: {} as any,
      show: false,
      item: {} as any
    });
    const getList = async () => {
      try {
        if (!prepareStore.getSubjectId) return;
        if (state.pagination.page === 1) {
          state.loading = true;
        }
        const { data } = await musicSheetPage({
          ...state.searchGroup,
          ...state.pagination,
          musicSubject: prepareStore.getSubjectId
        });
        state.loading = false;
        const tempRows = data.rows || [];
        const temp: any = [];

        tempRows.forEach((row: any) => {
          const index = prepareStore.getTrainList.findIndex(
            (course: any) => course.musicId === row.id
          );
          temp.push({
            id: row.id,
            coverImg: row.musicSvg,
            type: 'MUSIC',
            title: row.musicSheetName,
            isCollect: false,
            isSelected: true,
            content: row.id,
            xmlFileUrl: row.xmlFileUrl,
            exist: index !== -1 ? true : false // 是否存在
          });
        });
        state.tableList.push(...temp);
        state.finshed = data.pages <= data.current ? true : false;
      } catch {
        state.loading = false;
      }
    };

    const onSearch = async (item: any) => {
      state.pagination.page = 1;
      state.tableList = [];
      state.searchGroup = Object.assign(state.searchGroup, item);
      getList();
    };

    // 声部变化时
    watch(
      () => prepareStore.getSubjectId,
      () => {
        onSearch(state.searchGroup);
      }
    );
    watch(
      () => prepareStore.trainList,
      () => {
        state.tableList.forEach((item: any) => {
          const index = prepareStore.getTrainList.findIndex(
            (course: any) => course.musicId === item.id
          );
          item.exist = index !== -1 ? true : false; // 是否存在
        });
      },
      {
        deep: true,
        immediate: true
      }
    );

    const throttledFn = useThrottleFn(() => {
      state.pagination.page = state.pagination.page + 1;
      getList();
    }, 500);

    // 添加资源
    const onAdd = async (item: any) => {
      let xmlStatus = 'init';
      // 第一个声部小节
      let firstMeasures: any = null;
      try {
        // 获取文件
        const res = await requestOrigin.get(item.xmlFileUrl, {
          mode: 'cors'
        });
        const xmlParse = new DOMParser().parseFromString(res, 'text/xml');
        const parts = xmlParse.getElementsByTagName('part');
        firstMeasures = parts[0]?.getElementsByTagName('measure');
        xmlStatus = 'success';
      } catch (error) {
        xmlStatus = 'error';
      }

      // 判断读取小节数
      if (xmlStatus == 'success') {
        item.practiceChapterMax = firstMeasures.length;
      } else {
        item.practiceChapterMax = 0;
      }
      item.coursewareKnowledgeDetailId = prepareStore.getSelectKey;
      item.subjectId = prepareStore.getSubjectId;

      state.editItem = item;
      state.editStatus = true;
    };

    const typeFormat = (trainingType: string, configJson: any) => {
      let tList: string[] = [];

      if (trainingType === 'EVALUATION') {
        tList = [
          `${evaluateDifficult[configJson.evaluateDifficult]}`,
          '全部小节',
          // `速度${configJson.evaluateSpeed}`,
          `${configJson.trainingTimes}分合格`
        ];
      } else {
        tList = [
          `${configJson.practiceChapterBegin}-${configJson.practiceChapterEnd}小节`,
          `速度${configJson.practiceSpeed}`,
          `${configJson.trainingTimes}分钟`
        ];
      }
      return tList;
    };

    onMounted(() => {
      getList();

      eventGlobal.on('onTrainDragItem', (item: any) => {
        onAdd(item);
      });
    });
    return () => (
      <div>
        <ResourceSearchGroup onSearch={(item: any) => onSearch(item)} />
        <NScrollbar
          class={styles.listContainer}
          onScroll={(e: any) => {
            const clientHeight = e.target?.clientHeight;
            const scrollTop = e.target?.scrollTop;
            const scrollHeight = e.target?.scrollHeight;
            // 是否到底，是否加载完
            if (
              clientHeight + scrollTop + 20 >= scrollHeight &&
              !state.finshed &&
              !state.loading
            ) {
              throttledFn();
            }
          }}>
          <NSpin show={state.loading} size={'small'}>
            <div
              class={[
                styles.listSection,
                !state.loading && state.tableList.length <= 0
                  ? styles.emptySection
                  : ''
              ]}>
              {state.tableList.length > 0 && (
                <div class={styles.list}>
                  {state.tableList.map((item: any) => (
                    <CardType
                      isShowAdd
                      isShowCollect={false}
                      item={item}
                      draggable
                      // isShowAddDisabled={!prepareStore.getIsEditTrain}
                      disabledMouseHover={false}
                      onClick={() => {
                        if (item.type === 'IMG') return;
                        state.show = true;
                        state.item = item;
                      }}
                      onAdd={(child: any) => onAdd(child)}
                    />
                  ))}
                </div>
              )}
              {!state.loading && state.tableList.length <= 0 && <TheEmpty />}
            </div>
          </NSpin>
        </NScrollbar>

        {/* 弹窗查看 */}
        <CardPreview v-model:show={state.show} item={state.item} />

        <NModal
          v-model:show={state.editStatus}
          class={['modalTitle background', styles.trainEditModal]}
          preset="card"
          title="作业设置">
          <TrainUpdate
            item={state.editItem}
            type="homework"
            onClose={() => (state.editStatus = false)}
            onConfirm={(item: any) => {
              // state.editItem = {};
              // prepareStore.setIsAddTrain(true);

              const tList = typeFormat(
                item.trainingType,
                item.trainingConfigJson
              );
              //
              const train = {
                ...item,
                id: null,
                musicName: state.editItem.title,
                typeList: tList
              };

              console.log(train, '1212');
              eventGlobal.emit('onTrainAddItem', train);
            }}
          />
        </NModal>
      </div>
    );
  }
});
