import { Button, Cell, Empty, Image, Tab, Tabs } from 'vant'
import {
  computed,
  defineComponent,
  nextTick,
  onMounted,
  reactive,
  ref
} from 'vue'
import styles from './index.module.less'
import IconTrophy from './image/icon-trophy.png'
import IconLevel from '../share-page/track-review-activity/images/icon_level.png'
import IconLevel2 from '../share-page/track-review-activity/images/icon_level2.png'
import IconLevel3 from '../share-page/track-review-activity/images/icon_level3.png'
import IconEmtry from './image/icon-emtry.png'
import IconAvator from '@/common/images/icon_teacher.png'
import request from '@/helpers/request'
import { useRoute, useRouter } from 'vue-router'
import { state as userInfo } from '@/state'
import ColHeader from '@/components/col-header'

interface IMusicItem {
  loaded: boolean
  musicSheetName: string
  musicSubject: string
  musicSheetId: number
  evaluationId: number
  rankingList: any
  [_: string]: any
}

export default defineComponent({
  name: 'leaderboard',
  setup() {
    const route = useRoute()
    const router = useRouter()
    const state = reactive({
      tabIndex: 0,
      musicList: [] as IMusicItem[],
      rankingMethod: ''
    })
    const getMusicList = async () => {
      try {
        const {
          data: {
            rankingMethod,
            subjectInfos,
            activityMusicVoList,
            shareUrl,
            subjectUrl
          }
        } = await request.post(
          `/api-student/open/activity/info/${route.query.id}`
        )
        state.rankingMethod = rankingMethod
        const activityList =
          rankingMethod === 'TOTAL_SCORE' ? subjectInfos : activityMusicVoList
        if (Array.isArray(activityList)) {
          state.musicList = activityList.map(n => {
            n.rankingList = []
            return n
          })
        }
        img.value = subjectUrl
      } catch (error) {}
    }
    const getData = async () => {
      try {
        const { data } = await request.get(
          '/api-student/open/activityEvaluationRecord/queryRankingList',
          {
            params: {
              activityPlanId: route.query.id,
              activityEvaluationId:
                state.rankingMethod === 'TOTAL_SCORE'
                  ? state.musicList[state.tabIndex].subjectId
                  : state.musicList[state.tabIndex].evaluationId,
              limit: 10
            }
          }
        )
        if (Array.isArray(data.rankingList)) {
          state.musicList[state.tabIndex].rankingList = data.rankingList
        }
      } catch (error) {}
    }
    const img = ref()
    const imgShow = ref(false)
    const imgHeight = ref(100)

    const openActive = () => {
      router.back()
      //   router.replace({
      //     path: '/track-review-activity',
      //     query: {
      //       id: route.query.id
      //     }
      //   })
    }

    onMounted(async () => {
      await getMusicList()
      await getData()
    })
    const imgRef = ref()
    return () => (
      <div class={styles.leaderboard}>
        <ColHeader />
        <div class={styles.container}>
          <div class={styles.headImg} ref={imgRef}>
            <Image
              width="100%"
              fit="cover"
              src={img.value}
              onLoad={img => {
                nextTick(() => {
                  imgShow.value = true
                  imgHeight.value = imgRef.value?.offsetHeight || 100
                })
              }}
              onError={err => {
                console.log(err)
              }}
            />
          </div>
          {imgShow.value && (
            <Tabs
              v-model:active={state.tabIndex}
              class={styles.tabs}
              animated
              swipeable
              titleInactiveColor="rgba(153,152,155,1)"
              titleActiveColor="#fff"
              onChange={index => getData()}
            >
              {state.musicList.map((item: IMusicItem) => {
                return (
                  <Tab
                    title={
                      state.rankingMethod === 'TOTAL_SCORE'
                        ? item.subjectName
                        : item.musicSheetName
                    }
                  >
                    <div
                      class={[styles.tabContent, 'van-safe-area-bottom']}
                      style={{ height: `calc(100vh - ${imgHeight.value}px)` }}
                    >
                      <div class={styles.itemContent}>
                        <div class={styles.item}>
                          <div class={styles.left}>排名</div>
                          <div class={styles.center}>昵称</div>
                          <div class={styles.right}>评分</div>
                        </div>

                        {item.rankingList.map((n: any, index: number) => {
                          const t = (index + 1).toString().padStart(2, '0')
                          return (
                            <div class={styles.item}>
                              <div class={styles.left}>
                                {/* {index == 0 ? <Image src={IconTrophy} /> : t} */}
                                {index == 0 && <Image src={IconLevel} />}
                                {index == 1 && <Image src={IconLevel2} />}
                                {index == 2 && <Image src={IconLevel3} />}
                                {index != 0 && index != 1 && index != 2 && t}
                              </div>
                              <div class={styles.center}>
                                <Image
                                  width="38px"
                                  height="38px"
                                  fit="cover"
                                  round
                                  src={n.userAvatar || IconAvator}
                                />
                                <div class={styles.user}>
                                  <div class={styles.userContent}>
                                    <span class={styles.name}>
                                      {n.username}
                                    </span>
                                    <span class={styles.tag}>
                                      {n.userSubject}
                                    </span>
                                  </div>
                                  <div class={styles.times}>{n.joinDate}</div>
                                </div>
                              </div>
                              <div class={styles.right}>
                                <div class={styles.fraction}>{n.score}分</div>
                                {state.rankingMethod !== 'TOTAL_SCORE' && (
                                  <div class={styles.time}>
                                    第 {n.times} 次评测
                                  </div>
                                )}
                              </div>
                            </div>
                          )
                        })}

                        {!item.rankingList.length && (
                          <Empty
                            image={IconEmtry}
                            description={`该${
                              state.rankingMethod === 'TOTAL_SCORE'
                                ? '声部'
                                : '曲目'
                            }暂无排名喔～`}
                          />
                        )}
                      </div>
                    </div>
                  </Tab>
                )
              })}
            </Tabs>
          )}
        </div>
      </div>
    )
  }
})
