import CoursePlanStep from '@/business-components/course-plan-step'
import SectionDetail from '@/business-components/section-detail'
import UserDetail from '@/business-components/user-detail'
import ColSticky from '@/components/col-sticky'
import { postMessage, promisefiyPostMessage } from '@/helpers/native-message'
import request from '@/helpers/request'
import { browser } from '@/helpers/utils'
import { state } from '@/state'
import dayjs from 'dayjs'
import { Button, Dialog, Toast } from 'vant'
import { defineComponent } from 'vue'
import { shareCall } from '../share'
import styles from './index.module.less'
import qs from 'query-string'
import GroupPlanStep from '@/business-components/group-plan-step'
export const getAssetsHomeFile = (fileName: string) => {
  const path = `../images/${fileName}`
  const modules = import.meta.globEager('../images/*')
  return modules[path].default
}
interface IProps {
  courseTime: string
  coursePlan: string
  roomUid?: string
  teacherName: string
  subjectName: string
  liveState?: number
  id?: number | string
}
export default defineComponent({
  name: 'LiveDetail',
  data() {
    const query = this.$route.query
    return {
      recomUserId: query.recomUserId, // 分享人编号
      groupId: query.groupId,
      platform: query.p, // 来源
      live: {} as any,
      wxStatus: false
    }
  },
  computed: {
    userInfo() {
      const live = this.live as any
      const planList = live.planList || []
      const startTime = planList[0]?.startTime || new Date()
      const endTime = planList[0]?.endTime || new Date()
      return {
        headUrl: live.avatar,
        username: live.userName,
        isDegree: live.degreeFlag ? true : false,
        isTeacher: live.teacherFlag ? true : false,
        id: live.teacherId,
        startTime:
          `${dayjs(startTime).format('YYYY-MM-DD')} ${dayjs(startTime).format(
            'HH:mm'
          )}~${dayjs(endTime).format('HH:mm')}` || '',
        type: 'live',
        lessonPrice: live.coursePrice,
        buyNum: live.studentCount || 0,
        lessonNum: live.courseNum || 0, // 课时数
        lessonDesc: live.courseIntroduce,
        lessonCoverUrl: live.backgroundPic || live.backgroundPicTemplate,
        lessonName: live.courseGroupName,
        auditVersion: 0
      }
    },
    courseInfo() {
      const tempArr = [] as IProps[]
      const live = this.live
      const coursePlanList = this.live.planList || []
      coursePlanList.forEach((item: any) => {
        const startTime = item.startTime || new Date()
        const endTime = item.endTime || new Date()
        tempArr.push({
          courseTime: `${dayjs(startTime).format('YYYY-MM-DD')} ${dayjs(
            startTime
          ).format('HH:mm')}~${dayjs(endTime).format('HH:mm')}`,
          coursePlan: item.plan,
          teacherName: live.userName,
          subjectName: live.subjectName,
          roomUid: item.roomUid,
          liveState: item.liveState,
          id: item.courseId
        })
      })
      return tempArr || []
    }
  },
  created() {
    if (browser().isApp) {
      if (state.platformType === 'STUDENT') {
        // 自动跳转到学生端视频课详情购买页
        const query = this.$route.query
        query.recomUserId =
          query.userType && query.userType == 'STUDENT' ? '' : query.recomUserId
        if (browser().ios) {
          window.location.replace(
            `${location.origin}/student/#/groupDetail??${qs.stringify(query)}`
          )
        } else {
          postMessage({
            api: 'openWebView',
            content: {
              url: `${location.origin}/student/#/groupDetail??${qs.stringify(
                query
              )}`,
              orientation: 1,
              isHideTitle: false
            }
          })

          postMessage({ api: 'back' })
        }
      } 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/liveShareProfit', {
        data: {
          bizId: this.groupId,
          userId: this.recomUserId
        }
      })
      this.live = res.data.liveCourseGroup || {}
    } catch {
      //
    }
  },
  methods: {
    locationReplace(url: string) {
      if (history.replaceState) {
        history.replaceState(null, document.title, url)
        window.location.reload()
      } else {
        location.replace(url)
      }
    },
    reCall() {
      const { origin } = location
      let str = origin + '/student/#/groupDetail'
      const params = this.$route.query
      str += `?recomUserId=${
        params.userType && params.userType == 'STUDENT' ? '' : this.recomUserId
      }&groupId=${params.groupId}&p=${params.p}`
      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['live-detail'], 'mb12']}>
        <UserDetail userInfo={this.userInfo} showBuy={false} />
        <SectionDetail border>
          <p class={styles.introduction}>{this.userInfo.lessonDesc}</p>
        </SectionDetail>

        <GroupPlanStep courseInfo={this.courseInfo as any}  />

        <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>
    )
  }
})
