import OHeader from '@/components/o-header'
import OSearch from '@/components/o-search'
import OSticky from '@/components/o-sticky'
import OEmpty from '@/components/o-empty'
import dayjs from 'dayjs'
import {
  Cell,
  Icon,
  Popover,
  Tag,
  DatePicker,
  DatePickerColumnType,
  Popup,
  List,
  PullRefresh,
  ActionSheet,
  showToast
} from 'vant'
import StudentItem from './modals/student-item'
import { defineComponent, reactive, ref, onMounted } from 'vue'
import { state as globalState } from '@/state'
import { useRouter } from 'vue-router'
import styles from './index.module.less'
import request from '@/helpers/request'
export default defineComponent({
  name: 'exercise-record',
  setup() {
    const platformApi = ref(globalState.platformApi)
    const router = useRouter()
    const state = reactive({
      showPopoverTime: false,
      showPopoverOrchestra: false,
      showPopoverSubject: false,
      showPopoverSort: false,
      actions: [] as any,
      subjects: [] as any,
      actionSorts: [
        {
          text: '按天数',
          value: 'PRACTICE_DAY',
          color: '#f67146'
        },
        {
          text: '按时长',
          value: 'PRACTICE_TIMES',
          color: '#333'
        }
        //   color: forms.sortType == 'PRACTICE_DAY' ? '#FF8057' : '#333'
      ],
      currentDate: [dayjs().format('YYYY'), dayjs().format('MM')]
    })
    const forms = reactive({
      practiceMonth: state.currentDate[0] + '' + state.currentDate[1],
      practiceMonthName: state.currentDate[0] + '年' + state.currentDate[1] + '月',
      orchestraId: '',
      orchestraName: '全部乐团',
      subjectId: '',
      subjectName: '全部声部',
      sortType: 'PRACTICE_DAY',
      sortTypeName: '按天数',
      keyword: '',
      page: 1,
      rows: 20
    })
    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(`${platformApi.value}/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 || [])
        showContact.value = list.value.length > 0
        console.log(showContact.value, ' showContact.value ')
        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
      }
    }
    onMounted(() => {
      getList()
      getOrchestraList()
      getSubjects()
    })

    const onBack = () => {
      console.log('返回')
    }

    const checkSort = (val: any) => {
      forms.sortType = val.value
      forms.sortTypeName = val.text
      state.actionSorts.forEach((element) => {
        if (element.value == val.value) {
          element.color = '#f67146'
        } else {
          element.color = '#333'
        }
      })
      refreshing.value = true
      getList()
    }
    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 checkOrchestra = (val: any) => {
      forms.orchestraId = val.value
      forms.orchestraName = val.name
      state.showPopoverOrchestra = false
      refreshing.value = true
      getList()
    }

    const checkSubject = (val: any) => {
      forms.subjectId = val.value
      forms.subjectName = val.name
      console.log(val, forms)
      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(`${platformApi.value}/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)
      }
    }

    const getSubjects = async () => {
      try {
        const res = await request.post(`${platformApi.value}/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)
      }
    }
    const onRefresh = () => {
      finished.value = false
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      loading.value = true
      getList()
    }

    return () => (
      <>
        <OSticky position="top" background="#F8F8F8">
          <div>
            <OHeader onHeaderBack={onBack}></OHeader>
            <OSearch
              placeholder="请输入学生姓名"
              onSearch={(val: any) => {
                forms.keyword = val
                refreshing.value = true
                getList()
              }}
            ></OSearch>
            <div class={styles.chioseWrap}>
              <div
                class={styles.searchBandWrap}
                style={{ padding: '12px 13px', background: '#F8F8F8' }}
              >
                <div
                  class={styles.searchBand}
                  onClick={() => {
                    state.showPopoverTime = true
                  }}
                >
                  <p>{forms.practiceMonthName}</p>

                  <Icon name={state.showPopoverTime ? 'arrow-up' : 'arrow-down'} />
                </div>
              </div>

              <div
                class={styles.searchBandWrap}
                style={{ padding: '12px 13px', background: '#F8F8F8' }}
              >
                <div
                  class={styles.searchBand}
                  onClick={() => {
                    state.showPopoverOrchestra = true
                  }}
                >
                  <p> {forms.orchestraName}</p>

                  <Icon name={state.showPopoverOrchestra ? 'arrow-up' : 'arrow-down'} />
                </div>
              </div>
              <div
                class={styles.searchBandWrap}
                style={{ padding: '12px 13px', background: '#F8F8F8' }}
              >
                <div
                  class={styles.searchBand}
                  onClick={() => {
                    state.showPopoverSubject = true
                  }}
                >
                  <p>{forms.subjectName}</p>

                  <Icon name={state.showPopoverSubject ? 'arrow-up' : 'arrow-down'} />
                </div>
              </div>

              <div
                class={styles.searchBandWrap}
                style={{ padding: '12px 13px', background: '#F8F8F8' }}
              >
                <Popover
                  v-model:show={state.showPopoverSort}
                  actions={state.actionSorts}
                  showArrow={false}
                  placement="bottom-end"
                  offset={[0, 12]}
                  onSelect={checkSort}
                >
                  {{
                    reference: () => (
                      <div class={styles.searchBand}>
                        <p> {forms.sortTypeName}</p>
                        <Icon name={state.showPopoverSort ? 'arrow-up' : 'arrow-down'} />
                      </div>
                    )
                  }}
                </Popover>
              </div>
            </div>
          </div>
        </OSticky>
        {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) => (
                <StudentItem item={item} forms={forms} />
              ))}
            </List>
          </PullRefresh>
        ) : (
          <OEmpty></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.subjects}
          onSelect={checkSubject}
        ></ActionSheet>
      </>
    )
  }
})
