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 } from 'vant'
import { defineComponent } from 'vue'
import styles from './live-detail.module.less'
import iconTips from '@common/images/icon_tips.png'
import { orderStatus } from '@/views/order-detail/orderStatus'
import ColHeader from '@/components/col-header'
interface IProps {
  courseTime: string
  coursePlan: string
  videoPosterUrl?: string
  id?: number | string
}
export default defineComponent({
  name: 'LiveDetail',
  data() {
    const query = this.$route.query
    return {
      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
      }
    },
    courseInfo() {
      let 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,
          id: item.courseId
        })
      })
      return tempArr || []
    },
    salesEndDate() {
      const live = this.live as any
      return dayjs(live.salesEndDate || new Date()).format('YYYY-MM-DD')
    }
  },
  async mounted() {
    try {
      const res = await request.get(
        '/api-student/courseGroup/queryLiveCourseInfo',
        {
          params: {
            groupId: this.groupId
          }
        }
      )
      this.live = res.data || {}
    } catch {}
  },
  methods: {
    async onBuy() {
      try {
        const res = await request.post(
          '/api-student/userOrder/getPendingOrder',
          {
            data: {
              goodType: 'LIVE',
              bizId: this.groupId
            }
          }
        )
        console.log(res, res.data)
        const live = this.live
        orderStatus.orderObject.orderType = 'LIVE'
        orderStatus.orderObject.orderName = '直播课购买'
        orderStatus.orderObject.orderDesc = '直播课购买'
        orderStatus.orderObject.actualPrice = live.coursePrice
        orderStatus.orderObject.orderNo = ''
        orderStatus.orderObject.orderList = [
          {
            orderType: 'LIVE',
            goodsName: '直播课购买',
            courseGroupId: live.courseGroupId,
            courseGroupName: live.courseGroupName,
            coursePrice: live.coursePrice,
            teacherName: live.teacherName || `游客${live.teacherId || ''}`,
            teacherId: live.teacherId,
            avatar: live.avatar,
            courseInfo: this.courseInfo
          }
        ]
        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
              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} />
        <SectionDetail>
          <p class={styles.introduction}>{this.userInfo.lessonDesc}</p>
        </SectionDetail>

        <SectionDetail
          title="课程列表"
          icon="courseList"
          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}>
                立即购买
              </Button>
            </div>
          </Sticky>
        )}
      </div>
    )
  }
})
