import {
  computed,
  defineComponent,
  onBeforeMount,
  onMounted,
  reactive,
  ref
} 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,
  showConfirmDialog,
  showDialog,
  showToast
} from 'vant';
import {
  api_lessonCoursewareFavoriteRemove,
  api_lessonCoursewareFavoriteSave,
  api_lessonCoursewareFavoriteage,
  api_lessonCoursewarePage,
  api_lessonCoursewareDetail,
  api_classLessonCoursewarePage,
  api_classLessonCoursewareDetail
} 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 CoursewareList from '@/custom-plugins/guide-page/courseware-list';
import './jquery.min.1.7.js';
import './turn.js';
import MEmpty from '@/components/m-empty';

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 popoverShow = ref(false);
    // 返回
    const goback = () => {
      postMessage({ api: 'goBack' });
    };
    const forms = reactive({
      currentGradeNum: 0,
      page: 1,
      rows: 999,
      type: 'COURSEWARE'
    });
    const _actions = computed(() => {
      return BOOK_DATA.grades.map((item, index) => {
        return {
          ...item,
          color:
            forms.currentGradeNum === index ? 'var(--van-primary-color)' : '',
          className: forms.currentGradeNum === index ? 'fontBlod' : ''
        };
      });
    });
    const onSelect = (action: any, index: number) => {
      forms.currentGradeNum = index;
      handleChange();
    };
    const isShowGuide = ref(false);
    const data = reactive({
      list: [] as any[],
      loading: false,
      favoriteList: [] as any[],
      tab: 'all',
      details: [] as any[],
      bookData: {} as any,
      showBook: false,
      book: {} as DOMRect
    });

    const getList = async () => {
      data.loading = true;
      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) => {
          item.load = false;
          item.key = Date.now() + item.id;
          return item;
        });
      }
      data.loading = false;
      isShowGuide.value = true;
    };
    const getFavoriteList = async () => {
      data.loading = true;
      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) => {
          item.name = `${item.name}`;
          item.load = false;
          item.favoriteFlag = true;
          item.key = Date.now() + item.id;
          return item;
        });
      }
      data.loading = false;
    };
    const getLessonCourseware = async () => {
      data.loading = true;
      const res = await api_classLessonCoursewarePage({
        // 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) => {
          item.load = false;
          item.key = Date.now() + item.id;
          return item;
        });
      }
      data.loading = false;
      isShowGuide.value = true;
    };
    const getData = () => {
      if (data.tab === 'all') {
        getList();
      }
      if (data.tab === 'favorite') {
        getFavoriteList();
      }
      if (data.tab === 'course') {
        getLessonCourseware();
      }
    };
    const handleChange = () => {
      getData();
    };
    onMounted(() => {
      getData();
    });

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

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

    /** 学生端根据教材编号获取关联的单元、章节 */
    const getDetail = async (item: any) => {
      if (data.tab === 'course') {
        const res = await api_classLessonCoursewareDetail(item.id);
        console.log(res, item, 'course');
        if (res?.code == 200 && Array.isArray(res?.data?.lessonList)) {
          data.details = res.data.lessonList || [];
          data.bookData = res.data;
          console.log('🚀 ~ data.details course:', data.details);
        } else {
          showConfirmDialog({
            title: '提示',
            message: '课程教材已更新，是否重新加载？'
          })
            .then(() => {
              // on confirm
              getData();
            })
            .catch(() => {
              // on cancel
            });
          return;
        }
      } else {
        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);
        }
      }

      handleCreateContainer(item.id);
      handleRender(() => {
        data.showBook = true;
      });
    };

    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);
    };

    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="course"></Tab>
            <Tab
              name="favorite"
              v-slots={{
                title: () => <div id="courseware-2">我的收藏</div>
              }}></Tab>
          </Tabs>
          <Popover
            v-model:show={popoverShow.value}
            class={styles.popover}
            actions={_actions.value}
            onSelect={onSelect}>
            {{
              reference: () => (
                <Button
                  class={styles.downBtn}
                  round
                  size="small"
                  {...{ id: 'courseware-3' }}>
                  {BOOK_DATA.grades[forms.currentGradeNum].text}{' '}
                  {/* <img class={styles.icon} src={icon_arrow} /> */}
                  <svg
                    class={[
                      styles.icon,
                      popoverShow.value ? styles.iconUp : ''
                    ]}
                    width="9px"
                    height="5px"
                    viewBox="0 0 9 5"
                    version="1.1"
                    xmlns="http://www.w3.org/2000/svg">
                    <title>三角形</title>
                    <g
                      id="演示用"
                      stroke="none"
                      stroke-width="1"
                      fill="currentColor"
                      fill-rule="evenodd">
                      <g
                        id="全部教材-筛选"
                        transform="translate(-769.000000, -35.000000)"
                        fill="currentColor">
                        <g
                          id="编组-3"
                          transform="translate(696.000000, 20.000000)">
                          <g
                            id="筛选目录备份-2"
                            transform="translate(13.000000, 7.000000)">
                            <path
                              d="M64.8716471,8.41294119 L68.2489659,12.1655176 C68.4336954,12.3707726 68.4170562,12.6869176 68.2118012,12.8716471 C68.1199888,12.9542782 68.0008397,13 67.8773188,13 L61.1226812,13 C60.8465388,13 60.6226812,12.7761424 60.6226812,12.5 C60.6226812,12.3764791 60.668403,12.25733 60.7510341,12.1655176 L64.1283529,8.41294119 C64.3130824,8.20768618 64.6292274,8.19104698 64.8344824,8.37577649 C64.8475136,8.38750459 64.859919,8.39990996 64.8716471,8.41294119 Z"
                              id="三角形"
                              transform="translate(64.500000, 10.500000) rotate(-180.000000) translate(-64.500000, -10.500000) "></path>
                          </g>
                        </g>
                      </g>
                    </g>
                  </svg>
                </Button>
              )
            }}
          </Popover>
        </div>

        <div class={styles.content}>
          <div
            class={[
              styles.wrap,
              data.list.length <= 0 && !data.loading ? styles.emtpyWrap : ''
            ]}>
            {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)}>
                  {/* courseware- */}

                  <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}
                      onLoad={() => {
                        item.load = true;
                      }}
                      onError={() => {
                        item.load = true;
                      }}
                    />
                  </div>

                  <div class={styles.name}>{item.name}</div>
                  {/* 课程教材不需要收藏 */}
                  {data.tab !== 'course' && (
                    <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>
              );
            })}

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

        <TheBook
          show={data.showBook}
          bookData={data.bookData}
          tab={data.tab}
          rect={data.book}
          onClose={() => {
            data.showBook = false;
          }}
        />
        {isShowGuide.value ? <CoursewareList></CoursewareList> : null}
      </div>
    );
  }
});
