import CourseVideoItem from '@/business-components/course-video-item'
import SectionDetail from '@/business-components/section-detail'
import UserDetail from '@/business-components/user-detail'
import { Sticky, Button, Dialog, Popup, Toast } from 'vant'
import { postMessage } from '@/helpers/native-message'
import { defineComponent } from 'vue'
import styles from './video-detail.module.less'
import request from '@/helpers/request'
import ColHeader from '@/components/col-header'
import { onSubmitZero, orderStatus } from '@/views/order-detail/orderStatus'
import { tradeOrder } from '../trade/tradeOrder'
import ColSticky from '@/components/col-sticky'
import iconShare from '@/views/shop-mall/images/icon-share.svg'
import ColShare from '@/components/col-share'
import LiveItem from '@/views/live-class/live-item'
import { setLogin, state } from '@/state'
import { browser, getHttpOrigin } from '@/helpers/utils'
import { usePageVisibility } from '@vant/use'
import TheSticky from '@/components/the-sticky'
import { useStatisticTracking } from '@/helpers/hooks'
export default defineComponent({
  name: 'VideoDetail',
  data() {
    const query = this.$route.query
    return {
      pageVisibility: 'visible' as any,
      userInfo: {} as any,
      detailList: [],
      recomUserId: query.recomUserId, // 推荐人id
      params: {
        groupId: query.groupId
      },
      platform: query.p, // 属于哪个平台，//机构老师 tenant，平台老师 无
      shareStatus: false,
      shareUrl: ''
    }
  },
  computed: {
    platformStatus() {
      const userInfo = state.user.data as any

      // 是机构学生 并且 是机构老师分享
      const query = this.$route.query
      return userInfo.tenantId > 0 && query.p == 'tenant'
    }
  },
  async mounted() {
    this.pageVisibility = usePageVisibility()
    await this._init()
    // if (/(localhost|192)/g.test(location.origin)) {
    //   this.shareUrl = `https://dev.colexiu.com/teacher#/shareVideo?recomUserId=${state.user.data?.userId}&groupId=${this.params.groupId}&userType=${state.platformType}&p=tenant`
    // } else {
      this.shareUrl = `${getHttpOrigin()}/teacher#/shareVideo?recomUserId=${state.user.data?.userId}&groupId=${this.params.groupId}&userType=${state.platformType}&p=tenant`
    // }

    /** 埋点 */
    useStatisticTracking({
      objectType: "VIDEO",
      objectId: this.params.groupId as any
    })
  },
  methods: {
    async _init() {
      try {
        const res = await request.get(
          '/api-student/videoLesson/selectVideoLesson',
          {
            params: {
              groupId: this.params.groupId
            }
          }
        )
        const result = res.data || {}
        const lessonGroup = result.lessonGroup || {}
        const userInfo = state.user.data as any
        const alreadyBuy =
          lessonGroup.payType === 'VIP'
            ? result.alreadyBuy || userInfo.userVip?.vipType !== 'NOT_VIP'
              ? true
              : false
            : result.alreadyBuy

        this.userInfo = {
          alreadyBuy: alreadyBuy,
          username:
            lessonGroup.username || `游客${lessonGroup.teacherId || ''}`,
          headUrl: lessonGroup.avatar,
          buyNum: lessonGroup.countStudent,
          id: lessonGroup.id,
          lessonNum: lessonGroup.lessonCount,
          lessonName: lessonGroup.lessonName,
          payType: lessonGroup.payType,
          type: 'video',
          subjectName: lessonGroup.lessonSubjectName,
          lessonDesc: lessonGroup.lessonDesc,
          lessonPrice: lessonGroup.lessonPrice,
          relationType: lessonGroup.relationType,
          teacherId: lessonGroup.teacherId,
          lessonCoverUrl: lessonGroup.lessonCoverUrl,
          auditVersion: lessonGroup.auditVersion,
          isDegree: result.degreeFlag ? true : false,
          isTeacher: result.teacherFlag ? true : false
        }
        this.detailList = result.detailList || []
      } catch {
        //
      }
    },
    onPlay(detail: any) {
      this.$router.push({
        path: '/videoClassDetail',
        query: {
          groupId: this.params.groupId,
          classId: detail.id
        }
      })
    },
    initVideo () {
      const userInfo = this.userInfo
      orderStatus.orderObject.orderType = 'VIDEO'
      orderStatus.orderObject.orderName = '视频课购买'
      orderStatus.orderObject.orderDesc = '视频课购买'
      orderStatus.orderObject.actualPrice = userInfo.lessonPrice
      orderStatus.orderObject.recomUserId = this.recomUserId
      orderStatus.orderObject.orderNo = ''
      orderStatus.orderObject.orderList = [
        {
          orderType: 'VIDEO',
          goodsName: '视频课购买',
          courseGroupId: userInfo.id,
          courseGroupName: userInfo.lessonName,
          coursePrice: userInfo.lessonPrice,
          price: userInfo.lessonPrice,
          teacherName: userInfo.username || `游客${userInfo.teacherId || ''}`,
          teacherId: userInfo.teacherId,
          avatar: userInfo.headUrl,
          relationType: this.userInfo.relationType,
          courseInfo: this.detailList,
          recomUserId: this.recomUserId
        }
      ]
    },
    async onBuy() {
      try {
        if (this.userInfo.payType === 'VIP') {
          if (browser().isApp) {
            postMessage({
              api: 'openWebView',
              content: {
                url: `${getHttpOrigin()}${location.pathname}#/memberCenter`,
                orientation: 1,
                isHideTitle: false
              }
            })
          } else {
            this.$router.push({
              path: '/memberCenter'
            })
          }
          return
        }

        // const userInfo = this.userInfo

        // 判断是否是0无订单
        // if (userInfo.lessonPrice <= 0) {
        //   this.initVideo()
        //   await onSubmitZero(() => {
        //     Dialog.alert({
        //       message: '领取成功',
        //       confirmButtonText: '确定',
        //       confirmButtonColor: '#2dc7aa'
        //     }).then(() => {
        //       this._init()
        //     })
        //   })
        //   return
        // }

        const res = await request.post(
          '/api-student/userOrder/getPendingOrder',
          {
            data: {
              goodType: 'VIDEO',
              bizId: this.params.groupId
            }
          }
        )
        const result = res.data
        if (result) {
          Dialog.confirm({
            title: '提示',
            message: '您有一个未支付的订单，是否继续支付？',
            confirmButtonColor: '#269a93',
            cancelButtonText: '取消订单',
            confirmButtonText: '继续支付'
          })
            .then(async () => {
              tradeOrder(result, this.routerTo)
            })
            .catch(() => {
              Dialog.close()
              // 只用取消订单，不用做其它处理
              this.cancelPayment(result.orderNo)
            })
        } else {
          this.initVideo()
          this.routerTo()
        }
      } catch {}
    },
    routerTo() {
      this.$router.push({
        path: '/orderDetail',
        query: {
          orderType: 'VIDEO',
          courseGroupId: this.params.groupId
        }
      })
    },
    async cancelPayment(orderNo: string) {
      try {
        await request.post('/api-student/userOrder/orderCancel', {
          data: {
            orderNo
          }
        })
      } catch {}
    }
  },
  watch: {
    pageVisibility() {
      // 如果不是会员则不用刷新
      if (this.userInfo.payType !== 'VIP') {
        return
      }
      if(this.pageVisibility === 'visible') {
        request
        .get('/api-student/student/queryUserInfo', {
          initRequest: true // 初始化接口
        })
        .then((res: any) => {
          setLogin(res.data)
          this.userInfo.alreadyBuy = this.userInfo.alreadyBuy || res.data.userVip?.vipType !== 'NOT_VIP'
            ? true
            : false
        })
      }
    }
  },
  render() {
    return (
      <div class={[styles['video-detail']]}>
        <ColHeader
          v-slots={{
            right: () => (
              <img src={iconShare} onClick={() => (this.shareStatus = true)} />
            )
          }}
        />
        <UserDetail
          userInfo={this.userInfo}
          showBuy={false}
          onUserDetail={(item: any) => {
            if (browser().isApp && state.platformType === 'STUDENT') {
              this.$router.push({
                path: '/teacherHome',
                query: {
                  teacherId: item.teacherId,
                  tabs: 'video'
                }
              })
            }
          }}
        />
        <SectionDetail border={false}>
          <p class={styles.introduction}>{this.userInfo.lessonDesc}</p>
        </SectionDetail>

        <SectionDetail
          title="课程列表"
          icon="courseList"
          class="mb12"
          border={false}
        >
          {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,
                status: info.status, // 是否上架
                useRelationType: this.userInfo.relationType
              }
            })
            return (
              <CourseVideoItem
                musicAlbumInfos={temp}
                class={[styles.videoItem]}
                detail={{
                  id: item.id,
                  title: item.videoTitle,
                  content: item.videoContent,
                  imgUrl: item.coverUrl
                }}
                onPlay={this.onPlay}
                onMusicAlbumDetail={(item: any) => {
                  if (!this.userInfo.alreadyBuy && !item.status) {
                    Toast('数据正在更新，请稍后再试')
                    return
                  }
                  if (item.relationMusicAlbum === 'MUSIC') {
                    this.$router.push({
                      path: '/music-detail',
                      query: {
                        id: item.musicAlbumId
                      }
                    })
                  } else if (item.relationMusicAlbum === 'ALBUM') {
                    this.$router.push({
                      path: '/music-album-detail/' + item.musicAlbumId
                    })
                  }
                }}
              />
            )
          })}
        </SectionDetail>

        {this.userInfo.id && !this.userInfo.alreadyBuy && (
          // <Sticky offsetBottom={0} position="bottom">
          //   <div class={['btnGroup', styles.btnMore]}>
          //     <Button block round type="primary" onClick={this.onBuy}>
          //       {this.userInfo.lessonPrice <= 0 ? '免费领取' : `立即购买`}
          //     </Button>
          //   </div>
          // </Sticky>
          <TheSticky position="bottom">
            <div class={['btnGroup', styles.btnMore]}>
              <Button
                block
                round
                type="primary"
                onClick={this.onBuy}
                disabled={this.platformStatus}
              >
                {this.userInfo.payType === 'VIP'
                  ? '开通会员'
                  : this.userInfo.lessonPrice <= 0
                  ? '免费领取'
                  : `立即购买`}
              </Button>
            </div>
          </TheSticky>
        )}

        <Popup
          v-model:show={this.shareStatus}
          style={{ background: 'transparent' }}
        >
          <ColShare
            teacherId={this.userInfo.id}
            shareUrl={this.shareUrl}
            shareType="video"
          >
            <LiveItem
              class={styles.shareCourse}
              coverClass={styles.coverClass}
              liveInfo={{
                backgroundPic: this.userInfo.lessonCoverUrl,
                courseGroupId: this.userInfo.lessonId,
                courseGroupName: this.userInfo.lessonName,
                courseNum: this.userInfo.lessonNum,
                coursePrice: this.userInfo.lessonPrice,
                teacherName: this.userInfo.username,
                payType: this.userInfo.payType,
                teacherId: this.userInfo.id,
                avatar: this.userInfo.headUrl,
                studentCount: this.userInfo.buyNum,
                existBuy: 0,
                subjectName: this.userInfo.lessonSubjectName
              }}
            />
          </ColShare>
        </Popup>
      </div>
    )
  }
})
