import CoursePlanStep from '@/business-components/course-plan-step'
import SectionDetail from '@/business-components/section-detail'
import UserDetail from '@/business-components/user-detail'
import UserList from '@/business-components/user-list'
import ColResult from '@/components/col-result'
import { postMessage } from '@/helpers/native-message'
import request from '@/helpers/request'
import { state } from '@/state'
import dayjs from 'dayjs'
import { Button, Sticky, Tab, Tabs, Toast } from 'vant'
import { defineComponent } from 'vue'
import styles from './live-detail.module.less'
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, // 原生传递过来的参数，判断是否进入直播间
      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: state.user.data?.heardUrl,
        username:
          state.user.data?.username || `游客${state.user.data?.userId || ''}`,
        startTime:
          `${dayjs(startTime).format('YYYY-MM-DD')} ${dayjs(startTime).format(
            'HH:mm'
          )}~${dayjs(endTime).format('HH:mm')}` || '',
        lessonPrice: live.coursePrice,
        buyNum: live.studentCount || 0,
        lessonNum: live.courseNum || 0, // 课时数
        lessonDesc: live.courseIntroduce,
        lessonCoverUrl: live.backgroundPic || live.backgroundPicTemplate,
        lessonName: live.courseGroupName
      }
    },
    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 || []
    },
    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
    },
    studentList() {
      const live = this.live as any
      return live.studentList || []
    },
    courseOffStatus() {
      const live = this.live as any
      let status = false
      if (
        (live.status === 'APPLY' && live.studentList.length === 0) ||
        live.status === 'NOT_SALE'
      ) {
        status = true
      }
      return status
    }
  },
  async mounted() {
    try {
      const res = await request.get(
        '/api-teacher/courseGroup/queryLiveCourseInfo',
        {
          params: {
            groupId: this.groupId
          }
        }
      )
      console.log(res)
      this.live = res.data || {}

      console.log(this.live)
    } catch {
      //
    }
  },
  methods: {
    async onJoinRoom() {
      try {
        const res = await request.get(
          '/api-teacher/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
          }
        })
        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 cancelCourseGroup() {
      try {
        const res = await request.get(
          '/api-teacher/courseGroup/cancelCourseGroup',
          {
            params: {
              groupId: this.groupId
            }
          }
        )
        Toast('下架成功')
        setTimeout(() => {
          postMessage({ api: 'back', content: {} })
        }, 500)
      } catch {}
    }
  },
  render() {
    return (
      <div class={[styles['live-detail'], 'mb12']}>
        <UserDetail userInfo={this.userInfo} />
        <SectionDetail>
          <p class={styles.introduction}>{this.userInfo.lessonDesc}</p>
        </SectionDetail>

        <SectionDetail
          title="课程列表"
          icon="courseList"
          titleShow={false}
          contentStyle={{ paddingTop: '0' }}
        >
          <Tabs color="var(--van-primary)" lineWidth={20} sticky>
            <Tab title="课程" titleClass="van-hairline--bottom">
              <CoursePlanStep
                courseInfo={this.courseInfo}
                courseId={Number(this.courseId) || 0}
              />
            </Tab>
            <Tab title="学员列表" titleClass="van-hairline--bottom">
              {this.studentList.map((item: any) => (
                <UserList
                  class="mb12"
                  users={{
                    avatar: item.avatar,
                    studentId: item.studentId,
                    studentName: item.userName,
                    createTime: item.createTime
                  }}
                />
              ))}
              {this.studentList.length === 0 && (
                <ColResult
                  tips="暂无购买学员"
                  classImgSize="SMALL"
                  btnStatus={false}
                />
              )}
            </Tab>
          </Tabs>
        </SectionDetail>

        {this.courseOffStatus && (
          <Sticky offsetBottom={0} position="bottom">
            <div class={['btnGroup']} style={{ paddingTop: '12px' }}>
              <Button
                block
                round
                type="primary"
                onClick={this.cancelCourseGroup}
              >
                下架
              </Button>
            </div>
          </Sticky>
        )}

        {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>
        )}
      </div>
    )
  }
})
