import OSearch from '@/components/o-search'
import OEmpty from '@/components/o-empty'
import dayjs from 'dayjs'
import {
  Icon,
  Popover,
  DatePicker,
  DatePickerColumnType,
  Popup,
  List,
  PullRefresh,
  ActionSheet,
  showToast,
  Sticky,
  Picker
} 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 './timer-bang.module.less'
import request from '@/helpers/request'
import { state as globalState } from '@/state'
import RankItem from '../modals/rank-item'
import { formatterDatePicker } from '@/helpers/utils'
export default defineComponent({
  props: ['toHeight', 'startTime', 'endTime'],
  name: 'day-bang',
  setup(props, { slots, attrs, emit }) {
    const router = useRouter()
    const state = reactive({
      showPopoverTime: false,
      showPopoverOrchestra: false,
      showPopoverSubject: false,
      actions: [] as any,
      subjects: [] as any,
      currentDate: [dayjs().format('YYYY'), dayjs().format('MM')]
    })
    const forms = reactive({
      practiceMonth: props.startTime,
      orchestraId: '',
      orchestraName: '全部乐团',
      subjectId: '',
      subjectName: '全部声部',
      page: 1,
      rows: 50,
      sortType: 'PRACTICE_TIMES'
    })
    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 toTop = ref(props.toHeight)
    console.log(props.toHeight)
    watch(
      () => props.toHeight,
      (val: number) => {
        toTop.value = val
      }
    )
    watch(
      () => props.startTime,
      () => {
        forms.practiceMonth = props.startTime
        refreshing.value = true
        getList()
      }
    )
    const getList = async () => {
      loading.value = true
      try {
        if (refreshing.value) {
          forms.page = 1
          list.value = []
          refreshing.value = false
        }

        const res = await request.post('/api-school/student/page', {
          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 || [])
        list.value = res.data.rows
        showContact.value = list.value.length > 0
        console.log(showContact.value, ' showContact.value ')
        loading.value = false
        finished.value = true
        // 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 checkOrchestra = (val: any) => {
      const selectedOptions = val.selectedOptions[0] || {}
      forms.orchestraId = selectedOptions.value
      forms.orchestraName = selectedOptions.name
      state.showPopoverOrchestra = false
      refreshing.value = true
      getList()
    }

    const checkSubject = (val: any) => {
      const selectedOptions = val.selectedOptions[0] || {}
      forms.subjectId = selectedOptions.value
      forms.subjectName = selectedOptions.name
      state.showPopoverSubject = false
      refreshing.value = true
      getList()
    }
    const getOrchestraList = async () => {
      // const schoolId = globalState.user.data.schoolInfos
      //   .map((item) => {
      //     return item.id
      //   })
      //   .join(',')
      try {
        const res = await request.post('/api-school/orchestra/page', {
          data: { page: 1, rows: 9999, status: 'DONE' }
        })
        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)
      }
    }

    const getSubjects = async () => {
      try {
        const res = await request.post('/api-school/subjectBasicConfig/page', {
          data: { page: 1, rows: 9999 }
        })
        state.subjects = res.data.rows.map((item) => {
          return {
            name: item.subjectName,
            value: item.subjectId as string
          }
        })
        state.subjects.unshift({ name: '全部声部', value: '' })
      } catch (e: any) {
        const message = e.message
        showToast(message)
      }
    }

    onMounted(() => {
      getSubjects()
      getOrchestraList()
      getList()
    })
    const onRefresh = () => {
      finished.value = false
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      loading.value = true
      getList()
    }
    return () => (
      <div
        class={[!showContact.value && 'emptyRootContainer', styles.bangContainer]}
        style={{ minHeight: `calc(100vh - ${toTop.value}px)` }}
      >
        {/* <OSticky position="top" background="#FFF"> */}
        <Sticky offsetTop={toTop.value} style={{ width: '100%' }}>
          <div class={'searchGroup'}>
            {/* <div
              class={['searchItem searchItem-normal', state.showPopoverTime && 'searchItem-active']}
              onClick={() => {
                state.showPopoverTime = true
              }}
            >
              <span>{forms.timeName}</span>
              <i class="arrow"></i>
            </div> */}
            <div
              class={[
                'searchItem searchItem-normal',
                state.showPopoverOrchestra && 'searchItem-active'
              ]}
              onClick={() => {
                state.showPopoverOrchestra = true
              }}
            >
              <span>{forms.orchestraName}</span>
              <i class="arrow"></i>
            </div>
            <div
              class={[
                'searchItem searchItem-normal',
                state.showPopoverSubject && 'searchItem-active'
              ]}
              onClick={() => {
                state.showPopoverSubject = true
              }}
            >
              <span>{forms.subjectName}</span>
              <i class="arrow"></i>
            </div>
          </div>
        </Sticky>
        {/* </OSticky> */}

        {showContact.value ? (
          <OFullRefresh
            v-model:modelValue={refreshing.value}
            onRefresh={onRefresh}
            style={{
              minHeight: `calc(100vh - ${toTop.value}px - 1.17333rem)`
            }}
          >
            <List
              // v-model:loading={loading.value}
              finished={finished.value}
              finished-text=" "
              onLoad={getList}
              loading-text=" "
            >
              {list.value.map((item: any, index: number) => (
                <RankItem item={item} type="day" index={index + 1}></RankItem>
              ))}
            </List>
          </OFullRefresh>
        ) : (
          <OEmpty tips="暂无排行" />
        )}

        <Popup
          v-model:show={state.showPopoverOrchestra}
          position="bottom"
          round
          class={'popupBottomSearch'}
        >
          <Picker
            columns={state.actions}
            onCancel={() => (state.showPopoverOrchestra = false)}
            onConfirm={(val: any) => checkOrchestra(val)}
            columnsFieldNames={{ text: 'name', value: 'value' }}
          />
        </Popup>

        <Popup
          v-model:show={state.showPopoverSubject}
          position="bottom"
          round
          class={'popupBottomSearch'}
        >
          <Picker
            columns={state.subjects}
            onCancel={() => (state.showPopoverSubject = false)}
            onConfirm={(val: any) => checkSubject(val)}
            columnsFieldNames={{ text: 'name', value: 'value' }}
          />
        </Popup>
      </div>
    )
  }
})
