import {
  PropType,
  defineComponent,
  nextTick,
  onMounted,
  reactive,
  watch,
  ref
} from 'vue';
import styles from './index.module.less';
import icon_back from '../../image/icon_back.svg';
import icon_play from '../../image/icon_class.png';
import { useRouter } from 'vue-router';
import { listenerMessage, postMessage } from '@/helpers/native-message';
import { showToast } from 'vant';
import queryString from 'query-string';
import CoursewareDetail from '@/custom-plugins/guide-page/courseware-detail';
import { usePageVisibility } from '@vant/use';
export default defineComponent({
  name: 'the-book',
  props: {
    bookData: {
      type: Object as PropType<any>,
      default: () => ({})
    },
    tab: {
      type: String,
      default: ''
    },
    show: {
      type: Boolean,
      default: false
    },
    rect: {
      type: Object as PropType<DOMRect>,
      default: () => ({})
    }
  },
  emits: ['close'],
  setup(props, { emit }) {
    const router = useRouter();

    const data = reactive({
      show: false,
      width: 0,
      height: 0,
      transform: '',
      list: [] as any[][],
      lastTime: localStorage.getItem('lastTime')
    });
    const showGuide = ref(false);
    const handleCreate = (key: string, url: string) => {
      return new Promise((resolve, reject) => {
        const _s = document.head.querySelector(`script[data-key="${key}"]`);
        if (!_s) {
          const s = document.createElement('script');
          s.setAttribute('data-key', key);
          s.src = url;
          s.onload = async () => {
            console.log(key + ' 加载完成');
            resolve(1);
          };
          document.head.appendChild(s);
        }
      });
    };
    const init = async () => {
      //   await handleCreate('jquery', '/book/jquery.min.1.7.js');
      //   await handleCreate('turn', '/book/turn.js');
      console.log('初始化完成');
    };
    let book: any = null;
    let timer: any = null;
    const handleBook = () => {
      book = (window as any).$('#flipbook');
      const height = document.body.clientHeight * 0.8;

      data.height = height;
      data.width = height * (210 / 297) * 2;
      book.turn({
        autoCenter: true,
        duration: 1000,
        acceleration: true, // 是否启动硬件加速 如果为触摸设备必须为true
        // pages: 11, // 页码总数
        elevation: 50, // 转换期间页面的高度
        width: data.width, // 宽度 单位 px
        height: data.height, // 高度 单位 px
        gradients: true // 是否显示翻页阴影效果
        // display: 'single', //设置单页还是双页
      });
    };

    const getRect = () => {
      const bookWrap = document.querySelector(
        '.bookWrap'
      ) as unknown as HTMLElement;
      if (bookWrap) {
        const rect = bookWrap.getBoundingClientRect();
        const xScale = props.rect.width / (rect.width / 2);
        const yScale = props.rect.height / rect.height;
        const left =
          (((rect.width / 2) * (xScale - 1)) / 2 +
            props.rect.x -
            rect.x -
            rect.width / 4) /
          xScale;
        const top =
          ((rect.height * (yScale - 1)) / 2 + props.rect.y - rect.y) / yScale;
        const transform = `scale3d(${xScale}, ${yScale}, 1) translate(${left}px, ${top}px)`;
        bookWrap.style.transform = data.transform = transform;
        bookWrap.style.transition = 'transform 0s';
        nextTick(() => {
          requestAnimationFrame(() => {
            requestAnimationFrame(() => {
              bookWrap.style.transition = 'transform 1s';
              bookWrap.style.transform = '';
              data.show = true;
              timer = setTimeout(() => {
                book.turn('page', 2);
              }, 500);

              setTimeout(() => {
                showGuide.value = true;
              }, 1500);
            });
          });
        });
      }
    };
    const handleClose = () => {
      clearTimeout(timer);
      const bookWrap = document.querySelector(
        '.bookWrap'
      ) as unknown as HTMLElement;
      book.turn('page', 1);
      if (bookWrap) {
        bookWrap.style.transform = data.transform;
      }
      emit('close');
      setTimeout(() => {
        bookWrap.style.transition = '';
        bookWrap.style.transform = '';
        data.show = false;
        data.list = [];
      }, 1000);
    };
    onMounted(async () => {
      await init();
      listenerMessage('webViewOnResume', () => {
        data.lastTime = localStorage.getItem('lastTime');
      });
    });
    const getList = () => {
      if (!props.bookData?.lessonList) return;
      const step = Math.floor((document.body.clientHeight * 0.8 - 40) / 50);
      console.log('🚀 ~ step:', step);
      const list = [];
      let listItem = [] as any[];
      for (let i = 0; i < props.bookData.lessonList.length; i++) {
        const item = props.bookData.lessonList[i];
        if (listItem.length >= step) {
          list.push([...listItem]);
          listItem = [{ name: item.name }];
        } else {
          listItem.push({ name: item.name });
        }
        for (let j = 0; j < item.knowledgeList.length; j++) {
          if (listItem.length >= step) {
            list.push([...listItem]);
            listItem = [item.knowledgeList[j]];
          } else {
            listItem.push(item.knowledgeList[j]);
          }
        }
      }
      if (listItem.length) {
        list.push(listItem);
      }
      data.list = list;
      // console.log('🚀 ~ data.list:', data.list.length);
    };
    watch(
      () => props.show,
      () => {
        if (props.show) {
          getList();
          nextTick(() => {
            handleBook();
            requestAnimationFrame(() => {
              getRect();
            });
          });
        }
      }
    );
    const handleOpenPlay = (item: any) => {
      if (item.id) {
        if (!item.containMaterial) {
          showToast('暂无资源');
          return;
        }
        localStorage.setItem('lastTime', item.id);
        const query = queryString.stringify({
          id: item.id,
          name: item.name,
          tab: props.tab // 当前切换的是哪个类型
        });
        const url =
          location.origin + location.pathname + '#/courseware-play?' + query;
        console.log('🚀 ~ url:', url);
        // postMessage({
        //   api: 'openWebView',
        //   content: {
        //     url,
        //     orientation: 0,
        //     isHideTitle: false
        //   }
        // });
        router.push({
          path: '/courseware-play',
          query: {
            id: item.id,
            name: item.name,
            tab: props.tab
          }
        });
      }
    };
    return () => (
      <div class={[styles.book, data.show ? '' : styles.bookHide]}>
        <div class={styles.back} onClick={handleClose}>
          <img src={icon_back} />
        </div>
        <div class="bookWrap" style={{ width: data.width + 'px' }}>
          {!!data.list.length && (
            <div id="flipbook" class={[data.show && 'animated']}>
              <div class="page">
                <img
                  style="width: 100%; height: 100%; object-fit: cover;"
                  src={props.bookData.coverImg}
                />
              </div>
              {data.list.map((list: any) => {
                return (
                  <div class="page">
                    <div class={styles.wrap}>
                      <div class={styles.wrapItem}>
                        {list.map((item: any, index: number) => {
                          return (
                            <>
                              <div
                                class={[styles.item, item.id && styles.des]}
                                onTouchstart={(e: TouchEvent) => {
                                  e.stopPropagation();
                                }}
                                onClick={(e: Event) => {
                                  e.stopPropagation();
                                  handleOpenPlay(item);
                                }}>
                                {item.id ? (
                                  <img
                                    id={index == 1 ? 'coursewareDetail-0' : ''}
                                    class={styles.icon}
                                    src={icon_play}
                                  />
                                ) : null}
                                <div
                                  class={styles.name}
                                  style={{ lineHeight: '20Px' }}>
                                  {item.name}
                                  {data.lastTime === item.id && (
                                    <span class={styles.last}>上次观看</span>
                                  )}
                                </div>
                              </div>
                            </>
                          );
                        })}
                      </div>
                    </div>
                  </div>
                );
              })}
              {data.list.length % 2 === 1 && (
                <div class="page" style={{ pointerEvents: 'none' }}>
                  <div class={styles.wrap}>
                    <div class={styles.wrapItem}></div>
                  </div>
                </div>
              )}
            </div>
          )}
        </div>
        {showGuide.value ? <CoursewareDetail></CoursewareDetail> : null}
      </div>
    );
  }
});
