import OHeader from '@/components/o-header'
import OEmpty from '@/components/o-empty'
import dayjs from 'dayjs'
import {
  Icon,
  Popover,
  DatePicker,
  DatePickerColumnType,
  Popup,
  List,
  PullRefresh,
  ActionSheet,
  showToast,
  Sticky
} from 'vant'
import OFullRefresh from '@/components/o-full-refresh'
import { defineComponent, reactive, ref, onMounted, watch } from 'vue'
import { useRouter } from 'vue-router'
import styles from './index.module.less'
import request from '@/helpers/request'
import { state as globalState } from '@/state'
import { courseEmnu } from '@/constant'
import TeacherAttItem from './modals/teacherAtt-item'
import OSticky from '@/components/o-sticky'
export default defineComponent({
  name: 'attend-student',
  props: {
    toHeight: {
      type: Number,
      default: 0
    }
  },
  setup(props) {
    const router = useRouter()
    const state = reactive({
      showPopoverTime: false,
      showPopoverOrchestra: false,
      showPopoverSubject: false,
      actions: [] as any,
      courseList: [] as any,
      currentDate: [dayjs().format('YYYY'), dayjs().format('MM')]
    })
    const forms = reactive({
      time: state.currentDate[0] + '-' + state.currentDate[1],
      timeName: state.currentDate[0] + '年' + state.currentDate[1] + '月',
      keyword: '',
      orchestraId: '',
      orchestraName: '全部乐团',
      courseType: '',
      courseTypeName: '所有课程',
      page: 1,
      rows: 20
    })
    const toTop = ref(props.toHeight)
    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 list = ref([])

    const getList = async () => {
      loading.value = true
      try {
        if (refreshing.value) {
          forms.page = 1
          list.value = []
          refreshing.value = false
        }

        const res = await request.post('/api-teacher/courseSchedule/teacherAttendance', {
          data: { ...forms }
        })

        if (list.value.length > 0 && res.data.pages === 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 getCourseList = () => {
      state.courseList = []
      for (const key in courseEmnu) {
        state.courseList.push({ name: courseEmnu[key], value: key })
      }
      state.courseList.unshift({ name: '全部课程', value: '' })
    }
    const checkTimer = (val: any) => {
      forms.time = val.selectedValues[0] + '-' + val.selectedValues[1]
      forms.timeName = val.selectedValues[0] + '年' + val.selectedValues[1] + '月'
      state.showPopoverTime = false
      refreshing.value = true
      getList()
    }
    const checkOrchestra = (val: any) => {
      forms.orchestraId = val.value
      forms.orchestraName = val.name
      state.showPopoverOrchestra = false
      refreshing.value = true
      getList()
    }

    const checkSubject = (val: any) => {
      forms.courseType = val.value
      forms.courseTypeName = val.name
      refreshing.value = true
      getList()
    }
    const getOrchestraList = async () => {
      try {
        const res = await request.post('/api-teacher/orchestra/page', {
          data: { page: 1, rows: 9999 }
        })
        state.actions = res.data.rows.map((item) => {
          return {
            name: item.name,
            value: item.id as string
          }
        })
        state.actions.unshift({ name: '全部乐团', value: '' })
      } catch (e: any) {
        const message = e.message
        showToast(message)
      }
    }
    watch(
      () => props.toHeight,
      (val: number) => {
        toTop.value = val
        console.log(toTop.value, '老师的')
      }
    )
    onMounted(() => {
      getOrchestraList()
      getList()
      getCourseList()
    })
    const onRefresh = () => {
      finished.value = false
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      loading.value = true
      getList()
    }
    return () => (
      <>
        <OSticky position="top">
          <OHeader />
          <div class={styles.chioseWrap}>
            <div style={{ padding: '12px 13px', background: '#F8F8F8' }}>
              <div
                class={styles.searchBand}
                onClick={() => {
                  state.showPopoverTime = true
                }}
              >
                {forms.timeName}
                <Icon name={state.showPopoverTime ? 'arrow-up' : 'arrow-down'} />
              </div>
            </div>

            <div style={{ padding: '12px 13px', background: '#F8F8F8' }}>
              <div
                class={[styles.searchBand, styles.orchestraBand]}
                onClick={() => {
                  state.showPopoverOrchestra = true
                }}
              >
                <div class={['van-ellipsis', styles.bandName]}>{forms.orchestraName}</div>
                <Icon name={state.showPopoverOrchestra ? 'arrow-up' : 'arrow-down'} />
              </div>
            </div>
            <div style={{ padding: '12px 13px', background: '#F8F8F8' }}>
              <div
                class={styles.searchBand}
                onClick={() => {
                  state.showPopoverSubject = true
                }}
              >
                {forms.courseTypeName}
                <Icon name={state.showPopoverSubject ? 'arrow-up' : 'arrow-down'} />
              </div>
            </div>
          </div>
        </OSticky>

        {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) => (
                <TeacherAttItem item={item}></TeacherAttItem>
              ))}
            </List>
          </OFullRefresh>
        ) : (
          <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>

        <ActionSheet
          v-model:show={state.showPopoverOrchestra}
          title="选择乐团"
          actions={state.actions}
          onSelect={checkOrchestra}
        ></ActionSheet>

        <ActionSheet
          style={{ height: '40%' }}
          close-on-click-action
          v-model:show={state.showPopoverSubject}
          title="选择课程"
          actions={state.courseList}
          onSelect={checkSubject}
        ></ActionSheet>
      </>
    )
  }
})
