import {
  computed,
  defineComponent,
  onMounted,
  reactive,
  ref,
  watch
} from 'vue';
import styles from './baseIndex.module.less';
import icon_back from './image/icon_back.svg';
import { Button, Space, Tab, Tabs, showConfirmDialog, Image } from 'vant';
import {
  api_lessonCoursewareFavoriteRemove,
  api_lessonCoursewareFavoriteSave
} from '../courseware-list/api';
import { NImage } from 'naive-ui';
import { state } from '@/state';
import TheFavorite from '@/components/the-favorite';
import { useRouter } from 'vue-router';
import { postMessage } from '@/helpers/native-message';
import MEmpty from '@/components/m-empty';
import MSearch from '@/components/m-search';
import { api_musicSheetCategoriesPage, api_musicTagTree } from './api';
import queryString from 'query-string';
import { useRect } from '@vant/use';
import { nextTick } from 'process';
import iconDefaultCo from './image/icon-default-co.png';

export default defineComponent({
  name: 'baseIndex-list',
  setup() {
    const router = useRouter();
    const popoverShow = ref(false);
    const bookVersionList = ref([] as any);
    // 返回
    const goback = () => {
      postMessage({ api: 'goBack' });
    };
    const forms = reactive({
      // currentGradeNum: null,
      musicTagId: null,
      keyword: null,
      page: 1,
      rows: 999
      // type: 'COURSEWARE'
    });
    const isShowGuide = ref(false);
    const data = reactive({
      list: [] as any[],
      loading: false,
      favoriteList: [] as any[],
      details: [] as any[],
      bookData: {} as any,
      showBook: false,
      book: {} as DOMRect
    });

    const wrapRef = ref();
    const wrapItemRef = ref([] as any);

    const getTanentList = async () => {
      try {
        const { data } = await api_musicTagTree();
        bookVersionList.value = data || [];
        if (bookVersionList.value.length > 0) {
          forms.musicTagId = bookVersionList.value[0].id;
        }
      } catch {
        //
      }
    };

    const getList = async () => {
      data.loading = true;
      const { musicTagId, ...music } = forms;
      const res = await api_musicSheetCategoriesPage({
        musicTagIds: [musicTagId],
        subjectId: state.user.data?.subjectId || '',
        ...music
        // currentGradeNum: forms.currentGradeNum ? forms.currentGradeNum : ''
      });
      if (res?.code === 200 && Array.isArray(res?.data?.rows)) {
        data.list = res.data.rows.map((item: any) => {
          item.load = false;
          item.key = Date.now() + item.id;
          return item;
        });
      }
      data.loading = false;
      isShowGuide.value = true;

      // nextTick(() => {
      //   // 设置样式
      //   const wrap = useRect(wrapRef);
      //   const wrapItem = useRect(wrapItemRef.value[0]);
      //   if (wrapItem.width > 0) {
      //     wrapRef.value.style.width =
      //       Math.floor(wrap.width / wrapItem.width) * wrapItem.width + 'px';
      //     wrapRef.value.style.margin = '0 auto';
      //   }
      // });
    };
    onMounted(async () => {
      // 安卓的状态栏
      postMessage({
        api: 'setStatusBarVisibility',
        content: {
          isVisibility: 0
        }
      });
      data.loading = true;
      await getTanentList();
      await getList();
      data.loading = false;

      // if (wrapItemRef.value && wrapItemRef.length > 0) {
      //   console.log(wrapItemRef[0], '121');
      // }
    });

    const handleFavorite = async (item: any) => {
      if (item.favoriteFlag) {
        await api_lessonCoursewareFavoriteSave({
          lessonCoursewareId: item.id
        });
      } else {
        await api_lessonCoursewareFavoriteRemove({
          lessonCoursewareId: item.id
        });

        getList();
      }
    };

    let timer: any = null;
    const dubounce = (fn: any, delay: number = 300) => {
      if (timer) {
        clearTimeout(timer);
      }
      timer = setTimeout(fn, delay);
    };

    const onDetail = (item: any) => {
      // router.push({
      //   path: '/co-ai-detail',
      //   query: {
      //     musicTagId: forms.musicTagId,
      //     id: item.id,
      //     name: item.name
      //   }
      // });
      const query = queryString.stringify({
        musicTagId: forms.musicTagId,
        id: item.id,
        name: item.name
      });
      const url =
        location.origin + location.pathname + '#/co-ai-detail?' + query;
      console.log('🚀 ~ url:', url);
      postMessage({
        api: 'openWebView',
        content: {
          url,
          orientation: 0,
          isHideTitle: false,
          c_orientation: 0 // 0 横屏 1 竖屏
        }
      });
    };

    return () => (
      <div class={styles.container}>
        {/* <div class={styles.head} style={{ opacity: data.showBook ? 0 : '' }}>
          <div class={styles.back} onClick={goback}>
            <img src={icon_back} />
          </div>
        </div> */}
        <div class={styles.back} onClick={goback}>
          <img src={icon_back} />
        </div>

        <div class={styles.centerSearch}>
          <div id="coai-0">
            <MSearch
              class={[
                'searchNotice'
                // data.searchNoticeShow ? styles.searchNoticeShow : ''
              ]}
              shape="round"
              background="transparent"
              clearable={false}
              placeholder="请输入关键字"
              // modelValue={forms.keyword}
              // onFocus={() => (data.searchNoticeShow = false)}
              // onBlur={val => {
              //   musicForms.keyword = val?.trim() || '';
              //   requestAnimationFrame(() => {
              //     requestAnimationFrame(() => {
              //       if (musicForms.keyword) {
              //         data.searchNoticeShow = true;
              //       }
              //     });
              //   });
              // }}
              onSearch={val => {
                forms.keyword = val;
                getList();
              }}
            />
          </div>
        </div>

        <div class={styles.section}>
          <div class={styles.directorySection}>
            <div class={styles.directionc}>
              {bookVersionList.value.map((item: any) => (
                <p
                  class={[
                    styles.dirItem,
                    forms.musicTagId == item.id ? styles.active : ''
                  ]}
                  onClick={() => {
                    forms.musicTagId = item.id;
                    getList();
                  }}>
                  {item.name}
                </p>
              ))}
            </div>
          </div>

          <div class={styles.content}>
            <div
              class={[
                styles.wrap,
                data.list.length <= 0 && !data.loading ? styles.emtpyWrap : ''
              ]}
              ref={wrapRef}>
              {data.list.map((item, index) => {
                return (
                  <div class={styles.wrapfirstI}>
                    <div
                      ref={(el: any) => (wrapItemRef.value[index] = el)}
                      class={[
                        styles.wrapItem,
                        data.bookData.id === item.id && data.showBook
                          ? styles.wrapItemHide
                          : ''
                      ]}
                      key={item.key}
                      onClick={() => onDetail(item)}>
                      <div class={styles.item}>
                        <NImage
                          data-id={item.id}
                          {...{ id: index == 0 ? 'courseware-0' : '' }}
                          class={[styles.cover, item.load ? styles.loaded : '']}
                          objectFit="cover"
                          src={item.coverImg}
                          fallbackSrc={iconDefaultCo}
                          onLoad={() => {
                            item.load = true;
                          }}
                          onError={() => {
                            item.load = true;
                            item.error = true;
                          }}
                        />
                      </div>

                      <div class={styles.name}>{item.name}</div>
                      {/* <div
                      id={index === 0 ? 'courseware-1' : ''}
                      class={styles.favoriteBtn}
                      onClick={(e: Event) => {
                        e.stopPropagation();
                        item.favoriteFlag = !item.favoriteFlag;
                        dubounce(() => handleFavorite(item));
                      }}>
                      <TheFavorite isFavorite={item.favoriteFlag} />
                    </div> */}
                    </div>
                  </div>
                );
              })}

              {data.list.length <= 0 && !data.loading && (
                <MEmpty image="list" description="暂无数据" />
              )}
            </div>
          </div>
        </div>
      </div>
    );
  }
});
