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 { 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 { state } from '@/state'
import { browser } from '@/helpers/utils'
export default defineComponent({
  name: 'VideoDetail',
  data() {
    const query = this.$route.query
    return {
      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() {
    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 = `${location.origin}/teacher#/shareVideo?recomUserId=${state.user.data?.userId}&groupId=${this.params.groupId}&userType=${state.platformType}&p=tenant`
    }
  },
  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 teachertTag = result.teachertTag || ''
        this.userInfo = {
          alreadyBuy: result.alreadyBuy,
          username:
            lessonGroup.username || `游客${lessonGroup.teacherId || ''}`,
          headUrl: lessonGroup.avatar,
          buyNum: lessonGroup.countStudent,
          id: lessonGroup.id,
          lessonNum: lessonGroup.lessonCount,
          lessonName: lessonGroup.lessonName,
          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
        }
      })
    },
    async onBuy() {
      try {
        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,
            teacherName: userInfo.username || `游客${userInfo.teacherId || ''}`,
            teacherId: userInfo.teacherId,
            avatar: userInfo.headUrl,
            relationType: this.userInfo.relationType,
            courseInfo: this.detailList,
            recomUserId: this.recomUserId
          }
        ]

        // 判断是否是0无订单
        if (userInfo.lessonPrice <= 0) {
          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.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 {}
    }
  },
  render() {
    return (
      <div class={[styles['video-detail']]}>
        <ColHeader
          v-slots={{
            right: () => (
              <img src={iconShare} onClick={() => (this.shareStatus = true)} />
            )
          }}
        />
        <UserDetail
          userInfo={this.userInfo}
          onUserDetail={(item: any) => {
            console.log(item)
            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>
          <ColSticky position="bottom" background="white">
            <div class={['btnGroup', styles.btnMore]}>
              <Button
                block
                round
                type="primary"
                onClick={this.onBuy}
                disabled={this.platformStatus}
              >
                {this.userInfo.lessonPrice <= 0 ? '免费领取' : `立即购买`}
              </Button>
            </div>
          </ColSticky>
        )}

        <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,
                teacherId: this.userInfo.id,
                avatar: this.userInfo.headUrl,
                studentCount: this.userInfo.buyNum,
                existBuy: 0,
                subjectName: this.userInfo.lessonSubjectName
              }}
            />
          </ColShare>
        </Popup>
      </div>
    )
  }
})
