import {
  PropType,
  defineComponent,
  onMounted,
  reactive,
  watch,
  toRef
} 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 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';
import { favorite, materialQueryPage } from '/src/views/natural-resources/api';
import useDrag from '@/hooks/useDrag';
import Dragbom from '@/hooks/useDrag/dragbom';
import { useUserStore } from '@/store/modules/users';
import { modalClickMask } from '/src/state';

const formatType = (type: string) => {
  if (type === 'sahreMusic') {
    return 2;
  } else if (type === 'myMusic') {
    return 3;
  } else if (type === 'collectMusic') {
    return 4;
  }
};

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

  if (trainingType === 'EVALUATION') {
    tList = [
      `${evaluateDifficult[configJson.evaluateDifficult]}`,
      `${configJson.practiceChapterBegin || 0}-${configJson.practiceChapterEnd || 0}小节`,
      `速度${configJson.evaluateSpeed || 0}`,
      `${configJson.trainingTimes}分达标`
    ];
  } else {
    tList = [
      `${configJson.practiceChapterBegin}-${configJson.practiceChapterEnd}小节`,
      `速度${configJson.practiceSpeed || 0}`,
      `${configJson.trainingTimes}分钟`
    ];
  }
  return tList;
};

export default defineComponent({
  name: 'share-resources',
  props: {
    type: {
      type: String as PropType<'myMusic' | 'sahreMusic' | 'collectMusic'>,
      default: 'myMusic'
    },
    /** 类型 */
    cardType: {
      type: String as PropType<'' | 'homerowk-record' | 'prepare'>,
      default: ''
    },
    from: {
      // 来自哪里
      type: String,
      default: ''
    }
  },
  setup(props) {
    const prepareStore = usePrepareStore();
    const state = reactive({
      loading: false,
      finshed: false, // 是否加载完
      pagination: {
        page: 1,
        rows: 20
      },
      searchGroup: {
        name: '',
        type: 'MUSIC', //
        musicSheetCategoriesId: '',
        musicalInstrumentId: '',
        audioPlayTypes:
          props.cardType === 'homerowk-record' || props.cardType === 'prepare'
            ? ['PLAY']
            : [],
        sourceType: formatType(props.type),
        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 &&
          !['homerowk-record', 'prepare'].includes(props.cardType)
        )
          return;
        if (state.pagination.page === 1) {
          state.loading = true;
        }
        // const { data } = await musicSheetPage({
        //   ...state.searchGroup,
        //   ...state.pagination,
        //   musicSubject: prepareStore.getSubjectId
        // });
        const { data } = await materialQueryPage({
          ...state.searchGroup,
          ...state.pagination
          // subjectId: 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.coverImg || row.musicSvg,
            type: 'MUSIC',
            title: row.name,
            isCollect: !!row.favoriteFlag,
            refFlag: row.refFlag,
            isSelected: row.sourceFrom === 'PLATFORM' ? true : false,
            content: row.id,
            playSpeed: row.playSpeed ? Number(row.playSpeed) : null, // 原速
            audioPlayTypeArray: row.audioPlayTypes
              ? row.audioPlayTypes.split(',')
              : [],
            containAccompaniment: row.containAccompaniment,
            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');
        /**
         * 妙极客的曲子，systems中含有part标签，需过滤掉systems标签，xmlParse.querySelectorAll('systems')
         */
        const systems = Array.from(xmlParse?.querySelectorAll('systems')) || [];
        systems.forEach((system: any) => {
          const childs = Array.from(system?.querySelectorAll('system')) || [];
          childs.forEach((child: any) => {
            system?.removeChild(child);
          })
        });
        const parts = xmlParse.getElementsByTagName('part');
        firstMeasures = parts[0]?.getElementsByTagName('measure');
        xmlStatus = 'success';
      } catch (error) {
        xmlStatus = 'error';
      }

      // 判断读取小节数
      if (xmlStatus == 'success') {
        // 标记xml是否是从0小节开始
        item.firstMeasureIsZero = firstMeasures?.[0]?.getAttribute('number') === '0';
        item.practiceChapterMax = item.firstMeasureIsZero ? firstMeasures.length - 1 : firstMeasures.length;
      } else {
        item.practiceChapterMax = 0;
      }
      item.coursewareKnowledgeDetailId = prepareStore.getSelectKey;
      item.subjectId = prepareStore.getSubjectId;

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

    // 收藏
    const onCollect = async (item: any) => {
      try {
        await favorite({
          materialId: item.id,
          favoriteFlag: item.isCollect ? 0 : 1,
          type: item.type
        });
        item.isCollect = !item.isCollect;
      } catch {
        //
      }
    };

    onMounted(() => {
      // getList();

      eventGlobal.on('onTrainDragItem', (item: any, point?: any) => {
        onAdd(item);
      });
    });
    // 弹窗拖动
    // 作业设置
    let workSetingBoxDragData: any;
    let workSetingBoxClass: string;
    if (props.from === 'class') {
      const users = useUserStore();
      workSetingBoxClass = 'workSetingBoxClass_drag';
      workSetingBoxDragData = useDrag(
        [
          `${workSetingBoxClass}>.n-card-header`,
          `${workSetingBoxClass} .bom_drag`
        ],
        workSetingBoxClass,
        toRef(state, 'editStatus'),
        users.info.id
      );
    }
    return () => (
      <div>
        <ResourceSearchGroup
          type={props.type}
          onSearch={(item: any) => {
            onSearch(item)
          }}
        />
        <NScrollbar
          class={[
            styles.listContainer,
            props.type === 'myMusic' ? styles.listNoMusic : ''
          ]}
          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
                      item={item}
                      draggable
                      isShowCollect
                      // isShowAddDisabled={!prepareStore.getIsEditTrain}
                      disabledMouseHover={false}
                      onClick={() => {
                        if (item.type === 'IMG') return;
                        state.show = true;
                        state.item = {
                          instrumentId:
                            state.searchGroup.musicalInstrumentId || null,
                          ...item
                        };
                      }}
                      onAdd={(child: any) => onAdd(child)}
                      onCollect={(item: any) => onCollect(item)}
                    />
                  ))}
                </div>
              )}
              {!state.loading && state.tableList.length <= 0 && <TheEmpty />}
            </div>
          </NSpin>
        </NScrollbar>

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

        <NModal
          maskClosable={modalClickMask}
          v-model:show={state.editStatus}
          style={
            props.from === 'class' ? workSetingBoxDragData.styleDrag.value : {}
          }
          class={[
            'modalTitle background',
            styles.trainEditModal,
            workSetingBoxClass
          ]}
          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
              };

              eventGlobal.emit('onTrainAddItem', train);
            }}
          />
          {props.from === 'class' && <Dragbom></Dragbom>}
        </NModal>
      </div>
    );
  }
});
