import {
  PropType,
  defineComponent,
  nextTick,
  onMounted,
  reactive,
  watch
} from 'vue';
import styles from './index.module.less';
import icon_back from '../../image/icon_back.svg';
import icon_play from '../../image/icon_play.svg';
import { useRouter } from 'vue-router';
import { postMessage } from '@/helpers/native-message';
import { showToast } from 'vant';
import queryString from 'query-string';

export default defineComponent({
  name: 'the-book',
  props: {
    bookData: {
      type: Object as PropType<any>,
      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[][]
    });
    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);
            });
          });
        });
      }
    };
    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();
      //   handleBook();
    });
    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) {
          listItem.push({ name: item.name });
        } else {
          listItem = [{ name: item.name }];
        }
        for (let j = 0; j < item.knowledgeList.length; j++) {
          if (listItem.length < step) {
            listItem.push(item.knowledgeList[j]);
          } else {
            list.push(listItem);
            listItem = [item.knowledgeList[j]];
          }
        }
      }
      if (listItem.length) {
        list.push(listItem);
      }
      data.list = list;
    };
    watch(
      () => props.show,
      () => {
        if (props.show) {
          getList();
          nextTick(() => {
            handleBook();
            requestAnimationFrame(() => {
              getRect();
            });
          });
        }
      }
    );
    const handleOpenPlay = (item: any) => {
      if (!item.containMaterial) {
        showToast('暂无资源');
        return;
      }
      if (item.id) {
        const query = queryString.stringify({
          id: item.id,
          name: item.name
        })
        const url = location.origin + location.pathname + '#/courseware-play?' + query;
        postMessage({
          api: 'openWebView',
          content: {
            url,
            orientation: 0,
            isHideTitle: false
          }
        });
      }
    };
    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="gradient"></div>
                    <div class={styles.wrap}>
                      {list.map((item: any) => {
                        return (
                          <div
                            class={[styles.item, item.id && styles.des]}
                            onTouchstart={(e: TouchEvent) => {
                              e.stopPropagation();
                            }}
                            onClick={(e: Event) => {
                              e.stopPropagation();
                              handleOpenPlay(item);
                            }}>
                            <div class={styles.name}>{item.name}</div>
                            {item.id ? (
                              <img class={styles.icon} src={icon_play} />
                            ) : null}
                          </div>
                        );
                      })}
                    </div>
                  </div>
                );
              })}
              <div class="page">
                <div class="gradient"></div>
              </div>
            </div>
          )}
        </div>
      </div>
    );
  }
});
