import OHeader from '@/components/o-header'
import OSticky from '@/components/o-sticky'
import OEmpty from '@/components/o-empty'
import dayjs from 'dayjs'
import {
  Icon,
  Popover,
  DatePicker,
  DatePickerColumnType,
  Popup,
  List,
  PullRefresh,
  showToast,
  Dialog,
  Image
} from 'vant'
import DetailItem from './modals/detail-item'
import { defineComponent, onMounted, reactive, ref, onDeactivated } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import styles from './exercis-detail.module.less'
import request from '@/helpers/request'
import questIcon from '@/school/images/quest-icon.png'
import defaultIcon from '@/school/images/default-icon.png'
import { state as globalState } from '@/state'

export default defineComponent({
  name: 'exercis-detail',
  setup() {
    const router = useRouter()
    const route = useRoute()
    const platformApi = ref(globalState.platformApi)
    const state = reactive({
      showPopoverTime: false,
      showPopoverOrchestra: false,
      currentDate: [dayjs().format('YYYY'), dayjs().format('MM')],
      actions: [
        { text: '全部乐团', color: 'var(--van-primary-color)' },
        { text: '交付团' },
        { text: '晋升团' }
      ],
      id: route.query.id,
      heightV: 0 as number,
      scrollTop: 0 as number
    })

    const forms = reactive({
      practiceMonth: route.query.practiceMonth
        ? route.query.practiceMonth
        : state.currentDate[0] + '' + state.currentDate[1],
      practiceMonthName: route.query.practiceMonthName
        ? route.query.practiceMonthName
        : state.currentDate[0] + '年' + state.currentDate[1] + '月',
      orchestraId: '',
      orchestraName: '',
      page: 1,
      rows: 20,
      userId: route.query.id,
      clientType: 'STUDENT'
    })
    const showTip = ref(false)
    const minDate = ref(new Date(dayjs().subtract(10, 'year').format('YYYY-MM-DD')))
    const maxDate = ref(new Date(dayjs().add(10, 'year').format('YYYY-MM-DD')))
    const columnsType = ref<DatePickerColumnType[]>(['year', 'month'])
    const refreshing = ref(false)
    const loading = ref(false)
    const finished = ref(false)
    const showContact = ref(false)
    const infoDetail = ref({} as any)
    const list = ref([])
    const getList = async () => {
      loading.value = true
      if (refreshing.value) {
        list.value = []
        forms.page = 1
        refreshing.value = false
      }
      try {
        const res = await request.post(`${platformApi.value}/musicPracticeRecord/page`, {
          data: { ...forms }
        })

        if (list.value.length > 0 && res.data.current === 1) {
          return
        }

        forms.page = res.data.current + 1
        list.value = list.value.concat(res.data.rows || [])
        showContact.value = list.value.length > 0
        loading.value = false

        finished.value = res.data.current >= res.data.pages
      } catch (e: any) {
        // console.log(e, 'e')
        const message = e.message
        showToast(message)
        showContact.value = false
        finished.value = true
      }
    }

    const getDetail = async () => {
      try {
        const res = await request.get(`/api-backend/student/detail/${state.id}`)
        console.log(res)
        infoDetail.value = { ...res.data }
      } catch (e: any) {
        // console.log(e, 'e')
        const message = e.message
        showToast(message)
      }
    }
    onMounted(() => {
      getList()
      getDetail()
      window.addEventListener('scroll', handleScroll)
    })
    onDeactivated(() => {
      window.removeEventListener('scroll', handleScroll)
    })
    const handleScroll = () => {
      const scrollTop =
        window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0
      state.scrollTop = scrollTop
    }
    const getHeight = (dataHeight: number) => {
      state.heightV = dataHeight
      console.log(dataHeight, 'dataHeight')
    }

    const checkTimer = (val: any) => {
      forms.practiceMonth = val.selectedValues[0] + val.selectedValues[1]
      forms.practiceMonthName = val.selectedValues[0] + '年' + val.selectedValues[1] + '月'
      state.showPopoverTime = false
      refreshing.value = true
      getList()
    }

    const onRefresh = () => {
      finished.value = false
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      loading.value = true
      getList()
    }
    return () => (
      <>
        <div class={styles.exercisContainer}>
          <div class={styles.topWrap}>
            <OSticky position="top" background="#F8F8F8" onGetHeight={getHeight}>
              <OHeader
                border={false}
                background={state.heightV > state.scrollTop ? 'transparent' : '#fff'}
              >
                {{
                  right: () => (
                    <Icon
                      name={questIcon}
                      size={22}
                      color="#333"
                      onClick={() => {
                        showTip.value = true
                      }}
                    />
                  )
                }}
              </OHeader>
            </OSticky>
            <div class={styles.topInfo}>
              <div class={styles.topInfoLeft}>
                <div class={styles.headWrap}>
                  <Image
                    src={infoDetail.value.avatar ? infoDetail.value.avatar : defaultIcon}
                    fit="cover"
                    width="68px"
                    height="68px"
                  />
                </div>
                <div class={styles.infoMsg}>
                  <p>{infoDetail.value.nickname}</p>
                  <div class={styles.tag}>
                    {infoDetail.value.subjectNames ? infoDetail.value.subjectNames : '暂无声部'}
                  </div>
                </div>
              </div>
              <div class={styles.topInfoRight}>
                <div class={styles.infoDay}>
                  <p class={styles.infoDayMain}>
                    {infoDetail.value.practiceDays ? infoDetail.value.practiceDays : 0}{' '}
                    <span>天</span>
                  </p>
                  <p class={styles.infoDaysub}>练习天数</p>
                </div>
                <div class={styles.infoTime}>
                  <p class={styles.infoDayMain}>
                    {infoDetail.value.practiceTimes ? infoDetail.value.practiceTimes : 0}{' '}
                    <span>分钟</span>
                  </p>
                  <p class={styles.infoDaysub}>练习时长</p>
                </div>
              </div>
            </div>
            <div class={styles.chioseWrap}>
              <div style={{ padding: '12px 13px', background: 'transparent' }}>
                <div
                  class={styles.searchBand}
                  onClick={() => {
                    state.showPopoverTime = true
                  }}
                >
                  {forms.practiceMonthName}
                  <Icon name={state.showPopoverTime ? 'arrow-up' : 'arrow-down'} />
                </div>
              </div>

              {/* <div style={{ padding: '12px 13px', background: 'transparent' }}>
                <Popover
                  v-model:show={state.showPopoverOrchestra}
                  actions={state.actions}
                  showArrow={false}
                  placement="bottom-start"
                  offset={[0, 12]}
                >
                  {{
                    reference: () => (
                      <div class={styles.searchBand}>
                        全部乐团
                        <Icon name={state.showPopoverOrchestra ? 'arrow-up' : 'arrow-down'} />
                      </div>
                    )
                  }}
                </Popover>
              </div> */}
            </div>
          </div>
          {showContact.value ? (
            <PullRefresh
              v-model={refreshing.value}
              onRefresh={onRefresh}
              style="min-height: 100vh;"
            >
              <List
                v-model:loading={loading.value}
                finished={finished.value}
                finished-text="没有更多了"
                onLoad={getList}
              >
                {list.value.map((item: any) => (
                  <DetailItem item={item} />
                ))}
              </List>
            </PullRefresh>
          ) : (
            <OEmpty />
          )}
        </div>

        <Popup v-model:show={state.showPopoverTime} position="bottom" style="{ height: '30%' }">
          <DatePicker
            onCancel={() => {
              state.showPopoverTime = false
            }}
            onConfirm={checkTimer}
            v-model={state.currentDate}
            title="选择年月"
            minDate={minDate.value}
            maxDate={maxDate.value}
            columnsType={columnsType.value}
          />
        </Popup>
        <Dialog
          class="exercisDetailDialog"
          v-model:show={showTip.value}
          title="提示框"
          confirmButtonText="我知道了"
          v-slots={{
            title: () => (
              <div class={styles.DialogTitle}>
                <span></span>
                <p>什么是练习数据</p>
              </div>
            ),
            default: () => (
              <div class={styles.DialogConent}>
                <p>
                  练习数据是学生通过云教练自主练习的数据统计，可根据时间段查询学生的练习天数和练习时长{' '}
                </p>
                <p>练习天数：当天有曲目播放或测评记录即算练习</p>
                <p>练习时长：曲目播放和曲目测评的时长总和</p>
              </div>
            )
          }}
        ></Dialog>
      </>
    )
  }
})
