import { PropType, defineComponent, onMounted, reactive } from 'vue';
import styles from './index.module.less';
import SearchGroupResources from './search-group-resources';
import { NImage, NSpin } from 'naive-ui';
import TheEmpty from '/src/components/TheEmpty';
import Pagination from '/src/components/pagination';
import { api_knowledgeWiki_page } from '../../../api';
import { useRouter } from 'vue-router';

export default defineComponent({
  name: 'instrument-list',
  props: {
    categoryId: {
      type: String,
      default: ''
    },
    categoryChildList: {
      type: Array as PropType<any>,
      default: () => []
    }
  },
  setup(props) {
    // 保存数据
    const operationCatch = (type: 'get'| 'set' = 'get', value: string = '') : any => {
      const sessionName = 'content-instrument-catch'
      if(type === "get") {
        const result = sessionStorage.getItem(sessionName)
        return result ? JSON.parse(result) : null
      } else if(type === 'set') {
        sessionStorage.setItem(sessionName, value)
      }
    }

    const router = useRouter();
    const catchData = operationCatch('get')
    const state = reactive({
      searchWord: '',
      loading: false,
      pageTotal: 0,
      pagination: catchData && catchData.pagination ? catchData.pagination : {
        page: 1,
        rows: 18
      },
      searchGroup:  catchData && catchData.searchGroup ? catchData.searchGroup : {
        type: 'INSTRUMENT', //
        keyword: '',
        wikiCategoryId: props.categoryId
      },
      tableList: [] as any,
      teachingStatus: false,
      show: false,
      item: {} as any
    });

    

    const getList = async () => {
      state.loading = true;
      // 缓存
      operationCatch('set', JSON.stringify({
        pagination: state.pagination,
        searchGroup: state.searchGroup
      }))
      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 = temp || [];

        state.pageTotal = Number(data.total);
      } catch {
        //
      }
      state.loading = false;
    };

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

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

    return () => (
      <div class={styles.instrumentList}>
        <SearchGroupResources
          categoryChildList={props.categoryChildList || []}
          onSearch={(item: any) => onSearch(item)}
          wikiCategoryId={state.searchGroup.wikiCategoryId}
          defaultWikiCategoryId={props.categoryId}
          searchValue={state.searchGroup.keyword}
        />

        <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
                    }
                  });
                }}>
                <div class={styles.itemWrapBox}>
                  <div class={styles.itemCard}>
                    {item.categories ? (
                      <span class={styles.itemTag}>{item.categories}</span>
                    ) : (
                      ''
                    )}

                    <div class={styles.itemImgSection}>
                      <NImage
                        src={
                          item.avatar +
                          '?imageMogr2/strip/format/jpg/size-limit/15k!'
                        }
                        class={styles.img}
                        objectFit="cover"
                        previewDisabled
                      />
                    </div>
                    <div class={styles.itemTitle}>{item.name}</div>
                  </div>
                </div>
              </div>
            ))}

            {!state.loading && state.tableList.length <= 0 && (
              <TheEmpty
                style={{ minHeight: '50vh' }}
                description="暂无乐器百科"
              />
            )}
          </div>
        </NSpin>
        <Pagination
          v-model:page={state.pagination.page}
          v-model:pageSize={state.pagination.rows}
          v-model:pageTotal={state.pageTotal}
          pageSizes={[18, 24, 30, 36]}
          onList={getList}
        />
      </div>
    );
  }
});
