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 ColShare from '@/components/col-share'
import ColSticky from '@/components/col-sticky'
import { postMessage } from '@/helpers/native-message'
import request from '@/helpers/request'
import { state } from '@/state'
import LiveItem from '@/views/live-class/live-item'
import dayjs from 'dayjs'
import { Button, Popup, Sticky, Tab, Tabs, Toast } from 'vant'
import { defineComponent } from 'vue'
import styles from './live-detail.module.less'
import ColHeader from '@/components/col-header'
import TheSticky from '@/components/the-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 {
      share: query.share,
      joinRoom: query.joinRoom, // 原生传递过来的参数，判断是否进入直播间
      groupId: query.groupId,
      courseId: query.classId,
      live: {} as any,
      shareStatus: false,
      shareUrl: '',
      myself: false
    }
  },
  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,
        avatar: live.avatar,
        username: live.userName,
        id: live.teacherId,
        startTime:
          `${dayjs(startTime).format('YYYY-MM-DD')} ${dayjs(startTime).format(
            'HH:mm'
          )}` || '',
        courseStartTime: dayjs(live.courseStartTime).format('YYYY-MM-DD HH:mm'),
        lessonPrice: live.coursePrice,
        buyNum: live.studentCount || 0,
        type: 'live',
        lessonId: live.courseGroupId,
        completeCourseNum: live.completeCourseNum, // 已上课时
        isShowCourse: live.status !== 'APPLY', // 是否显示课程
        lessonNum: live.courseNum || 0, // 课时数
        lessonDesc: live.courseIntroduce,
        lessonCoverUrl: live.backgroundPic || live.backgroundPicTemplate,
        lessonName: live.courseGroupName,
        subjectName: live.subjectName,
        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 || []
    },
    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
          }
        }
      )
      this.live = res.data || {}

      if (state.platformType === 'TEACHER') {
        this.myself = !res.data.myself
      }

      this.shareUrl = `${location.origin}/teacher/#/shareLive?recomUserId=${state.user.data?.userId}&groupId=${this.groupId}&p=tenant`
      // 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 {
        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']}>
        <ColHeader />
        <UserDetail userInfo={this.userInfo} />
        <SectionDetail border>
          <p class={styles.introduction}>{this.userInfo.lessonDesc}</p>
        </SectionDetail>

        {this.myself ? (
          <SectionDetail title="课程列表" icon="courseList" border={true}>
            <CoursePlanStep
              courseInfo={this.courseInfo}
              courseId={Number(this.courseId) || 0}
            />
          </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
                  showState={
                    this.joinRoom == '1' && this.liveStatus.liveStatus !== 2
                  }
                  courseInfo={this.courseInfo}
                  courseId={Number(this.courseId) || 0}
                />
              </Tab>
              <Tab title="上课学员" titleClass="van-hairline--bottom">
                {this.studentList.map((item: any) => (
                  <UserList
                    class="mb16"
                    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.live.status !== 'OUT_SALE' && (
          <>
            {this.courseOffStatus && (
              <TheSticky position="bottom">
                <div
                  class={['btnGroup']}
                  style={{ paddingTop: '10px', background: '#fff' }}
                >
                  <Button
                    block
                    round
                    type="primary"
                    onClick={this.cancelCourseGroup}
                  >
                    取消课程
                  </Button>
                </div>
              </TheSticky>
            )}

            {this.joinRoom == '1' && this.liveStatus.liveStatus !== 2 && (
              <TheSticky position="bottom">
                <div
                  class={['btnGroup']}
                  style={{ paddingTop: '10px', background: '#fff' }}
                >
                  <Button block round type="primary" onClick={this.onJoinRoom}>
                    进入直播间
                  </Button>
                </div>
              </TheSticky>
            )}

            {this.share == '1' && this.courseInfo.length > 0 && (
              <TheSticky position="bottom">
                <div
                  class={['btnGroup']}
                  style={{ paddingTop: '10px', background: '#fff' }}
                >
                  <Button
                    block
                    round
                    type="primary"
                    onClick={() => {
                      this.shareStatus = true
                    }}
                  >
                    分享
                  </Button>
                </div>
              </TheSticky>
            )}
          </>
        )}

        <Popup
          v-model:show={this.shareStatus}
          style={{ background: 'transparent' }}
        >
          <ColShare
            teacherId={this.userInfo.id}
            shareUrl={this.shareUrl}
            shareType="live"
          >
            <LiveItem
              class={styles.shareCourse}
              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.avatar,
                studentCount: this.userInfo.buyNum,
                courseStartTime: this.userInfo.courseStartTime,
                existBuy: 0,
                subjectName: this.userInfo.subjectName
              }}
            />
          </ColShare>
        </Popup>
      </div>
    )
  }
})
