import ColHeader from '@/components/col-header'
import { useRect } from '@vant/use'
import { useEventListener, useWindowScroll } from '@vueuse/core'
import { defineComponent } from 'vue'
import { Button, Cell, CellGroup, Image } from 'vant'
import styles from './index.module.less'
import { browser, getRandomKey } from '@/helpers/utils'
import qs from 'query-string'
import request from '@/helpers/request'
import { postMessage } from '@/helpers/native-message'

export const getAssetsHomeFile = (fileName: string) => {
  const path = `./images/${fileName}`
  const modules = import.meta.globEager('./images/*')
  return modules[path].default
}

export default defineComponent({
  name: 'track-song',
  data() {
    const query = this.$route.query
    console.log(query)
    const subjectName = query.subjectName || ''
    return {
      id: query.id,
      subjectId: query.subjectId,
      background: 'rgba(55, 205, 177, 0)',
      headColor: '#fff',
      height: 'auto' as any,
      backIconColor: 'white',
      title: subjectName + '曲目评测',
      behaviorId: getRandomKey(),
      musicList: [] as any,
      rankingScore: 0,
      hiddenProperty: null as any,
      evaluationDifficulty: ''
    }
  },
  async mounted() {
    useEventListener(document, 'scroll', () => {
      const { y } = useWindowScroll()
      if (y.value > 52) {
        this.headColor = '#000'
        this.background = '#fff'
        this.backIconColor = 'black'
      } else {
        this.background = 'transparent'
        this.headColor = '#fff'
        this.backIconColor = 'white'
      }
    })
    await this.getMusicInfo()

    this.hiddenProperty =
      'hidden' in document
        ? 'hidden'
        : 'webkitHidden' in document
        ? 'webkitHidden'
        : 'mozHidden' in document
        ? 'mozHidden'
        : null
    const visibilityChangeEvent = this.hiddenProperty.replace(
      /hidden/i,
      'visibilitychange'
    )
    document.addEventListener(visibilityChangeEvent, this.onVisibilityChange)
  },
  unmounted() {
    if (this.hiddenProperty) {
      const visibilityChangeEvent = this.hiddenProperty.replace(
        /hidden/i,
        'visibilitychange'
      )
      document.removeEventListener(
        visibilityChangeEvent,
        this.onVisibilityChange
      )
    }
  },
  methods: {
    onVisibilityChange() {
      if (!document[this.hiddenProperty]) {
        this.getMusicInfo()
      }
    },
    async getMusicInfo() {
      try {
        const { data } = await request.post(
          '/api-student/open/activity/info/' + this.id
        )

        const activityMusicVoList = data.activityMusicVoList || []
        const musicList = activityMusicVoList.filter(
          (activity: any) => activity.subjectId == this.subjectId
        )
        this.musicList = musicList
        this.rankingScore = data.rankingScore || 0
        this.evaluationDifficulty = data.evaluationDifficulty
      } catch {
        //
      }
    },
    onOpenMusic(item: any) {
      try {
        const browserInfo = browser()
        const url = qs.stringifyUrl({
          url: location.origin + '/accompany',
          query: {
            id: item.musicSheetId,
            behaviorId: this.behaviorId,
            client: browserInfo.isTeacher ? 'teacher' : 'student',
            setting: JSON.stringify({
              mode: 'EVALUATING',
              resets: ['SPEED'],
              difficulty:
                item.evaluationDifficulty || this.evaluationDifficulty,
              feeType: 'FREE',
              submitData: { evaluationId: item.evaluationId }
            })
          }
        })
        console.log(url, 'url')
        postMessage({
          api: 'openAccompanyWebView',
          content: {
            url,
            orientation: 0,
            isHideTitle: true,
            statusBarTextColor: false,
            isOpenLight: true
          }
        })
      } catch {
        //
      }
    }
  },
  computed: {
    allScore() {
      const musicList = this.musicList || []
      let score = 0
      musicList.forEach((item: any) => {
        score += item.score
      })
      return score
    },
    calcScore() {
      const allScore = this.allScore as number
      const rankingScore = this.rankingScore as number
      return Number(rankingScore - allScore)
    }
  },
  render() {
    return (
      <div class={styles.trackSong}>
        <div ref="headers">
          <ColHeader
            title={this.title}
            background={this.background}
            border={false}
            color={this.headColor}
            backIconColor={this.backIconColor as any}
            onHeaderBack={() => {
              this.$nextTick(() => {
                const { height } = useRect((this as any).$refs.headers)
                this.height = height
                // this.homeContaiterHeight = `calc(100vh - var(--van-tabs-line-height) - ${height}px - 15px)`
              })
            }}
          >
            <div class={styles.trackScore}>
              <div class={styles.trackCountScore}>
                我的总分 <span>{this.allScore}</span>
              </div>

              <div class={styles.trackIf}>
                {this.calcScore <= 0
                  ? '恭喜您已达到获奖分数！'
                  : `距离要求分数还有${this.calcScore}分，继续加油！`}
              </div>

              <Image
                class={styles.trackImg}
                src={getAssetsHomeFile('icon_score.png')}
              />
            </div>
          </ColHeader>
        </div>
        <div class={styles.bg}></div>

        <CellGroup class={styles.cellGroup}>
          {this.musicList.map((item: any) => (
            <Cell
              center
              v-slots={{
                icon: () => (
                  <Image src={item.musicImage} class={styles.musicPic} />
                ),
                title: () => (
                  <div class={styles.musicName}>{item.musicSheetName}</div>
                ),
                label: () =>
                  item.score ? (
                    <div class={[styles.labelClass, styles.labelScore]}>
                      我的评分：{item.score}
                    </div>
                  ) : (
                    <div class={styles.labelClass}>暂无评分，快来挑战吧～</div>
                  ),
                value: () => (
                  <div class={styles.valueClass}>
                    <Button
                      type="primary"
                      size="small"
                      round
                      color="linear-gradient(180deg, #FFA200 0%, #FF6900 100%)"
                      onClick={() => {
                        this.onOpenMusic(item)
                      }}
                    >
                      立刻挑战
                    </Button>
                  </div>
                )
              }}
            />
          ))}
        </CellGroup>
      </div>
    )
  }
})
