import {
  computed,
  defineComponent,
  onBeforeMount,
  onMounted,
  reactive
} from 'vue';
import styles from './index.module.less';
import icon_back from './image/icon_back.svg';
import icon_arrow from './image/icon_arrow.svg';
import { Button, Image, Popover, Tab, Tabs, showToast } from 'vant';
import {
  api_lessonCoursewareFavoriteRemove,
  api_lessonCoursewareFavoriteSave,
  api_lessonCoursewareFavoriteage,
  api_lessonCoursewarePage,
  api_lessonCoursewareDetail
} from './api';
import { NImage } from 'naive-ui';
import { state } from '@/state';
import TheFavorite from '@/components/the-favorite';
import { useRouter } from 'vue-router';
import TheBook from './component/book';
import { postMessage } from '@/helpers/native-message';

import './jquery.min.1.7.js';
import './turn.js';

export const BOOK_DATA = {
  grades: [
    { text: '全部年级', value: '' },
    { text: '一年级', value: 1 },
    { text: '二年级', value: 2 },
    { text: '三年级', value: 3 },
    { text: '四年级', value: 4 },
    { text: '五年级', value: 5 },
    { text: '六年级', value: 6 },
    { text: '七年级', value: 7 },
    { text: '八年级', value: 8 },
    { text: '九年级', value: 9 }
  ],
  bookTypes: {
    LAST: '上册',
    NEXT: '下册'
  } as { [key: string]: string }
};

export default defineComponent({
  name: 'courseware-list',
  setup() {
    const router = useRouter();
    // 返回
    const goback = () => {
      postMessage({ api: 'goBack' });
    };
    const forms = reactive({
      currentGradeNum: 0,
      page: 1,
      rows: 10,
      type: 'COURSEWARE'
    });
    const _actions = computed(() => {
      return BOOK_DATA.grades.map((item, index) => {
        return {
          ...item,
          color:
            forms.currentGradeNum === index ? 'var(--van-primary-color)' : ''
        };
      });
    });
    const onSelect = (action: any, index: number) => {
      forms.currentGradeNum = index;
      handleChange();
    };

    const data = reactive({
      list: [] as any[],
      favoriteList: [] as any[],
      tab: 'all',
      details: [] as any[],
      bookData: {} as any,
      showBook: false,
      book: {} as DOMRect
    });

    const getList = async () => {
      const res = await api_lessonCoursewarePage({
        ...forms,
        currentGradeNum: forms.currentGradeNum ? forms.currentGradeNum : ''
      });
      if (res?.code === 200 && Array.isArray(res?.data?.rows)) {
        data.list = res.data.rows.map((item: any) => {
          const type = BOOK_DATA.bookTypes[item.bookType];
          item.name = `${item.name}(${type})`;
          item.load = false;
          item.key = Date.now() + item.id;
          return item;
        });
      }
    };
    const getFavoriteList = async () => {
      const res = await api_lessonCoursewareFavoriteage({
        clientType: 'STUDENT',
        userId: state.user?.data?.id,
        page: forms.page,
        rows: forms.rows,
        currentGradeNum: forms.currentGradeNum ? forms.currentGradeNum : ''
      });
      if (res?.code === 200 && Array.isArray(res?.data?.rows)) {
        data.list = res.data.rows.map((item: any) => {
          const type = BOOK_DATA.bookTypes[item.bookType];
          item.name = `${item.name}(${type})`;
          item.load = false;
          item.key = Date.now() + item.id;
          return item;
        });
      }
    };
    const getData = () => {
      data.list = []
      if (data.tab === 'all') {
        getList();
      }
      if (data.tab === 'favorite') {
        getFavoriteList();
      }
    };
    const handleChange = () => {
      forms.page = 1;
      getData();
    };
    onMounted(() => {
      getData();
    });

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

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

    /** 学生端根据教材编号获取关联的单元、章节 */
    const getDetail = async (item: any) => {
      const res = await api_lessonCoursewareDetail(item.id);
      if (res?.code == 200 && Array.isArray(res?.data?.lessonList)) {
        data.details = res.data.lessonList || [];
        data.bookData = res.data;
        console.log('🚀 ~ data.details:', data.details);
      }
    };

    const handleCreateContainer = (id: string) => {
      const box = document.querySelector(
        `[data-id="${id}"]`
      ) as unknown as HTMLElement;
      if (!box) return;
      const rect = box.getBoundingClientRect();
      data.book = rect;
    };
    const handleRender = (fn: any) => {
      requestAnimationFrame(() => {
        requestAnimationFrame(() => {
          fn();
        });
      });
    };
    const handleOpen = async (item: any) => {
      await getDetail(item);
      handleCreateContainer(item.id);
      handleRender(() => {
        data.showBook = true;
      });
    };

    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>
          <Tabs
            class={styles.tabs}
            v-model:active={data.tab}
            onChange={() => handleChange()}>
            <Tab title="全部教材" name="all"></Tab>
            <Tab title="我的收藏" name="favorite"></Tab>
          </Tabs>
          <Popover
            class={styles.popover}
            actions={_actions.value}
            onSelect={onSelect}>
            {{
              reference: () => (
                <Button class={styles.downBtn} round size="small">
                  {BOOK_DATA.grades[forms.currentGradeNum].text}{' '}
                  <img class={styles.icon} src={icon_arrow} />
                </Button>
              )
            }}
          </Popover>
        </div>

        <div class={styles.content}>
          <div class={styles.wrap}>
            {data.list.map((item, index) => {
              return (
                <div
                  class={[
                    styles.wrapItem,
                    data.bookData.id === item.id && data.showBook
                      ? styles.wrapItemHide
                      : ''
                  ]}
                  key={item.key}
                  onClick={() => handleOpen(item)}>
                  <NImage
                    data-id={item.id}
                    class={[styles.cover, item.load ? styles.loaded : '']}
                    objectFit="cover"
                    src={item.coverImg}
                    onLoad={() => {
                      item.load = true;
                    }}
                    onError={() => {
                      item.load = true;
                    }}
                  />
                  <div class={styles.name}>{item.name}</div>
                  <div
                    class={styles.favoriteBtn}
                    onClick={(e: Event) => {
                      e.stopPropagation();
                      if (data.tab !== 'all') return;
                      item.favoriteFlag = !item.favoriteFlag;
                      dubounce(() => handleFavorite(item));
                    }}>
                    <TheFavorite isFavorite={data.tab !== 'all' ? true : item.favoriteFlag} />
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        <TheBook
          show={data.showBook}
          bookData={data.bookData}
          rect={data.book}
          onClose={() => {
            data.showBook = false;
          }}
        />
      </div>
    );
  }
});
