import request from '@/helpers/request'
import { state } from '@/state'
import { Button, Empty, Grid, GridItem, Icon, showConfirmDialog, showToast } from 'vant'
import { defineComponent, onMounted, reactive, onUnmounted } from 'vue'
import styles from './index.module.less'
import { useRoute, useRouter } from 'vue-router'
import {
  listenerMessage,
  postMessage,
  promisefiyPostMessage,
  removeListenerMessage
} from '@/helpers/native-message'
import iconLook from './image/look.svg'
import iconCourse from './image/icon-course.png'
import { browser } from '@/helpers/utils'
export default defineComponent({
  name: 'lessonCourseware',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const browserInfo = browser()
    // const catchList = store
    const data = reactive({
      loading: true,
      list: [] as any
    })
    const getList = async () => {
      data.loading = true
      if (route.query.courseScheduleId) {
        try {
          const res: any = await request.post(
            state.platformApi + '/courseSchedule/getCoursewareDetail',
            {
              params: {
                courseScheduleId: route.query.courseScheduleId,
                coursewareId: route.query.id
              }
            }
          )
          if (Array.isArray(res?.data)) {
            data.list = res.data
          }
        } catch (error) {}
      } else {
        try {
          const res: any = await request.post(
            state.platformApi + '/courseSchedule/myCoursewareDetail/' + route.query.id
          )
          if (Array.isArray(res?.data)) {
            // data.list = res.data
            data.list = browserInfo.isApp ? await checkCoursewareCache(res.data) : res.data
          }
        } catch (error) {}
      }
      data.loading = false
    }
    onMounted(() => {
      getList()
      listenerMessage('downloadCoursewareToCache', getProgress)
    })
    onUnmounted(() => {
      removeListenerMessage('downloadCoursewareToCache', getProgress)
    })

    const handleClick = async (item: any) => {
      if (route.query.code === 'select') {
        console.log('选择课时')
        setCoursewareDetail(item)
        return
      }
      if (!item.hasCache) {
        if (browserInfo.isStudent || route.query.isdev) {
          try {
            await showConfirmDialog({
              message: '当前课程没有缓存是否缓存'
            })
          } catch (error) {
            gotoPlay(item)
            return
          }
        }
        downCatch(item)
        return
      }
      gotoPlay(item)
    }
    // 去课件播放
    const gotoPlay = (item: any) => {
      router.push({
        path: '/coursewarePlay',
        query: {
          id: item.lessonCoursewareDetailId
        }
      })
    }
    // 检查数据的缓存状态
    const checkCoursewareCache = (list: []) => {
      return new Promise((resolve) => {
        postMessage(
          {
            api: 'checkCoursewareCache',
            content: {
              data: list
            }
          },
          (res) => {
            if (res?.content?.data) {
              resolve(res.content.data)
              return
            }
            return []
          }
        )
      })
    }
    // 下载缓存
    const downCatch = async (item: any) => {
      if (browserInfo.isApp) {
        const res = await postMessage({
          api: 'downloadCoursewareToCache',
          content: {
            data: item
          }
        })
        return res
      }

      return true
    }
    // 下载缓存进度
    const getProgress = (res: any) => {
      // console.log('🚀 ~ res', res)
      if (res?.content?.lessonCoursewareDetailId) {
        const { lessonCoursewareDetailId, downloadStatus, progress } = res.content
        const course = data.list.find(
          (n: any) => n.lessonCoursewareDetailId == lessonCoursewareDetailId
        )
        if (course) {
          course.downloadStatus = downloadStatus
          course.progress = progress
          if (downloadStatus == 2) {
            course.hasCache = 1
            course.progress = 100
          }
        }
      }
    }
    // 绑定课时
    const setCoursewareDetail = async (item: any) => {
      try {
        const res: any = await request.post(
          state.platformApi + '/courseSchedule/setCoursewareDetail',
          {
            params: {
              courseScheduleId: route.query.courseScheduleId,
              coursewareDetailId: item.lessonCoursewareDetailId
            }
          }
        )
        if (res.code === 200) {
          showToast('保存成功')
          postMessage({ api: 'back' })
        }
      } catch (error) {}
    }
    return () => (
      <div style={{ paddingTop: '14px' }}>
        <Grid gutter={14} columnNum={3} class={styles.grid}>
          {data.list.map((item: any) => {
            return (
              <GridItem>
                <div class={styles.gridItem} onClick={() => handleClick(item)}>
                  <img src={iconCourse} class={styles.cover} />
                  <div class={styles.title}>
                    <div>{item.coursewareDetailName}</div>
                    {route.query.code !== 'select' && <div>已使用 {item.useNum} 次</div>}
                  </div>
                  {route.query.code !== 'select' ? (
                    <>
                      {item.hasCache ? (
                        <div class={styles.num}>
                          查看
                          <Icon name="play-circle-o" />
                        </div>
                      ) : (
                        <>
                          {item.downloadStatus === 1 ? (
                            <div class={styles.num}>下载中 {item.progress || 0}%</div>
                          ) : item.downloadStatus === 2 ? (
                            <div class={styles.num}>下载成功</div>
                          ) : item.downloadStatus === 3 ? (
                            <div class={styles.num}>重新下载</div>
                          ) : (
                            <div class={styles.num}>下载</div>
                          )}
                        </>
                      )}
                    </>
                  ) : (
                    <div class={styles.num}>选择</div>
                  )}

                  {route.query.code == 'select' && !item.unlock && (
                    <div class={styles.look} onClick={(e: Event) => e.stopPropagation()}>
                      <Icon name={iconLook} /> 未解锁
                    </div>
                  )}
                </div>
              </GridItem>
            )
          })}
        </Grid>
        <Button onClick={() => {
          location.href = 'http://192.168.3.114:1000/teacher.html#/coursewarePlay?id=1613426640725217281'
        }}>胜强测试老师端</Button>
        {!data.loading && !data.list.length && <Empty description="空空如也" />}
      </div>
    )
  }
})
