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,
  NoticeBar
} from 'vant'
import OFullRefresh from '@/components/o-full-refresh'
import DetailItem from './modals/detail-item'
import { defineComponent, onMounted, reactive, ref, onDeactivated, nextTick } 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 iconStudent from '@common/images/icon_student.png'
import { state as globalState } from '@/state'
import { useRect } from '@vant/use'
import { formatterDatePicker } from '@/helpers/utils'

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,
      isClick: false
    })

    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: route.query.clientType ? route.query.clientType : globalState.platformType
    })
    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 () => {
      if (state.isClick) {
        return
      }
      state.isClick = true
      if (refreshing.value) {
        list.value = []
        forms.page = 1
        refreshing.value = false
      }
      try {
        const res = await request.post(`${platformApi.value}/musicPracticeRecord/page`, {
          data: { ...forms, feature: 'EVALUATION' }
        })

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

        list.value = list.value.concat(res.data.rows || [])
        forms.page = res.data.current + 1
        showContact.value = list.value.length > 0
        loading.value = false
        console.log(res.data, res.data.current >= res.data.pages)
        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
      }
      state.isClick = false
    }

    const getDetail = async () => {
      if (forms.clientType === 'TEACHER') {
        try {
          const res = await request.post(`${platformApi.value}/teacher/detail`, {
            data: {
              teacherId: state.id
            }
          })
          infoDetail.value = { ...res.data }
          infoDetail.value.subjectNames = res.data.subjectName.split(',')
        } catch (e: any) {
          // console.log(e, 'e')
          const message = e.message
          // showToast(message)
        }
      } else {
        try {
          const res = await request.get(`${platformApi.value}/student/detail/${state.id}`)
          console.log(res)
          infoDetail.value = { ...res.data }
        } catch (e: any) {
          // console.log(e, 'e')
          const message = e.message
          // showToast(message)
        }
      }
    }
    const topWrap = ref()
    const topWrapHeight = ref(0)
    onMounted(async () => {
      await getList()
      await getDetail()
      window.addEventListener('scroll', handleScroll)

      nextTick(() => {
        const { height } = useRect(topWrap.value)
        topWrapHeight.value = height
      })
    })
    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()
    }
    const onBack = () => {
      router.go(-1)
    }

    return () => (
      <>
        <div class={[styles.exercisContainer, !showContact.value && 'emptyRootContainer']}>
          <div class={styles.topWrap} ref={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 : iconStudent}
                    fit="cover"
                    width="68px"
                    height="68px"
                  />
                </div>
                <div class={styles.infoMsg}>
                  <p>{infoDetail.value.nickname}</p>
                  {forms.clientType === 'TEACHER' ? (
                    <NoticeBar class={styles.teacherSubject}>
                      {infoDetail.value?.subjectNames?.map((item: any) => {
                        return <div class={styles.tag}>{item}</div>
                      })}
                    </NoticeBar>
                  ) : (
                    <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={'searchGroup-single'} style="padding-top: 0 !important;">
              <div
                class={['searchItem', state.showPopoverTime ? 'searchItem-active' : '']}
                onClick={() => {
                  state.showPopoverTime = true
                }}
              >
                <span>{forms.practiceMonthName}</span>
              </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 ? (
            <OFullRefresh
              v-model:modelValue={refreshing.value}
              onRefresh={onRefresh}
              style="min-height: 100vh;"
            >
              <List
                loading-text=" "
                // v-model:loading={loading.value}
                finished={finished.value}
                finished-text="没有更多了"
                onLoad={getList}
              >
                {list.value.map((item: any) => (
                  <DetailItem item={item} />
                ))}
              </List>
            </OFullRefresh>
          ) : (
            <OEmpty tips="暂无练习统计" />
          )}
        </div>

        <Popup
          v-model:show={state.showPopoverTime}
          position="bottom"
          round
          class={'popupBottomSearch'}
        >
          <DatePicker
            onCancel={() => {
              state.showPopoverTime = false
            }}
            onConfirm={checkTimer}
            v-model={state.currentDate}
            minDate={minDate.value}
            maxDate={maxDate.value}
            formatter={formatterDatePicker}
            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>
                  练习数据是{forms.clientType == 'TEACHER' ? '' : '学员'}
                  通过云练习自主练习的数据统计，可根据时间段查询
                  {forms.clientType == 'TEACHER' ? '' : '学员'}的练习天数和练习时长{' '}
                </p>
                <p>练习天数：当天有曲目播放或测评记录即算练习</p>
                <p>练习时长：曲目播放和曲目测评的时长总和</p>
              </div>
            )
          }}
        ></Dialog>
      </>
    )
  }
})
