import CoursePlanStep from '@/business-components/course-plan-step'
import SectionDetail from '@/business-components/section-detail'
import UserDetail from '@/business-components/user-detail'
import request from '@/helpers/request'
import dayjs from 'dayjs'
import { Icon, Sticky, Button, Dialog, Toast } from 'vant'
import { defineComponent } from 'vue'
import styles from './live-detail.module.less'
import iconTips from '@common/images/icon_tips.png'
import { onSubmitZero, orderStatus } from '@/views/order-detail/orderStatus'
import ColHeader from '@/components/col-header'
import { postMessage } from '@/helpers/native-message'
import ColSticky from '@/components/col-sticky'
interface IProps {
  courseTime: string
  coursePlan: string
  videoPosterUrl?: string
  roomUid?: string
  liveState?: number
  id?: number | string
}
export default defineComponent({
  name: 'LiveDetail',
  data() {
    const query = this.$route.query
    return {
      joinRoom: query.joinRoom, // 原生传递过来的参数，判断是否进入直播间
      recomUserId: query.recomUserId, // 推荐人id
      groupId: query.groupId,
      courseId: query.classId,
      live: {} as any
    }
  },
  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 || `游客${live.teacherId || ''}`,
        startTime:
          `${dayjs(startTime).format('YYYY-MM-DD')} ${dayjs(startTime).format(
            'HH:mm'
          )}~${dayjs(endTime).format('HH:mm')}` || '',
        buyNum: live.studentCount,
        lessonPrice: live.coursePrice,
        lessonNum: live.courseNum,
        lessonDesc: live.courseIntroduce,
        lessonCoverUrl: live.backgroundPic || live.backgroundPicTemplate,
        lessonName: live.courseGroupName,
        auditVersion: live.auditVersion || 0,
        isDegree: live.degreeFlag ? true : false,
        isTeacher: live.teacherFlag ? true : false
      }
    },
    courseInfo() {
      const tempArr = [] as IProps[]
      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,
          roomUid: item.roomUid,
          liveState: item.liveState,
          id: item.courseId
        })
      })
      return tempArr || []
    },
    salesEndDate() {
      const live = this.live as any
      return dayjs(live.salesEndDate || new Date()).format('YYYY-MM-DD')
    },
    liveStatus() {
      const coursePlanList = this.live.planList || []
      const tempObj = {
        status: false,
        liveStatus: 0,
        roomUid: ''
      }
      coursePlanList.forEach((item: any) => {
        if (item.courseId === Number(this.courseId)) {
          tempObj.status = true
          tempObj.liveStatus = item.liveStatus
          tempObj.roomUid = item.roomUid
        }
      })
      return tempObj
    }
  },
  async mounted() {
    await this._init()
  },
  methods: {
    async _init() {
      try {
        const res = await request.get(
          '/api-student/courseGroup/queryLiveCourseInfo',
          {
            params: {
              groupId: this.groupId
            }
          }
        )
        this.live = res.data || {}
      } catch {}
    },
    async onJoinRoom() {
      try {
        const res = await request.get(
          '/api-student/courseGroup/queryLiveCourseInfo',
          {
            params: {
              groupId: this.groupId
            }
          }
        )
        const result = res.data || {}
        const coursePlanList = result.planList || []
        let tempObj: any = {}
        coursePlanList.forEach((item: any) => {
          if (item.courseId === Number(this.courseId)) {
            tempObj = item
          }
        })
        console.log(tempObj, this.live, 'tempObj')
        if (tempObj && tempObj.liveState === 1) {
          postMessage({
            api: 'joinLiveRoom',
            content: {
              roomId: tempObj.roomUid,
              teacherId: this.live.teacherId
            }
          })
        } else if (tempObj && tempObj.liveState === 2) {
          setTimeout(() => {
            Toast('课程已结束')
          }, 100)
        } else {
          setTimeout(() => {
            Toast('课程尚未开始，请耐心等候')
          }, 100)
        }
      } catch {}
    },
    async onBuy() {
      try {
        const live = this.live
        orderStatus.orderObject.orderType = 'LIVE'
        orderStatus.orderObject.orderName = '直播课购买'
        orderStatus.orderObject.orderDesc = '直播课购买'
        orderStatus.orderObject.actualPrice = live.coursePrice
        orderStatus.orderObject.recomUserId = this.recomUserId
        orderStatus.orderObject.orderNo = ''
        orderStatus.orderObject.orderList = [
          {
            orderType: 'LIVE',
            goodsName: '直播课购买',
            courseGroupId: live.courseGroupId,
            courseGroupName: live.courseGroupName,
            coursePrice: live.coursePrice,
            teacherName: live.userName || `游客${live.teacherId || ''}`,
            teacherId: live.teacherId,
            avatar: live.avatar,
            courseInfo: this.courseInfo,
            recomUserId: this.recomUserId
          }
        ]
        // 判断是否是0无订单
        if (live.coursePrice <= 0) {
          await onSubmitZero(() => {
            Dialog.alert({
              message: '领取成功',
              confirmButtonText: '确定',
              confirmButtonColor: '#2dc7aa'
            }).then(() => {
              this._init()
            })
          })
          return
        }
        const res = await request.post(
          '/api-student/userOrder/getPendingOrder',
          {
            data: {
              goodType: 'LIVE',
              bizId: this.groupId
            }
          }
        )

        const result = res.data
        if (result) {
          Dialog.confirm({
            title: '提示',
            message: '您有一个未支付的订单，是否继续支付？',
            confirmButtonColor: '#269a93',
            cancelButtonText: '取消订单',
            confirmButtonText: '继续支付'
          })
            .then(async () => {
              orderStatus.orderObject.orderNo = result.orderNo
              orderStatus.orderObject.actualPrice = result.actualPrice
              orderStatus.orderObject.discountPrice = result.discountPrice
              this.routerTo()
            })
            .catch(() => {
              Dialog.close()
              // 只用取消订单，不用做其它处理
              this.cancelPayment(result.orderNo)
            })
        } else {
          this.routerTo()
        }
      } catch {
        //
      }
    },
    routerTo() {
      const live = this.live
      this.$router.push({
        path: '/orderDetail',
        query: {
          orderType: 'LIVE',
          courseGroupId: live.courseGroupId
        }
      })
    },
    async cancelPayment(orderNo: string) {
      try {
        await request.post('/api-student/userOrder/orderCancel', {
          data: {
            orderNo
          }
        })
        // this.routerTo()
      } catch {}
    }
  },
  render() {
    return (
      <div class={[styles['live-detail'], 'mb12']}>
        <ColHeader />
        <UserDetail userInfo={this.userInfo} showBuy={false} />
        <SectionDetail border>
          <p class={styles.introduction}>{this.userInfo.lessonDesc}</p>
        </SectionDetail>

        <SectionDetail
          title="课程列表"
          icon="courseList"
          border
          contentStyle={{ paddingTop: '0' }}
        >
          {this.courseInfo.length > 0 && (
            <CoursePlanStep
              courseInfo={this.courseInfo}
              courseId={Number(this.courseId) || 0}
            />
          )}
        </SectionDetail>

        <div class={styles.tips}>
          <h3>
            <Icon name={iconTips} size={15} />
            温馨提示
          </h3>
          <p>
            1、该直播课程销售截止后，报名人数若少于
            {this.live.mixStudentNum || 0}
            人将取消开课，已购买学员付费金额将自动返还，请您放心购买；
            <br />
            2、直播课教学计划中的上课时间为老师预计时间，实际上课时间以老师开启直播时间为准；
            <br />
            3、若您错过老师直播，可通过视频回放观看完整课程。
          </p>
        </div>
        {this.courseInfo.length > 0 && this.live.existBuy !== 1 && (
          // <Sticky offsetBottom={0} position="bottom">
          //   <div class={['btnGroup', styles.btnMore]}>
          //     <Button block round type="primary" onClick={this.onBuy}>
          //       {this.live.coursePrice <= 0 ? '免费领取' : `立即购买`}
          //     </Button>
          //   </div>
          // </Sticky>
          <ColSticky position="bottom" background="white">
            <div class={['btnGroup', styles.btnMore]}>
              <Button block round type="primary" onClick={this.onBuy}>
                {this.live.coursePrice <= 0 ? '免费领取' : `立即购买`}
              </Button>
            </div>
          </ColSticky>
        )}

        {this.joinRoom == '1' && this.liveStatus.liveStatus !== 2 && (
          // <Sticky offsetBottom={0} position="bottom">
          //   <div class={['btnGroup']} style={{ paddingTop: '12px' }}>
          //     <Button block round type="primary" onClick={this.onJoinRoom}>
          //       进入直播间
          //     </Button>
          //   </div>
          // </Sticky>
          <ColSticky position="bottom" background="white">
            <div class={['btnGroup']} style={{ paddingTop: '12px' }}>
              <Button block round type="primary" onClick={this.onJoinRoom}>
                进入直播间
              </Button>
            </div>
          </ColSticky>
        )}
      </div>
    )
  }
})
