import { PropType, defineComponent, onMounted, reactive } from 'vue';
import styles from './index.module.less';
import SearchGroupResources from './search-group-resources';
import { NImage, NScrollbar, NSpin } from 'naive-ui';
import TheEmpty from '/src/components/TheEmpty';
import { api_knowledgeWiki_page } from '/src/views/content-information/api';
import CardPreview from '/src/components/card-preview';

export default defineComponent({
  name: 'instrument-list',
  props: {
    categoryId: {
      type: String,
      default: ''
    },
    categoryChildList: {
      type: Array as PropType<any>,
      default: () => []
    },
    selectItems: {
      type: Array as PropType<any>,
      default: () => []
    }
  },
  emits: ['confirm'],
  setup(props, { emit }) {
    const state = reactive({
      searchWord: '',
      loading: false,
      pageTotal: 0,
      finshed: false, // 是否加载完
      pagination: {
        page: 1,
        rows: 18
      },
      searchGroup: {
        type: 'INSTRUMENT', //
        keyword: '',
        wikiCategoryId: props.categoryId
      },
      tableList: [] as any,
      teachingStatus: false,
      show: false,
      item: {} as any
    });

    const getList = async () => {
      state.loading = true;
      try {
        const { data } = await api_knowledgeWiki_page({
          ...state.pagination,
          ...state.searchGroup
        });
        const temp = data.rows || [];
        temp.forEach((item: any) => {
          if (
            item.knowledgeWikiCategories &&
            item.knowledgeWikiCategories.length
          ) {
            item.categories =
              item.knowledgeWikiCategories[0].knowledgeWikiCategoryTypeName;
          }
        });
        state.tableList.push(...temp);

        state.pageTotal = Number(data.total);
        state.finshed = data.pages <= data.current ? true : false;
      } catch {
        //
      }
      state.loading = false;
    };

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

    // 更新
    const onSelect = (item: any) => {
      const ids = props.selectItems || [];
      const index = ids.findIndex((i: any) => i.id === item.id);
      if (index !== -1) {
        ids.splice(index, 1);
      } else {
        ids.push(item);
      }

      emit('confirm', ids);
    };

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

    return () => (
      <div class={styles.instrumentList}>
        <SearchGroupResources
          class={styles.searchGroups}
          categoryChildList={props.categoryChildList || []}
          onSearch={(item: any) => onSearch(item)}
          wikiCategoryId={props.categoryId}
        />
        <NScrollbar
          class={styles.listContainer}
          style={{
            'max-height': `50vh`
          }}
          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
            ) {
              state.pagination.page = state.pagination.page + 1;
              getList();
            }
          }}>
          <NSpin v-model:show={state.loading} style={{ 'min-height': '50vh' }}>
            <div class={styles.list}>
              {state.tableList.map((item: any) => (
                <div
                  class={styles.itemWrap}
                  onClick={() => {
                    // router.push({
                    //   path: '/content-instruments-detail',
                    //   query: {
                    //     id: item.id,
                    //     name: item.name
                    //   }
                    // });

                    state.item = {
                      content: item.id,
                      title: item.name,
                      type: 'INSTRUMENT'
                    };
                    state.show = true;
                  }}>
                  <div class={styles.itemWrapBox}>
                    <div class={styles.itemCard}>
                      <div
                        class={[
                          styles.itemImgSection,
                          props.selectItems.findIndex(
                            (i: any) => i.id === item.id
                          ) !== -1 && styles.itemImgSectionSelected
                        ]}>
                        <NImage
                          src={
                            item.avatar +
                            '?imageMogr2/strip/format/jpg/size-limit/15k!'
                          }
                          class={styles.img}
                          objectFit="cover"
                          previewDisabled
                        />

                        <i
                          class={[styles.iconCheck]}
                          onClick={(e: any) => {
                            e.stopPropagation();
                            onSelect(item);
                          }}></i>
                      </div>
                      <div class={styles.itemTitle}>{item.name}</div>
                    </div>
                  </div>
                </div>
              ))}

              {!state.loading && state.tableList.length <= 0 && (
                <TheEmpty
                  style={{ minHeight: '50vh' }}
                  description="暂无乐器百科"
                />
              )}
            </div>
          </NSpin>
        </NScrollbar>

        {/* 弹窗查看 */}
        <CardPreview
          size={'large'}
          v-model:show={state.show}
          item={state.item}
        />
      </div>
    );
  }
});
