import { defineComponent, 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 useTime from './image/use-time.png';
import { Button, Image, List, Popup, Tag } from 'vant';
import {
  api_lessonCoursewareStudentPage,
  api_lessonCoursewareDetail,
  api_bookVersionPage
} from './api';
import TheBook from './component/book';
import { postMessage } from '@/helpers/native-message';
import './jquery.min.1.7.js';
import './turn.js';
import MEmpty from '@/components/m-empty';
import deepClone from '@/helpers/deep-clone';
import { browser, chunkArray } from '@/helpers/utils';

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 popoverShow = ref(false);
    // const baseBookVersionList = ref([] as any);
    const bookVersionList = ref([] as any);
    // 返回
    const goback = () => {
      postMessage({ api: 'goBack' });
    };
    const coursewareStorage = localStorage.getItem('courseware-list')
      ? JSON.parse(localStorage.getItem('courseware-list') as any)
      : {};
    const forms = reactive({
      currentGradeNum: coursewareStorage.currentGradeNum || null,
      bookVersionId: coursewareStorage.bookVersionId || (null as any),
      page: 1,
      rows: 24
    });

    const data = reactive({
      courseRecord: null as any, // 上课记录
      dataShow: true, //
      list: [] as any[],
      loading: false,
      finished: false, // 是否加载完成
      details: [] as any[],
      bookData: {} as any,
      bookLessonId: '',
      showBook: false,
      book: {} as DOMRect
    });

    const getTenantList = async () => {
      try {
        const { data } = await api_bookVersionPage({ type: 'COURSEWARE' });
        const result = data.rows || [];
        // baseBookVersionList.value = result.map((item: any) => {
        //   return {
        //     bookVersionId: item.id,
        //     bookVersionName: item.name
        //   };
        // });
        // ...deepClone(baseBookVerionList.value),

        bookVersionList.value = result.map((item: any) => {
          return {
            bookVersionId: item.id,
            bookVersionName: item.name
          };
        });
        bookVersionList.value.push({
          bookVersionId: -1,
          bookVersionName: '自定义'
        });
        const index = bookVersionList.value.findIndex(
          (item: any) => item.bookVersionId == coursewareStorage.bookVersionId
        );
        // 判断列表中是存在，缓存的教材数据
        if (index < 0) {
          forms.bookVersionId = null;
        }
      } catch (e) {
        //
        console.log(e);
      }
    };

    let isClick = false;
    const getData = async () => {
      if (isClick) return;
      isClick = true;
      data.loading = true;
      const { bookVersionId, currentGradeNum, ...more } = forms;
      const res = await api_lessonCoursewareStudentPage({
        ...more,
        bookVersionId: bookVersionId == -1 ? null : bookVersionId,
        currentGradeNum: currentGradeNum ? currentGradeNum : ''
      });
      if (res?.code === 200 && Array.isArray(res?.data?.rows)) {
        // 只有在第一页的时候才会赋值上次上课记录
        if (res?.data?.current == 1) {
          data.courseRecord = res?.data?.extra;
        }

        const result = res.data.rows.map((item: any) => {
          item.load = false;
          item.key = Date.now() + item.id;
          return item;
        });

        data.list = data.list.concat(
          chunkArray(result, data.courseRecord?.id ? 3 : 4)
        );
        forms.page = res.data.current + 1;
        data.dataShow = data.list.length > 0;
        data.finished = res.data.current >= res.data.pages;
      }
      data.loading = false;
      isClick = false;
    };

    onMounted(async () => {
      // window.addEventListener('error', (e: any) => {
      //   console.log(e, 'error');
      // });
      await getTenantList();

      getData();
      // 安卓的状态栏
      postMessage({
        api: 'setStatusBarVisibility',
        content: {
          isVisibility: 0
        }
      });
    });

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

      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>
          <Button
            class={[
              styles.downBtn,
              forms.bookVersionId > 0 || forms.currentGradeNum
                ? styles.activeBtn
                : '',
              popoverShow.value ? styles.activeBtn : ''
            ]}
            round
            size="small"
            onClick={() => (popoverShow.value = true)}>
            筛选
            <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>
        </div>

        <div
          class={[
            styles.content,
            data.courseRecord?.id ? styles.courseDetails : ''
          ]}>
          <div class={styles.wrapLeft}>
            {data.courseRecord ? (
              <div
                class={[
                  styles.wrapItem,
                  styles.courseWrapItem
                  // data.bookData.id === item.id && data.showBook
                  //   ? styles.wrapItemHide
                  //   : ''
                ]}
                key={data.courseRecord.id}
                onClick={() => handleOpen(data.courseRecord)}>
                <div class={styles.item}>
                  <img src={useTime} class={styles.useTime} />
                  <Image
                    data-id={data.courseRecord.id}
                    class={[
                      styles.cover,
                      data.courseRecord.load ? styles.loaded : ''
                    ]}
                    fit="cover"
                    src={data.courseRecord.coverImg}
                    onLoad={() => {
                      data.courseRecord.load = true;
                    }}>
                    {{ loading: () => <i></i> }}
                  </Image>
                </div>

                <div class={styles.name}>{data.courseRecord.name}</div>
              </div>
            ) : (
              ''
            )}
          </div>
          <div class={styles.wrapRight}>
            <div class={[styles.wrap]}>
              {data.dataShow ? (
                <List
                  loading={data.loading}
                  loading-text=" "
                  finished={data.finished}
                  finished-text=" "
                  onLoad={getData}
                  immediateCheck={false}>
                  {data.list.map(parent => {
                    const sLength = data.courseRecord?.id ? 3 : 4;
                    const length = sLength - parent.length;
                    // 填补空白
                    const array = [];
                    for (let i = 0; i < length; i++) {
                      array.push(i);
                    }
                    return (
                      <div class={styles.warpSection}>
                        {parent.map((item: any) => (
                          <div
                            class={[
                              styles.wrapItem,
                              data.bookData.id === item.id && data.showBook
                                ? styles.wrapItemHide
                                : ''
                            ]}
                            key={item.key}
                            onClick={() => handleOpen(item)}>
                            <div class={styles.item}>
                              <Image
                                data-id={item.id}
                                class={[
                                  styles.cover,
                                  item.load ? styles.loaded : ''
                                ]}
                                fit="cover"
                                src={item.coverImg}
                                onLoad={() => {
                                  item.load = true;
                                }}>
                                {{ loading: () => <i></i> }}
                              </Image>
                            </div>

                            <div class={styles.name}>{item.name}</div>
                          </div>
                        ))}
                        {array.map(() => (
                          <div class={styles.wrapItem}></div>
                        ))}
                      </div>
                    );
                  })}
                </List>
              ) : (
                // <OEmpty
                //   description="暂无学练统计"
                //   style={{ height: `calc(100vh - ${topWrapHeight.value}px)` }}
                // />
                <MEmpty image="list" description="暂无数据" />
              )}
            </div>
          </div>
        </div>
        <TheBook
          show={data.showBook}
          bookData={data.bookData}
          bookLessonId={data.bookLessonId}
          rect={data.book}
          onClose={() => {
            data.showBook = false;
          }}
          onConfirm={() => {
            getData();
          }}
        />

        {/* 搜索条件 */}
        <Popup v-model:show={popoverShow.value} class={styles.popupContainer}>
          <div class={styles.popoverContainer}>
            <div class={styles.searchList}>
              {bookVersionList.value.length > 0 && (
                <div>
                  <div class={styles.popoverTitle}>教材版本</div>
                  <div class={[styles.popupList, styles.versionList]}>
                    {bookVersionList.value.map((item: any) => (
                      <Tag
                        plain={forms.bookVersionId == item.bookVersionId}
                        round
                        onClick={() =>
                          (forms.bookVersionId = item.bookVersionId)
                        }>
                        {item.bookVersionName}
                      </Tag>
                    ))}
                  </div>
                </div>
              )}

              <div class={styles.popoverTitle}>选择年级</div>
              <div class={[styles.popupList, styles.versionList]}>
                {BOOK_DATA.grades.map((item: any) => (
                  <Tag
                    plain={forms.currentGradeNum === item.value}
                    round
                    onClick={() => (forms.currentGradeNum = item.value)}>
                    {item.text}
                  </Tag>
                ))}
              </div>
            </div>

            <div class={styles.btnGroup}>
              <Button
                round
                onClick={() => {
                  forms.bookVersionId = null;
                  forms.currentGradeNum = null;
                }}>
                重置
              </Button>
              <Button
                round
                class={styles.btnSure}
                onClick={() => {
                  // 保存缓存
                  localStorage.setItem(
                    'courseware-list',
                    JSON.stringify({
                      bookVersionId: forms.bookVersionId,
                      currentGradeNum: forms.currentGradeNum
                    })
                  );
                  forms.page = 1;
                  data.courseRecord = null;
                  data.list = [];
                  getData();
                  popoverShow.value = false;
                }}>
                确认
              </Button>
            </div>
          </div>
        </Popup>
      </div>
    );
  }
});
