import ColSticky from '@/components/col-sticky'
import request from '@/helpers/request'
import { Button, Cell, CellGroup, Dialog, Image, Popup } from 'vant'
import { defineComponent } from 'vue'
import styles from './index.module.less'
import dayjs from 'dayjs'
import ShareModel from './share-model'
import { postMessage } from '@/helpers/native-message'
import { state } from '@/state'
import ColHeader from '@/components/col-header'

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

export default defineComponent({
  name: 'track-review-activity',
  data() {
    const query = this.$route.query
    return {
      id: query.id,
      activeInfo: {} as any,
      shareStatus: false,
      shareUrl: ''
    }
  },
  computed: {
    rankingMethod() {
      const activeInfo: any = this.activeInfo
      return activeInfo.rankingMethod || ''
    },
    activityMusic() {
      const activeInfo: any = this.activeInfo
      const list =
        activeInfo.rankingMethod === 'TOTAL_SCORE'
          ? activeInfo.subjectInfos
          : activeInfo.activityMusicVoList
      return list || []
    },
    rewardList() {
      const activeInfo: any = this.activeInfo
      let list = activeInfo.activityRewardList || []
      if (list && list.length > 0) {
        if (activeInfo.rankingMethod === 'TOTAL_SCORE') {
          list = [list]
        } else {
          const last = list.sort((a: any, b: any) => {
            return Number(a.group) < Number(b.group) ? -1 : 1
          })
          list = this.groupBy(last, (item: any) => {
            return [item.group]
          })
        }
      }
      // console.log(list)
      return list || []
    }
  },
  async mounted() {
    await this.getMusicInfo()

    // 判断活动状态的活动时间
    this.checkActivityTime()
  },
  methods: {
    groupBy(array: any, f: any) {
      const groups = {}
      array.forEach(function (o) {
        //注意这里必须是forEach 大写
        const group = JSON.stringify(f(o))
        groups[group] = groups[group] || []
        groups[group].push(o)
      })
      return Object.keys(groups).map(function (group) {
        return groups[group]
      })
    },
    async getMusicInfo() {
      try {
        // 获取活动基本信息
        const res = await request.post(
          '/api-teacher/open/activity/info/' + this.id
        )
        this.activeInfo = res.data
        document.title = this.activeInfo.activityName

        // 设置连接
        this.shareUrl = `${location.origin}/student/#/track-review-activity?recomUserId=${state.user.data?.userId}&id=${this.activeInfo.id}`
      } catch {
        //
      }
    },
    checkActivityTime() {
      // 判断活动状态的活动时间
      try {
        const activeInfo = this.activeInfo
        if (activeInfo.activityState !== 1) {
          Dialog.alert({
            message: '活动已结束，感谢你的关注！',
            theme: 'round-button',
            confirmButtonColor: '#2dc7aa'
          })
          this.onBackDialog('活动已结束，感谢你的关注！')
          return false
        }

        const nowTime = dayjs()
        const startTime = dayjs(activeInfo.activityStart)
        const endTime = dayjs(activeInfo.activityEnd)
        if (dayjs(nowTime).isBefore(dayjs(startTime))) {
          this.onBackDialog('活动尚未开始，请您耐心等待！')
          return false
        } else if (!dayjs(nowTime).isBefore(dayjs(endTime))) {
          this.onBackDialog('活动已结束，感谢你的关注！')
          return false
        }
        return true
      } catch {
        //
      }
    },
    onBackDialog(str: string) {
      Dialog.alert({
        message: str,
        theme: 'round-button',
        confirmButtonColor: '#2dc7aa'
      }).then(() => {
        postMessage({ api: 'back' })
      })
    }
  },
  render() {
    return (
      <div
        class={styles.review}
        style={{
          // background: `url(${
          //   this.activeInfo.subjectUrl + '?time' + +new Date()
          // }) no-repeat top center ${
          //   this.activeInfo.backgroundUrl + '?time' + +new Date()
          // }`,
          backgroundColor: this.activeInfo.backgroundUrl,
          backgroundSize: 'contain'
        }}
      >
        <ColHeader />
        <img class={styles.bannerImg} src={this.activeInfo.subjectUrl} />
        <div class={styles.reviewContainer}>
          <div class={[styles.section, styles.activeTime]}>
            <div class={styles.activeBg}>
              <img src={getAssetsHomeFile('icon_time.png')} />
              <p>
                <span>活动时间：</span>
                {dayjs(this.activeInfo.activityStart).format(
                  'YYYY-MM-DD'
                )} ~ {dayjs(this.activeInfo.activityEnd).format('YYYY-MM-DD')}
              </p>
            </div>
          </div>

          <div class={[styles.section]}>
            <div class={styles.title}>
              <img src={getAssetsHomeFile('icon_arrow_left.png')} />
              <span>活动介绍</span>
              <img src={getAssetsHomeFile('icon_arrow_right.png')} />
            </div>
            <div class={styles.tips}>{this.activeInfo.describe}</div>
          </div>

          <div class={[styles.section]}>
            <h2 class={styles.title2}>
              <span>
                <i class={styles.titlePrefix}></i>
                活动奖品
              </span>

              {/* <img
                src={getAssetsHomeFile('star_bg.png')}
                class={styles.iconStar}
              /> */}
              <span
                class={styles.titleTips}
                onClick={() =>
                  this.$router.push({
                    path: '/leaderboard',
                    query: { id: this.id }
                  })
                }
              >
                查看挑战排行榜
                <img
                  style={{ width: '16px', marginLeft: '4px' }}
                  src={getAssetsHomeFile('icon-lv.png')}
                />
                {/* 共{this.activityMusic.length || 0}
                首曲目 */}
              </span>
            </h2>
            {this.rewardList.map((item: any, index: number) => (
              <>
                <div class={styles.prizeTitle}>
                  {this.rankingMethod === 'TOTAL_SCORE' ? (
                    <div class={styles.prizeTitle_score}>
                      总评测分数达到 {this.activeInfo.rankingScore || 0}
                      分即可获奖
                    </div>
                  ) : (
                    <>
                      {index === 0 && (
                        <Image
                          class={styles.prizeLevel}
                          src={getAssetsHomeFile('icon_level.png')}
                        />
                      )}
                      {index === 1 && (
                        <Image
                          class={styles.prizeLevel}
                          src={getAssetsHomeFile('icon_level2.png')}
                        />
                      )}
                      {index === 2 && (
                        <Image
                          class={styles.prizeLevel}
                          src={getAssetsHomeFile('icon_level3.png')}
                        />
                      )}
                      第{++index}名奖品
                    </>
                  )}
                </div>
                <div class={styles.prizeSection}>
                  {item.map((child: any) => (
                    <div class={[styles.prize]}>
                      <Image src={child.imgUrl} />
                      <div class={styles.prizeContainer}>
                        <div class={styles.prizeName}>{child.rewardName}</div>
                        <div class={styles.prizeDesc}>
                          {child.rewardDescribe}
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              </>
            ))}
            {/* {this.activeInfo.activityRewardList &&
              this.activeInfo.activityRewardList.map((item: any) => (
                <div class={styles.prize}>
                  <Image src={item.imgUrl} />
                  <div class={styles.prizeContainer}>
                    <div class={styles.prizeName}>{item.rewardName}</div>
                    <div class={styles.prizeDesc}>{item.rewardDescribe}</div>
                  </div>
                </div>
              ))} */}
          </div>

          <div class={[styles.section]} style={{ backgroundColor: '#fff' }}>
            <h2 class={styles.title2}>
              <span>
                <i class={styles.titlePrefix}></i>
                活动{this.rankingMethod === 'TOTAL_SCORE' ? '声部' : '曲目'}
              </span>

              {this.rankingMethod === 'TOTAL_SCORE' ? (
                <span
                  class={styles.titleTips}
                  onClick={() => {
                    this.$router.push({
                      path: '/track-subject-song',
                      query: {
                        id: this.id
                      }
                    })
                  }}
                >
                  查看曲目
                </span>
              ) : (
                <span class={styles.titleTips}>
                  共{this.activityMusic.length || 0}首曲目
                </span>
              )}
            </h2>

            {this.activityMusic.map((item: any) => (
              <CellGroup class={styles.musicItem} border={false}>
                <Cell
                  center
                  titleClass={[
                    styles.musicTitle,
                    this.rankingMethod == 'TOTAL_SCORE' &&
                      styles.musicTitleScore
                  ]}
                  isLink={this.rankingMethod === 'TOTAL_SCORE' ? true : false}
                  v-slots={{
                    icon: () => (
                      <Image
                        src={getAssetsHomeFile(
                          this.rankingMethod !== 'TOTAL_SCORE'
                            ? 'icon_music.png'
                            : 'icon_subject.png'
                        )}
                        class={styles.iconMusic}
                      />
                    ),
                    title: () => (
                      <span class={styles.musicName}>
                        {this.rankingMethod === 'TOTAL_SCORE'
                          ? item.subjectName
                          : item.musicSheetName}
                      </span>
                    ),
                    value: () => (
                      <span
                        onClick={() => {
                          if (this.rankingMethod !== 'TOTAL_SCORE') {
                            return
                          }
                          this.$router.push({
                            path: '/track-subject-song',
                            query: {
                              id: this.id,
                              subjectId: item.subjectId
                            }
                          })
                        }}
                      >
                        {this.rankingMethod === 'TOTAL_SCORE'
                          ? `共${item.musicNums}首活动曲目`
                          : item.musicSubject}
                      </span>
                    )
                  }}
                />
                <Cell
                  center
                  class={styles.cellLevel}
                  v-slots={{
                    icon: () => (
                      <div class={styles.kingSection}>
                        <Image
                          src={getAssetsHomeFile('icon_king.png')}
                          class={styles.iconKing}
                        />
                        <p class={styles.score}>
                          {item.userId ? item.score : '--'}
                          <span>分</span>
                        </p>
                      </div>
                    ),
                    title: () => (
                      <div class={styles.users}>
                        <div class={styles.userInfo}>
                          <div class={styles.userImg}>
                            {item.userId ? (
                              <>
                                <Image
                                  src={item.userAvatar}
                                  class={styles.userLogo}
                                  fit="cover"
                                />
                                <img
                                  src={getAssetsHomeFile('icon_level.png')}
                                  class={styles.iconLevel}
                                />
                              </>
                            ) : (
                              <div class={styles.userLogo}>
                                <img
                                  class={styles.img}
                                  src={getAssetsHomeFile('icon_no_level.png')}
                                />
                              </div>
                            )}
                          </div>
                          <div class={styles.userName}>
                            {item.userId ? (
                              <>
                                <p class={styles.name}>{item.username}</p>
                                <p>
                                  <span class={styles.subjectName}>
                                    {item.userSubject}
                                  </span>
                                </p>
                              </>
                            ) : (
                              <span class={styles.noText}>虚位以待</span>
                            )}
                          </div>
                        </div>
                        <div class={styles.userBtn}>
                          <Button
                            round
                            style={{
                              padding: '0 8px',
                              height: '32px'
                            }}
                            color="linear-gradient(180deg, #FFA200 0%, #FF6900 100%)"
                            disabled={true}
                          >
                            立刻挑战
                          </Button>
                        </div>
                      </div>
                    )
                  }}
                ></Cell>
              </CellGroup>
            ))}
          </div>

          <div class={[styles.section]}>
            <div class={styles.title}>
              <img src={getAssetsHomeFile('icon_arrow_left.png')} />
              <span>活动规则</span>
              <img src={getAssetsHomeFile('icon_arrow_right.png')} />
            </div>
            <div class={styles.tips}>{this.activeInfo.ruleDescribe}</div>
          </div>
        </div>

        <ColSticky position="bottom">
          <div class={styles.btnGroup}>
            <Button
              round
              class={styles.submit}
              block
              onClick={() => {
                if (!this.checkActivityTime()) {
                  return
                }
                this.shareStatus = true
              }}
            >
              立即分享
            </Button>
          </div>
        </ColSticky>

        <Popup
          v-model:show={this.shareStatus}
          style={{ background: 'transparent' }}
        >
          <ShareModel shareUrl={this.shareUrl} activeInfo={this.activeInfo} />
        </Popup>
      </div>
    )
  }
})
