import { NScrollbar, NSpin } from 'naive-ui';
import { PropType, defineComponent, onMounted, reactive } from 'vue';
import styles from './index.module.less';
import CardType from '@/components/card-type';
import SearchGroup from './search-group';
import TheEmpty from '/src/components/TheEmpty';
import { useDebounceFn, useThrottleFn, useResizeObserver } from '@vueuse/core';
import { usePrepareStore } from '/src/store/modules/prepareLessons';
import CardPreview from '/src/components/card-preview';
import { favorite, materialQueryPage } from '/src/views/natural-resources/api';

const formatType = (type: string) => {
  if (type === 'shareResources') {
    return 2;
  } else if (type === 'myResources') {
    return 3;
  } else if (type === 'myCollect') {
    return 4;
  }
};

export default defineComponent({
  name: 'select-music',
  props: {
    /** 类型 */
    cardType: {
      type: String as PropType<'' | 'homerowk-record' | 'prepare'>,
      default: ''
    },
    type: {
      type: String,
      default: ''
    },
    from: {
      type: String,
      default: ''
    }
  },
  emits: ['add'],
  setup(props, { emit }) {
    const prepareStore = usePrepareStore();
    const state = reactive({
      searchHeight: '0px',
      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,
        subjectId: null
      },
      tableList: [] as any,
      show: false,
      item: {} as any,
      isShowAddDisabled: !prepareStore.getIsEditTrain
    });
    const className = 'musicSearchGroup' + +new Date();
    const getList = async () => {
      try {
        if (state.pagination.page === 1) {
          state.loading = true;
        }
        const { data } = await materialQueryPage({
          ...state.searchGroup,
          ...state.pagination
        });
        state.loading = false;
        if (data.current === 1 && state.tableList.length > 0) return;
        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,
            isSelected: row.sourceFrom === 'PLATFORM' ? true : false,
            refFlag: row.refFlag,
            content: row.id,
            xmlFileUrl: row.xmlFileUrl,
            playSpeed: row.playSpeed ? Number(row.playSpeed) : null, // 原速
            audioPlayTypeArray: row.audioPlayTypes
              ? row.audioPlayTypes.split(',')
              : [],
            containAccompaniment: row.containAccompaniment
            // exist: index !== -1 ? true : false // 是否存在
          });
        });
        state.tableList.push(...temp);

        state.finshed = data.pages <= data.current ? true : false;
      } catch {
        state.loading = false;
      }
    };

    // 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 onSearch = (item: any) => {
      state.pagination.page = 1;
      state.tableList = [];
      state.searchGroup = Object.assign(state.searchGroup, item);
      getList();
    };
    const throttledFnSearch = useDebounceFn(item => {
      onSearch(item);
    }, 300);

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

    // 收藏
    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(() => {
      useResizeObserver(
        document.querySelector('.' + className) as HTMLElement,
        (entries: any) => {
          const entry = entries[0];
          const { height } = entry.contentRect;
          state.searchHeight = height + 'px';
        }
      );
      if (props.type === 'homework') {
        state.isShowAddDisabled = false;
      }
      // getList();
    });
    return () => (
      <div class={styles.selectMusic}>
        <NScrollbar
          class={styles.listContainer}
          style={{
            'max-height': `calc(85vh - var(--modal-lesson-tab-height) - 12px) `
          }}
          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();
            }
          }}>
          <div class={className}>
            <SearchGroup
              type={props.type}
              onSearch={(item: any, type: any) => {
                if (type) {
                  onSearch(item);
                } else {
                  throttledFnSearch(item);
                }
              }}
            />
          </div>
          <NSpin show={state.loading} size={'small'}>
            <div
              style={{
                'min-height': `calc(85vh - var(--modal-lesson-tab-height) - ${state.searchHeight} - 12px)`
              }}
              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
                      item={item}
                      // isShowAddDisabled={state.isShowAddDisabled}
                      onAdd={() => emit('add', item)}
                      disabledMouseHover={false}
                      onClick={() => {
                        if (item.type === 'IMG') return;
                        state.show = true;
                        state.item = {
                          instrumentId:
                            state.searchGroup.musicalInstrumentId || null,
                          ...item
                        };
                      }}
                      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}
        />
      </div>
    );
  }
});
