import CourseVideoItem from '@/business-components/course-video-item'
import SectionDetail from '@/business-components/section-detail'
import UserDetail from '@/business-components/user-detail'
import UserList from '@/business-components/user-list'
import { Button, Dialog, List, Popup, Sticky, Tab, Tabs, Toast } from 'vant'
import { defineComponent } from 'vue'
import styles from './video-detail.module.less'
import request from '@/helpers/request'
import ColResult from '@/components/col-result'
import ColShare from '@/components/col-share'
import ColSticky from '@/components/col-sticky'
import LiveItem from '@/views/live-class/live-item'
import { state } from '@/state'
import { postMessage } from '@/helpers/native-message'
import ColHeader from '@/components/col-header'
export default defineComponent({
  name: 'VideoDetail',
  data() {
    const query = this.$route.query
    return {
      userInfo: {} as any,
      detailList: [],
      musicAlbumInfos: [], // 关联曲目或专辑"
      buyUserList: [], // 购买学生数
      dataShow: true, // 判断是否有数据
      loading: false,
      finished: false,
      share: query.share,
      params: {
        videoLessonGroupId: query.groupId,
        page: 1,
        rows: 20
      },
      shareStatus: false,
      shareUrl: '',
      shelvesFlag: 0,
      myself: false
    }
  },
  async mounted() {
    try {
      const res = await request.get(
        '/api-teacher/videoLessonGroup/selectVideoLesson',
        {
          params: {
            groupId: this.params.videoLessonGroupId
          }
        }
      )
      const result = res.data || {}
      if (state.platformType === 'TEACHER') {
        this.myself = !result.myself
      }
      this.userInfo = {
        id: result.lessonGroup.teacherId,
        username: result.lessonGroup.username,
        headUrl: result.lessonGroup.avatar,
        buyNum: result.lessonGroup.countStudent,
        lessonId: result.lessonGroup.id,
        lessonNum: result.lessonGroup.lessonCount,
        lessonName: result.lessonGroup.lessonName,
        lessonDesc: result.lessonGroup.lessonDesc,
        lessonPrice: result.lessonGroup.lessonPrice,
        lessonCoverUrl: result.lessonGroup.lessonCoverUrl,
        relationType: result.lessonGroup.relationType,
        lessonSubjectName: result.lessonGroup.lessonSubjectName,
        auditVersion: result.lessonGroup.auditVersion,
        isDegree: result.degreeFlag ? true : false,
        isTeacher: result.teacherFlag ? true : false,
        alreadyBuy: result.alreadyBuy
      }

      this.shelvesFlag = result.lessonGroup.shelvesFlag
      this.detailList = result.detailList || []

      // shareVideo?recomUserId=56&groupId=124
      this.shareUrl = `${location.origin}/teacher/#/shareVideo?recomUserId=${state.user.data?.userId}&groupId=${this.params.videoLessonGroupId}&p=tenant`
      !this.myself && this.getList()
    } catch (e) {
      console.log(e)
    }
  },
  methods: {
    async getList() {
      try {
        const params = this.params
        const res = await request.post('/api-teacher/videoLesson/pageStudent', {
          data: {
            ...params
          }
        })
        this.loading = false
        const result = res.data || {}
        // 处理重复请求数据
        if (this.buyUserList.length > 0 && result.pageNo === 1) {
          return
        }
        this.buyUserList = this.buyUserList.concat(result.rows || [])
        this.finished = result.pageNo >= result.totalPage
        this.params.page = result.pageNo + 1
        this.dataShow = this.buyUserList.length > 0
      } catch {
        this.dataShow = false
        this.finished = true
      }
    },
    onPlay(detail: any) {
      this.$router.push({
        path: '/videoClassDetail',
        query: {
          groupId: this.params.videoLessonGroupId,
          classId: detail.id
        }
      })
    },
    async updateShelves() {
      Dialog.confirm({
        title: '提示',
        message: '确认下架该课程吗？',
        confirmButtonColor: 'var(--van-primary)'
      }).then(async () => {
        try {
          // 下架
          await request.post('/api-teacher/videoLessonGroup/updateShelves', {
            data: {
              id: this.userInfo.lessonId,
              shelvesFlag: 0
            }
          })

          Toast('下架成功')
          setTimeout(() => {
            postMessage({ api: 'back' })
          }, 800)
        } catch {
          //
        }
      })
    }
  },
  render() {
    return (
      <div class={[styles['video-detail'], 'mb12']}>
        <ColHeader />
        {this.userInfo.id && <UserDetail userInfo={this.userInfo} />}
        <SectionDetail border>
          <p class={styles.introduction}>{this.userInfo.lessonDesc}</p>
        </SectionDetail>

        {this.myself ? (
          <SectionDetail title="课程列表" icon="courseList" border={true}>
            {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}
                  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>
        ) : (
          <SectionDetail
            title="课程列表"
            icon="courseList"
            titleShow={false}
            contentStyle={{ paddingTop: '0' }}
          >
            <Tabs color="var(--van-primary)" lineWidth={20} sticky>
              <Tab title="课程" titleClass="van-hairline--bottom">
                {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}
                      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
                          })
                        }
                      }}
                    />
                  )
                })}
              </Tab>
              <Tab title="学员列表" titleClass="van-hairline--bottom">
                {this.dataShow ? (
                  <List
                    v-model:loading={this.loading}
                    finished={this.finished}
                    finishedText="没有更多了"
                    onLoad={this.getList}
                  >
                    {this.buyUserList.map((item: any) => (
                      <UserList
                        class="mb12"
                        users={{
                          avatar: item.avatar,
                          studentId: item.userId,
                          studentName: item.username,
                          createTime: item.createTime
                        }}
                      />
                    ))}
                  </List>
                ) : (
                  <ColResult
                    btnStatus={false}
                    classImgSize="SMALL"
                    tips="暂无学生购买"
                  />
                )}
              </Tab>
            </Tabs>
          </SectionDetail>
        )}

        {this.shelvesFlag === 1 && (
          <>
            {this.share == '1' && this.detailList.length > 0 && (
              <ColSticky position="bottom" background="white">
                <div class={['btnGroup']} style={{ paddingTop: '12px' }}>
                  <Button
                    block
                    round
                    type="primary"
                    onClick={() => {
                      this.shareStatus = true
                    }}
                  >
                    分享课程
                  </Button>
                </div>
              </ColSticky>
            )}
            {this.share != '1' && this.detailList.length > 0 && (
              <ColSticky position="bottom" background="white">
                <div class={['btnGroup']} style={{ paddingTop: '12px' }}>
                  <Button
                    block
                    round
                    type="primary"
                    onClick={this.updateShelves}
                  >
                    下架
                  </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>
    )
  }
})
