import TheSticky from '@/components/the-sticky'
import { computed, defineComponent, onMounted, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import styles from './index.module.less'
import ColHeader from '@/components/col-header'
import bgImg from './images/time-bg.png'
import bgImg2 from './images/day-bg.png'
import timeTitle from './images/time-title.png'
import dayTitle from './images/day-title.png'
import { Tabs, Tab, Image, Icon, Calendar, Cell } from 'vant'
import dayjs from 'dayjs'
import isBetween from 'dayjs/plugin/isBetween'
dayjs.extend(isBetween)
import request from '@/helpers/request'
import { state as baseState } from '@/state'
import studentLogo from '@/common/images/icon_student.png'
import emptyLogo from './images/empty-logo.png'
import ColResult from '@/components/col-result'
import { browser } from '@/helpers/utils'
import { postMessage } from '@/helpers/native-message'
export default defineComponent({
  name: 'ranking-list',
  setup() {
    const router = useRouter()
    const route = useRoute()
    const state = reactive({
      showPopoverTime: false,
      tabActive: 'timeBill',
      firstInfo: {} as any,
      secondInfo: {} as any,
      threeInfo: {} as any,
      myInfo: {} as any,
      list: [] as any,
      loading: false,
      beforListShow: true,
      listShow: true // 是否显示
    })

    const isDayRank = computed(() => {
      return state.tabActive === 'dayBill'
    })

    // 初始化周一
    const formatWeekDays = (time?: any) => {
      const week = dayjs(time).day()
      let startTime = ''
      let endTime = ''
      if (week === 0) {
        // 星期天
        startTime = dayjs(time).subtract(6, 'day').format('YYYY-MM-DD')
        endTime = dayjs(time).format('YYYY-MM-DD')
      } else if (week === 1) {
        // 星期一
        startTime = dayjs(time).format('YYYY-MM-DD')
        endTime = dayjs(time).add(6, 'day').format('YYYY-MM-DD')
      } else {
        startTime = dayjs(time)
          .subtract(week - 1, 'day')
          .format('YYYY-MM-DD')
        endTime = dayjs(time)
          .add(7 - week, 'day')
          .format('YYYY-MM-DD')
      }
      return {
        startTime,
        endTime
      }
    }

    const forms = reactive({
      ...formatWeekDays(),
      studentIds: baseState.user.data?.userId,
      orderType: 0,
      page: 1,
      rows: 20
    })

    const getList = async () => {
      state.loading = true
      try {
        const { data } = await request.post(
          '/api-tenant/studentMusicCompareRecord/rankingList',
          {
            data: {
              ...forms
            }
          }
        )
        state.beforListShow = data.detail && data.detail.length > 0
        state.myInfo = data.head || {}
        state.list = data.detail || []
        state.firstInfo =
          state.list.length > 0 ? state.list.splice(0, 1)[0] : {}
        state.secondInfo =
          state.list.length > 0 ? state.list.splice(0, 1)[0] : {}
        state.threeInfo =
          state.list.length > 0 ? state.list.splice(0, 1)[0] : {}

        state.listShow = state.list.length > 0
      } catch {
        //
      }
      state.loading = false
    }

    onMounted(() => {
      getList()
    })
    return () => (
      <div
        class={[
          styles.rankListPage,
          isDayRank.value ? styles.rankListDay : styles.rankListTime
        ]}
      >
        <div class={styles.sticky}>
          <TheSticky position="top">
            <ColHeader
              background="transparent"
              isFixed={false}
              border={false}
              title=" "
              color="#131415"
            >
              {{
                content: () => (
                  <>
                    <Icon
                      name="arrow-left"
                      class={styles.backArrow}
                      onClick={() => {
                        if (browser().isApp) {
                          postMessage({ api: 'goBack' })
                        } else {
                          router.back()
                        }
                      }}
                    />
                    <Tabs
                      lineWidth={22}
                      lineHeight={4}
                      shrink
                      v-model:active={state.tabActive}
                      onChange={(val: string) => {
                        if (val === 'dayBill') {
                          forms.orderType = 2
                        } else {
                          forms.orderType = 0
                        }

                        getList()
                      }}
                    >
                      <Tab title="时长榜" name="timeBill"></Tab>
                      <Tab title="天数榜" name="dayBill"></Tab>
                    </Tabs>
                  </>
                )
              }}
            </ColHeader>
          </TheSticky>
          <img class={styles.bgImg} src={isDayRank.value ? bgImg2 : bgImg} />
        </div>

        {/* {state.beforListShow && ( */}
        <div class={styles.rankContainer}>
          <div class={styles.rankLevel}>
            <div class={[styles.levelItem, styles.level2]}>
              {state.secondInfo.userId ? (
                <>
                  <div class={styles.levelUserImg}>
                    <Image
                      class={styles.img}
                      src={state.secondInfo.avatar || studentLogo}
                    />
                  </div>
                  <h2 class={'van-ellipsis'}>{state.secondInfo.studentName}</h2>
                  {forms.orderType === 2 ? (
                    <p class={[styles.levelTime, 'van-ellipsis']}>
                      {state.secondInfo.subjectName}-
                      {state.secondInfo.trainDays}天
                    </p>
                  ) : (
                    <p class={[styles.levelTime, 'van-ellipsis']}>
                      {state.secondInfo.subjectName}-
                      {state.secondInfo.trainTime}
                      分钟
                    </p>
                  )}
                </>
              ) : (
                <>
                  <div class={styles.levelUserImg}>
                    <Image class={styles.img} src={emptyLogo} />
                  </div>
                  <h2 class={'van-ellipsis'}>虚位以待</h2>
                  <p class={[styles.levelTime, 'van-ellipsis']}>&nbsp;</p>
                </>
              )}
            </div>
            <div class={[styles.levelItem, styles.level1]}>
              {state.firstInfo.userId ? (
                <>
                  <div class={styles.levelUserImg}>
                    <Image
                      class={styles.img}
                      src={state.firstInfo.avatar || studentLogo}
                    />
                  </div>
                  <h2 class={'van-ellipsis'}>{state.firstInfo.studentName}</h2>
                  {forms.orderType === 2 ? (
                    <p class={[styles.levelTime, 'van-ellipsis']}>
                      {state.firstInfo.subjectName}-{state.firstInfo.trainDays}
                      天
                    </p>
                  ) : (
                    <p class={[styles.levelTime, 'van-ellipsis']}>
                      {state.firstInfo.subjectName}-{state.firstInfo.trainTime}
                      分钟
                    </p>
                  )}
                </>
              ) : (
                <>
                  <div class={styles.levelUserImg}>
                    <Image class={styles.img} src={emptyLogo} />
                  </div>
                  <h2 class={'van-ellipsis'}>虚位以待</h2>
                  <p class={[styles.levelTime, 'van-ellipsis']}>&nbsp;</p>
                </>
              )}
            </div>
            <div class={[styles.levelItem, styles.level3]}>
              {state.threeInfo.userId ? (
                <>
                  <div class={styles.levelUserImg}>
                    <Image
                      class={styles.img}
                      src={state.threeInfo.avatar || studentLogo}
                    />
                  </div>
                  <h2 class={'van-ellipsis'}>{state.threeInfo.studentName}</h2>
                  {/* <p class={[styles.levelTime, 'van-ellipsis']}>
                    {state.threeInfo.subjectName}-{state.threeInfo.trainTime}
                    分钟
                  </p> */}
                  {forms.orderType === 2 ? (
                    <p class={[styles.levelTime, 'van-ellipsis']}>
                      {state.threeInfo.subjectName}-{state.threeInfo.trainDays}
                      天
                    </p>
                  ) : (
                    <p class={[styles.levelTime, 'van-ellipsis']}>
                      {state.threeInfo.subjectName}-{state.threeInfo.trainTime}
                      分钟
                    </p>
                  )}
                </>
              ) : (
                <>
                  <div class={styles.levelUserImg}>
                    <Image class={styles.img} src={emptyLogo} />
                  </div>
                  <h2 class={'van-ellipsis'}>虚位以待</h2>
                  <p class={[styles.levelTime, 'van-ellipsis']}>&nbsp;</p>
                </>
              )}
            </div>
          </div>

          <div class={styles.rankList}>
            <div class={styles.rankTitle}>
              <div class={styles.titleName}>
                <img src={isDayRank.value ? dayTitle : timeTitle} />
              </div>
              <span
                class={styles.timeRange}
                onClick={() => (state.showPopoverTime = true)}
              >
                {dayjs(forms.startTime).format('YYYY-MM-DD')}至
                {dayjs(forms.endTime).format('YYYY-MM-DD')}
                <i class={styles.iconArrow}></i>
              </span>
            </div>

            {state.list.map((item: any) => (
              // i == 4 && styles.active
              <Cell
                class={[
                  styles.rankItem,
                  state.myInfo.userId === item.userId ? styles.active : ''
                ]}
                border={false}
                center
              >
                {{
                  icon: () => (
                    <>
                      <span class={styles.num}>{item.rankNum}</span>
                      <Image
                        class={styles.userImg}
                        src={item.avatar || studentLogo}
                      />
                    </>
                  ),
                  title: () => (
                    <div class={styles.userInfo}>
                      <p class={styles.userName}>{item.studentName}</p>
                      <p class={styles.subjectName}>{item.subjectName}</p>
                    </div>
                  ),
                  value: () =>
                    forms.orderType === 2 ? (
                      <div class={styles.times}>
                        <span>{item.trainDays}</span>天
                      </div>
                    ) : (
                      <div class={styles.times}>
                        <span>{item.trainTime}</span>分钟
                      </div>
                    )
                }}
              </Cell>
            ))}

            {!state.loading && !state.listShow && (
              <ColResult tips="暂无数据" btnStatus={false} />
            )}
          </div>
          {state.myInfo?.userId ? (
            <TheSticky position="bottom" varName="--bottom-height">
              <Cell class={styles.selfInfo} border={false} center>
                {{
                  icon: () => (
                    <>
                      <span class={styles.num}>
                        {state.myInfo.rankNum == -1
                          ? '-'
                          : state.myInfo.rankNum}
                      </span>
                      <Image
                        src={state.myInfo.avatar || studentLogo}
                        class={styles.userImg}
                      />
                    </>
                  ),
                  title: () => (
                    <div class={styles.userInfo}>
                      <p class={styles.userName}>{state.myInfo.studentName}</p>
                      <p class={styles.subjectName}>
                        {state.myInfo.subjectName}
                      </p>
                    </div>
                  ),
                  value: () =>
                    forms.orderType === 2 ? (
                      <div class={styles.times}>
                        <span>{state.myInfo.trainDays}</span>天
                      </div>
                    ) : (
                      <div class={styles.times}>
                        <span>{state.myInfo.trainTime}</span>分钟
                      </div>
                    )
                }}
              </Cell>
            </TheSticky>
          ) : (
            ''
          )}
        </div>
        {/* )} */}

        {/* {!state.loading && !state.beforListShow && (
          <div class={styles.emptyResult}>
            <ColResult tips="暂无数据" btnStatus={false} />
          </div>
        )} */}

        <Calendar
          v-model:show={state.showPopoverTime}
          firstDayOfWeek={1}
          showConfirm={false}
          type="range"
          title="周期选择"
          maxRange={7}
          minDate={new Date('2023-02-27')}
          defaultDate={[
            dayjs(forms.startTime).toDate(),
            dayjs(forms.endTime).toDate()
          ]}
          style={{
            height: '70%'
          }}
          onSelect={(item: any) => {
            forms.startTime = ''
            forms.endTime = ''
            if (
              !dayjs(item[0]).isBetween(
                dayjs(forms.startTime),
                dayjs(forms.endTime)
              )
            ) {
              const times = formatWeekDays(item[0])
              forms.startTime = times.startTime
              forms.endTime = times.endTime
            }
            state.showPopoverTime = false

            getList()
          }}
        />
      </div>
    )
  }
})
