import { Cell, Dialog, Icon, Image, List, Rate, Sticky, Toast } from 'vant'
import { defineComponent } from 'vue'
import styles from './model/teacher-header.module.less'
import iconTeacher from '@common/images/icon_teacher.png'
import musicCert from '@common/images/music_cert.png'
import teacherCert from '@common/images/teacher_cert.png'
import request from '@/helpers/request'
import ColResult from '@/components/col-result'
import { postMessage } from '@/helpers/native-message'
import ColSearch from '@/components/col-search'
import IconXueli from '@common/images/icon-xueli.png'
import IconJiaozi from '@common/images/icon-jiaozi.png'
import dayjs from 'dayjs'
export const getAssetsHomeFile = (fileName: string) => {
  const path = `./images/${fileName}`
  const modules = import.meta.globEager('./images/*')
  return modules[path].default
}

export default defineComponent({
  name: 'teacher-follow',
  data() {
    return {
      userInfo: {} as any,
      starGrade: 0,
      subjectNameList: [],
      list: [],
      dataShow: true, // 判断是否有数据
      loading: false,
      finished: false,
      params: {
        username: '',
        page: 1,
        rows: 20
      }
    }
  },
  mounted() {
    this.getList()
  },
  methods: {
    getSubjectNameList(subject: string) {
      const subjectList = subject.split(',')
      return subjectList || []
    },
    onSearch(val: string) {
      this.params.username = val
      this.onSort()
    },
    onSort() {
      this.params.page = 1
      this.list = []
      this.dataShow = true // 判断是否有数据
      this.loading = false
      this.finished = false
      this.getList()
    },
    async getList() {
      try {
        const params = this.params
        const res = await request.post('/api-student/student/queryMyFollow', {
          data: {
            ...params
          }
        })
        this.loading = false
        const result = res.data || {}
        // 处理重复请求数据
        if (this.list.length > 0 && result.pageNo === 1) {
          return
        }
        this.list = this.list.concat(result.rows || [])
        this.finished = result.pageNo >= result.totalPage
        this.params.page = result.pageNo + 1
        this.dataShow = this.list.length > 0
      } catch {
        this.dataShow = false
        this.finished = true
      }
    },
    async onUnLike(item: any) {
      Dialog.confirm({
        message: '确定取消关注吗？',
        confirmButtonColor: 'var(--van-primary)'
      }).then(async () => {
        try {
          await request.get('/api-student/teacher/starOrUnStar', {
            params: {
              userId: item.userId,
              starStatus: 0
            }
          })
          Toast('取消关注成功')
          setTimeout(() => {
            this.onSort()
          }, 1000)
        } catch {}
      })
    },
    // 检验是否有对应徽章
    checkBadge(type: string, item: any) {
      // tag : 老师点亮图标
      // STYLE:个人风采
      // VIDEO：视频课
      // LIVE：直播课，
      // MUSIC：曲目 逗号隔开
      let status = false
      switch (type) {
        case 'STYLE':
        case 'VIDEO':
        case 'LIVE':
        case 'MUSIC':
          if (item.tag) {
            status = item.tag.indexOf(type) > -1
          }
          break
        case 'VIP':
          if (item.membershipStartTime && item.membershipEndTime) {
            const startTime = dayjs(item.membershipStartTime).valueOf()
            const endTime = dayjs(item.membershipEndTime).valueOf()
            const nowTime = dayjs().valueOf()
            status = nowTime >= startTime && nowTime <= endTime
          } else {
            status = false
          }
          break
        case 'DEGREE':
          status = item.degreeFlag ? true : false
          break
        case 'TEACHER':
          status = item.teacherFlag ? true : false
          break
        default:
          status = false
          break
      }
      return status
    }
  },
  render() {
    return (
      <div class={styles.teacherFollow}>
        <Sticky position="top" offsetTop={0}>
          <ColSearch onSearch={this.onSearch} />
        </Sticky>
        {this.dataShow ? (
          <List
            class={styles.liveList}
            v-model:loading={this.loading}
            immediateCheck={false}
            finished={this.finished}
            finishedText="没有更多了"
          >
            {this.list.map((item: any) => (
              <div
                class={[styles.headerCount, styles.headerFollow]}
                onClick={(e: MouseEvent) => {
                  e.stopPropagation()
                  sessionStorage.removeItem('teacherHomeTabs')
                  this.$router.push({
                    path: '/teacherHome',
                    query: {
                      teacherId: item.userId,
                      tabs: 'single'
                    }
                  })
                }}
              >
                <div class={styles.followContainer}>
                  <div class={styles.teacherContent}>
                    <div
                      class={styles.teacherIcon}
                      onClick={e => {
                        // 判断是否在直播中
                        if (item.liveFlag === 1) {
                          e.stopPropagation()
                          postMessage({
                            api: 'joinLiveRoom',
                            content: {
                              roomId: item.roomUid,
                              teacherId: item.userId
                            }
                          })
                        }
                      }}
                    >
                      <Image
                        class={[
                          styles.avatar,
                          this.checkBadge('VIP', item.teacher) &&
                            styles.avatarActive
                        ]}
                        round
                        src={item.avatar || iconTeacher}
                        fit="cover"
                      />

                      {item.liveFlag === 1 && (
                        <p class={styles.liveTag}>直播中</p>
                      )}

                      <Image
                        class={styles.teacherIconVip}
                        src={
                          this.checkBadge('VIP', item.teacher)
                            ? getAssetsHomeFile('vip_active.png')
                            : getAssetsHomeFile('vip_default.png')
                        }
                      />
                    </div>
                  </div>

                  <div>
                    <div class={styles.teacherInfo}>
                      <div class={styles.teacherInfoName}>
                        {item.userName || `游客${item.userId || ''}`}
                      </div>
                      {this.checkBadge('DEGREE', item.teacher) && (
                        <img src={IconXueli} />
                      )}
                      {this.checkBadge('TEACHER', item.teacher) && (
                        <img src={IconJiaozi} />
                      )}
                    </div>
                    <div class={styles.teacherHonor}>
                      <div>勋章:</div>
                      <div class={styles.teacherIcons}>
                        <Image
                          class={styles.iconOther}
                          src={
                            this.checkBadge('STYLE', item.teacher)
                              ? getAssetsHomeFile('cert_active.png')
                              : getAssetsHomeFile('cert_default.png')
                          }
                        />
                        <Image
                          class={styles.iconOther}
                          src={
                            this.checkBadge('VIDEO', item.teacher)
                              ? getAssetsHomeFile('video_active.png')
                              : getAssetsHomeFile('video_default.png')
                          }
                        />
                        <Image
                          class={styles.iconOther}
                          src={
                            this.checkBadge('LIVE', item.teacher)
                              ? getAssetsHomeFile('live_active.png')
                              : getAssetsHomeFile('live_default.png')
                          }
                        />
                        <Image
                          class={styles.iconOther}
                          src={
                            this.checkBadge('MUSIC', item.teacher)
                              ? getAssetsHomeFile('music_active.png')
                              : getAssetsHomeFile('music_default.png')
                          }
                        />
                      </div>
                      <div class={styles.score}>评分: </div>
                      <div class={styles.level}>
                        {this.starGrade ? (
                          <Rate
                            readonly
                            modelValue={this.starGrade}
                            iconPrefix="iconfont"
                            color="#FFC459"
                            void-icon="star_default"
                            icon="star_active"
                            size={15}
                          />
                        ) : (
                          <span style={{ fontSize: '12px', color: '#999999' }}>
                            暂无评分
                          </span>
                        )}
                      </div>
                    </div>
                    <div class={styles.piNameSubject}>
                      <Image
                        class={styles.subjectSection}
                        src={getAssetsHomeFile('icon_subject.png')}
                        fit="contain"
                      />
                      <div class={styles.subjectList}>
                        {this.getSubjectNameList(item.subjectName).map(
                          (item: any) => (
                            <span class={styles.subject}>{item}</span>
                          )
                        )}
                      </div>
                    </div>
                  </div>
                </div>
                <div class={styles['teacher-bottom']}>
                  <div class={styles['teacher-data']}>
                    <div class={styles['teacher-data_item']}>
                      粉丝 <span>{item.fansNum || 0}</span>
                    </div>
                    <div class={styles['teacher-data_item']}>
                      已上课时 <span>{item.expTime || 0}</span>
                    </div>
                  </div>
                  <div
                    class={styles.unlinkeBtn}
                    onClick={(e: MouseEvent) => {
                      e.stopPropagation()
                      this.onUnLike(item)
                    }}
                  >
                    取消关注
                  </div>
                </div>
              </div>
            ))}
          </List>
        ) : (
          <ColResult btnStatus={false} classImgSize="SMALL" tips="暂无关注" />
        )}
      </div>
    )
  }
})
