import ColHeader from '@/components/col-header'
import { defineComponent } from 'vue'
import styles from './exercise-detail.module.less'
import {
  Cell,
  CellGroup,
  DatetimePicker,
  Grid,
  GridItem,
  Icon,
  Image,
  List,
  Popup
} from 'vant'
import { levelMember } from '@/constant'
import request from '@/helpers/request'
import { formatterDate, getHttpOrigin } from '@/helpers/utils'
import dayjs from 'dayjs'
import ColResult from '@/components/col-result'
import { postMessage } from '@/helpers/native-message'
import { useEventTracking } from '@/helpers/hooks'
import iconVideo from '../images/icon_video.png'
import recordBg from '../images/record_bg.png'
import iconStudent from '@/common/images/icon_student.png'

export default defineComponent({
  name: 'memberRecord',
  data() {
    return {
      userTrainOverView: {
        trainDays: 0,
        trainNum: 0,
        trainTime: 0
      },
      userInfo: {
        avatar: '',
        username: '',
        subjectName: ''
      },
      timeStatus: false,
      currentDate: new Date(),
      list: [],
      dataShow: true, // 判断是否有数据
      loading: false,
      finished: false,
      params: {
        page: 1,
        rows: 20
      }
    }
  },
  async mounted() {
    this.getList()
    useEventTracking('评测记录')
  },
  methods: {
    onSearch() {
      this.timeStatus = false
      this.dataShow = true
      this.loading = false
      this.finished = false
      this.list = []
      this.params.page = 1
      this.getList()
    },
    async getList() {
      try {
        const params = this.params
        const res = await request.get(
          '/api-teacher/sysMusicRecord/studentTrainData',
          {
            params: {
              ...params,
              studentId: this.$route.query.studentId || '',
              startTime: dayjs(this.currentDate).format('YYYY-MM')
            }
          }
        )
        this.loading = false
        const result = res.data || {}
        // 在第一页的时候才处理数据显示
        if (result.detail.pageNo === 1) {
          this.userTrainOverView = result.userTrainOverView
          this.userInfo = result.userInfo
        }
        // 处理重复请求数据
        if (this.list.length > 0 && result.detail.pageNo === 1) {
          return
        }
        this.list = this.list.concat(result.detail.rows || [])
        this.finished = result.detail.pageNo >= result.detail.totalPage
        this.params.page = result.detail.pageNo + 1
        this.dataShow = this.list.length > 0
      } catch {
        this.dataShow = false
        this.finished = true
      }
    }
  },
  render() {
    return (
      <div class={styles['member-record']}>
        {/* <Sticky position="top" offsetTop={0}> */}
        <ColHeader
          class={styles.memberHeader}
          background="#00d1a1"
          backIconColor="white"
          border={false}
          color="#fff"
          // isFixed={false}
          title=' '
          v-slots={{
            default: () => (
              <div class={styles.headerContent}>
                <Image class={styles.headerImg} src={recordBg} />

                <div class={styles.userInfo}>
                  <img class={styles.userImg} src={this.userInfo.avatar || iconStudent} />
                  <span class={styles.userName}>{this.userInfo.username}</span>
                  {this.userInfo.subjectName ? <span class={styles.subjectName}>{this.userInfo.subjectName}</span> : ''}
                </div>

                <div class={styles.headerCount}>
                  <div class={styles.headerItem}>
                    <span class={styles.num}>
                      {this.userTrainOverView.trainDays}天
                    </span>
                    <span>累计练习天数</span>
                  </div>
                  <div class={styles.headerItem}>
                    <span class={styles.num}>
                      {this.userTrainOverView.trainTime}分钟
                    </span>
                    <span>累计练习时长</span>
                  </div>
                  <div class={styles.headerItem}>
                    <span class={styles.num}>
                      {this.userTrainOverView.trainNum}次
                    </span>
                    <span>累计练习次数</span>
                  </div>
                </div>
              </div>
              //   <div class={[styles.certHeader, this.headStatus ? styles.certWhite : null]}>
              //     老师认证
              //   </div>
            )
          }}
        />
        {/* </Sticky> */}

        <div style={{ overflow: 'hidden', paddingBottom: '12px' }}>
          <Cell
            class={styles.memberCell}
            v-slots={{
              title: () => (
                <div class={styles.rTitle}>
                  <span>评测记录</span>
                </div>
              ),
              default: () => (
                <div
                  class={styles.dataItem}
                  onClick={() => (this.timeStatus = true)}
                >
                  {dayjs(this.currentDate).format('YYYY年MM月')}
                  <Icon
                    classPrefix="iconfont"
                    name="down"
                    size={14}
                    color="var(--van-primary)"
                  />
                </div>
              )
            }}
          ></Cell>

          <Popup
            v-model:show={this.timeStatus}
            position="bottom"
            round
            closeOnPopstate
          >
            <DatetimePicker
              type="year-month"
              v-model={this.currentDate}
              formatter={formatterDate}
              onCancel={() => {
                this.timeStatus = false
              }}
              onConfirm={this.onSearch}
            />
          </Popup>
          {this.dataShow ? (
            <List
              v-model:loading={this.loading}
              finished={this.finished}
              finishedText=" "
              immediateCheck={false}
              class={[styles.liveList, 'mb12']}
              onLoad={this.getList}
            >
              {this.list.map((item: any) => (
                <CellGroup
                  class={styles['data-content']}
                  border={false}
                  onClick={() => {
                    const behaviorId = +new Date()
                    // 酷乐秀云教练的部署目录
                    const musicScorePath = '/klx-music-score/'
                    //https://dev.colexiu.com/klx-music-score/#/evaluat-report?id=6856&musicRenderType=staff&systemType=student&Authorization=bearer%2043d42470-e968-4efe-a17a-b859a350cbff
                    postMessage({
                      api: 'openAccompanyWebView',
                      content: {
                        url:
                          getHttpOrigin() +
                          musicScorePath +
                          '#/' +
                          'evaluat-report?id=' +
                          item.id +
                          '&behaviorId=' +
                          behaviorId,
                        orientation: 0,
                        isHideTitle: true,
                        statusBarTextColor: false,
                        isOpenLight: true
                      }
                    })
                    return
                  }}
                >
                  <Cell
                    center
                    v-slots={{
                      title: () => (
                        <div class={styles.dataTitle}>
                          <span>{item.sysMusicScoreName}</span>
                          {item.videoFilePath && (
                            <Icon name={iconVideo} size={20} />
                          )}
                        </div>
                      ),
                      default: () => (
                        <div class={styles.dataItem}>
                          {dayjs(item.createTime).format('YYYY/MM/DD HH:mm')}
                        </div>
                      )
                    }}
                  ></Cell>
                  <Cell
                    center
                    style={{ paddingLeft: '5px', paddingRight: '5px' }}
                    v-slots={{
                      title: () => (
                        <Grid border={false} columnNum={5}>
                          <GridItem
                            text="评测难度"
                            v-slots={{
                              icon: () => (
                                <span style={{ color: '#000000' }}>
                                  {levelMember[item.heardLevel]}
                                </span>
                              )
                            }}
                          ></GridItem>
                          <GridItem
                            text="评测分数"
                            v-slots={{
                              icon: () => (
                                <span style={{ color: '#000000' }}>
                                  {item.score}分
                                </span>
                              )
                            }}
                          ></GridItem>
                          <GridItem
                            text="音准"
                            v-slots={{
                              icon: () => (
                                <span style={{ color: '#01C1B5' }}>
                                  {item.intonation}分
                                </span>
                              )
                            }}
                          ></GridItem>
                          <GridItem
                            text="节奏"
                            v-slots={{
                              icon: () => (
                                <span style={{ color: '#FF802C' }}>
                                  {item.cadence}分
                                </span>
                              )
                            }}
                          ></GridItem>
                          <GridItem
                            text="完成度"
                            v-slots={{
                              icon: () => (
                                <span style={{ color: '#F79C00' }}>
                                  {item.integrity}分
                                </span>
                              )
                            }}
                          ></GridItem>
                        </Grid>
                      )
                    }}
                  ></Cell>
                </CellGroup>
              ))}
            </List>
          ) : (
            <ColResult btnStatus={false} classImgSize="SMALL" tips="暂无记录" />
          )}
        </div>
      </div>
    )
  }
})
