import CourseVideoItem from '@/business-components/course-video-item'
import SectionDetail from '@/business-components/section-detail'
import UserDetail from '@/business-components/user-detail'
import { Button, Dialog, Toast } from 'vant'
import { defineComponent } from 'vue'
import styles from './index.module.less'
import request from '@/helpers/request'
import ColSticky from '@/components/col-sticky'
import { shareCall } from '../share'
import { browser } from '@/helpers/utils'
import { postMessage } from '@/helpers/native-message'
import { state } from '@/state'
import qs from 'query-string'

export const getAssetsHomeFile = (fileName: string) => {
  const path = `../images/${fileName}`
  const modules = import.meta.globEager('../images/*')
  return modules[path].default
}

export default defineComponent({
  name: 'VideoDetail',
  data() {
    const query = this.$route.query
    return {
      userInfo: {} as any,
      detailList: [],
      buyUserList: [], // 购买学生数
      dataShow: true, // 判断是否有数据
      loading: false,
      finished: false,
      recomUserId: query.recomUserId, // 分享人编号
      params: {
        videoLessonGroupId: query.groupId,
        page: 1,
        rows: 20
      },
      wxStatus: false
    }
  },
  created() {
    if (browser().isApp) {
      if (state.platformType === 'STUDENT') {
        const query = this.$route.query
        query.recomUserId =
          query.userType && query.userType == 'STUDENT' ? '' : query.recomUserId
        // 自动跳转到学生端视频课详情购买页
        // 为了处理andoird webview的跳转问题
        if (browser().ios) {
          window.location.replace(
            `${location.origin}/student/#/videoDetail?${qs.stringify(query)}`
          )
        } else {
          postMessage({
            api: 'openWebView',
            content: {
              url: `${location.origin}/student/#/videoDetail?${qs.stringify(
                query
              )}`,
              orientation: 1,
              isHideTitle: false
            }
          })

          postMessage({ api: 'back' })
        }
        return
      } else if (state.platformType === 'TEACHER') {
        Dialog.alert({
          title: '提示',
          message: '请使用酷乐秀学生端扫码打开',
          confirmButtonColor: '#2dc7aa'
        }).then(() => {
          postMessage({ api: 'back' })
        })
      }
    } else {
      // 如果不在app里面则不需要唤起操作
      this.reCall()
    }
  },
  async mounted() {
    try {
      const res = await request.post(`/api-teacher/open/videoShareProfit`, {
        data: {
          bizId: this.params.videoLessonGroupId,
          userId: this.recomUserId
        }
      })
      const result = res.data || {}
      const { lessonGroup, detailList } = result.videoGroup
      this.userInfo = {
        username: lessonGroup.username,
        headUrl: lessonGroup.avatar,
        isDegree: result.videoGroup.degreeFlag ? true : false,
        isTeacher: result.videoGroup.teacherFlag ? true : false,
        buyNum: lessonGroup.countStudent,
        lessonNum: lessonGroup.lessonCount,
        lessonName: lessonGroup.lessonName,
        lessonDesc: lessonGroup.lessonDesc,
        lessonPrice: lessonGroup.lessonPrice,
        relationType: lessonGroup.relationType,
        lessonCoverUrl: lessonGroup.lessonCoverUrl
      }

      this.detailList = detailList || []
    } catch {
      //
    }
  },
  methods: {
    locationReplace(url: string) {
      // alert(url)
      if (history.replaceState) {
        history.replaceState(null, document.title, url)
        window.location.reload()
      } else {
        location.replace(url)
      }
    },
    reCall() {
      const { origin } = location
      let str = origin + '/student/#/videoDetail'
      const params = this.$route.query
      str += `?recomUserId=${
        params.userType && params.userType == 'STUDENT' ? '' : this.recomUserId
      }&groupId=${params.groupId}&p=${params.p}`
      console.log(str)
      shareCall(str, {})
    },
    onShare() {
      if (browser().weixin) {
        this.wxStatus = true
        return
      }
      this.reCall()
      setTimeout(() => {
        window.location.href = location.origin + '/student/#/download'
      }, 3000)
    }
  },
  render() {
    return (
      <div class={[styles['video-detail'], 'mb12']}>
        <UserDetail userInfo={this.userInfo} showBuy={false} />
        <SectionDetail border>
          <p class={styles.introduction}>{this.userInfo.lessonDesc}</p>
        </SectionDetail>

        <SectionDetail
          title="课程列表"
          icon="courseList"
          contentStyle={{ paddingTop: '0' }}
        >
          {this.detailList.map((item: any) => {
            const musicAlbumInfos = item.musicAlbumInfos || []
            const temp = musicAlbumInfos.map((info: any) => {
              return {
                relationMusicAlbum: info.relationType,
                musicAlbumName: info.name,
                musicAlbumId: info.musicAlbumId,
                useRelationType: this.userInfo.relationType
              }
            })
            return (
              <CourseVideoItem
                musicAlbumInfos={temp}
                detail={{
                  id: item.id,
                  title: item.videoTitle,
                  content: item.videoContent,
                  imgUrl: item.coverUrl
                }}
              />
            )
          })}
        </SectionDetail>

        <ColSticky position="bottom">
          <div class={['btnGroup']} style={{ paddingTop: '12px' }}>
            <Button block round type="primary" onClick={this.onShare}>
              下载酷乐秀进入课程
            </Button>
          </div>
        </ColSticky>

        {this.wxStatus && (
          <div
            class={styles.wxpopup}
            onClick={() => {
              this.wxStatus = false
            }}
          >
            <img src={getAssetsHomeFile('wx_bg.png')} alt="" />
          </div>
        )}
      </div>
    )
  }
})
