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
} from 'vant'
import DetailItem from './modals/detail-item'
import { defineComponent, onMounted, reactive, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import styles from './exercis-detail.module.less'
import request from '@/helpers/request'
import questIcon from '../images/quest-icon.png'
import defaultIcon from '@/school/images/default-icon.jpg'

export default defineComponent({
  name: 'exercis-detail',
  setup() {
    const router = useRouter()
    const route = useRoute()
    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
    })
    console.log(route.query)
    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(5, 'year').format('YYYY-MM-DD')))
    const maxDate = ref(new Date(dayjs().add(5, '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('/api-school/musicPracticeRecord/page', {
          data: { ...forms }
        })

        if (list.value.length > 0 && res.data.pageNo === 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()
    })
    const onBack = () => {
      console.log('返回')
      router.push('/exercise-record')
    }

    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 () => (
      <>
        <OSticky position="top" background="#F8F8F8">
          <div class={styles.topWrap}>
            <OHeader
              isBack={true}
              // onHeaderBack={onBack}
              border={false}
              background={'transparent'}
            >
              {{
                right: () => (
                  <Icon
                    name={questIcon}
                    size={22}
                    color="#333"
                    onClick={() => {
                      showTip.value = true
                    }}
                  />
                )
              }}
            </OHeader>
            <div class={styles.topInfo}>
              <div class={styles.topInfoLeft}>
                <div class={styles.headWrap}>
                  <img
                    src={infoDetail.value.avatar ? infoDetail.value.avatar : defaultIcon}
                    alt=""
                  />
                </div>
                <div class={styles.infoMsg}>
                  <p>{infoDetail.value.nickname}</p>
                  <div class={styles.tag}>{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>
        </OSticky>
        {showContact.value ? (
          <PullRefresh v-model={refreshing.value} onRefresh={onRefresh}>
            <List
              v-model:loading={loading.value}
              finished={finished.value}
              finished-text="没有更多了"
              onLoad={getList}
            >
              {list.value.map((item: any) => (
                <DetailItem item={item} />
              ))}
            </List>
          </PullRefresh>
        ) : (
          <OEmpty />
        )}

        <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>
      </>
    )
  }
})
