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 isBetween from 'dayjs/plugin/isBetween'
dayjs.extend(isBetween)
import { Icon, List, showToast, DropdownMenu, DropdownItem, Button, Calendar } from 'vant'
import OFullRefresh from '@/components/o-full-refresh'
import StudentItem from './modals/student-item'
import { defineComponent, reactive, ref, onMounted, nextTick } from 'vue'
import { state as globalState } from '@/state'
import { useRoute, 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 route = useRoute()
    const state = reactive({
      showSearchStatus: true,
      showPopoverTime: false,
      actions: [] as any,
      subjects: [] as any,
      listState: {
        dataShow: true, // 判断是否有数据
        loading: false,
        finished: false,
        refreshing: false,
        height: 0 // 页面头部高度，为了处理下拉刷新用的
      },
      isClick: false
    })
    const forms = reactive({
      startTime: dayjs().day(1).format('YYYY-MM-DD'),
      endTime: dayjs().day(7).format('YYYY-MM-DD'),
      orchestraId: '',
      orchestraName: '',
      subjectId: '',
      subjectName: '',
      sortType: '',
      sortTypeName: '',
      keyword: '',
      page: 1,
      rows: 20
    })
    // const loading = ref(false)
    // const finished = ref(false)
    // const showContact = ref(true)
    const list = ref([])

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

        const { endTime, startTime, ...re } = forms
        const res = await request.post(
          `${platformApi.value}/musicPracticeRecord/${
            globalState.platformType === 'TEACHER' ? 'teacher' : 'school'
          }/studentPracticeThisWeek`,
          {
            data: { ...re, endTime: endTime + ' 23:59:59', startTime: startTime + ' 00:00:00' }
          }
        )
        state.listState.loading = false
        state.listState.refreshing = false
        const result = res.data || {}
        // 处理重复请求数据
        if (list.value.length > 0 && result.current === 1) {
          return
        }
        list.value = list.value.concat(result.rows || [])
        state.listState.finished = result.current >= result.pages
        forms.page = result.current + 1
        state.listState.dataShow = list.value.length > 0
        state.isClick = false
      } catch {
        state.listState.dataShow = false
        state.listState.finished = true
        state.listState.refreshing = false
        state.isClick = false
      }
    }

    onMounted(async () => {
      await getSubjects()
      await getOrchestraList()
      await getList()
    })

    const onBack = () => {
      router.go(-1)
    }

    const checkSort = (val: any) => {
      forms.sortType = val.value
      forms.sortTypeName = val.name
    }

    const checkOrchestra = (val: any) => {
      forms.orchestraId = val.value
      forms.orchestraName = val.name
    }

    const checkSubject = (val: any) => {
      forms.subjectId = val.value
      forms.subjectName = val.name
    }
    const getOrchestraList = async () => {
      try {
        const res = await request.post(`${platformApi.value}/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
          }
        })
      } 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, enableFlag: true }
        })
        state.subjects = res.data.rows.map((item) => {
          if (route.query.subjectId == item.subjectId) {
            forms.subjectId = item.subjectId
            forms.subjectName = item.subjectName
          }
          return {
            name: item.subjectName,
            value: item.subjectId as string
          }
        })
      } catch (e: any) {
        const message = e.message
        showToast(message)
      }
    }
    const onRefresh = () => {
      state.listState.finished = false
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      state.listState.loading = true
      console.log(3)
      getList()
    }

    // 名称
    const formatLength = (name: string) => {
      if (name.length > 11) {
        const fristName = name.substring(0, 6)
        const lastName = name.substring(name.length - 5, name.length)
        return fristName + '...' + lastName
      } else {
        return name
      }
    }

    const dropdownMenuRef = ref()
    const dropdownItemRef = ref()
    // 重置
    const onSearchReset = () => {
      forms.startTime = dayjs().day(1).format('YYYY-MM-DD')
      forms.endTime = dayjs().day(7).format('YYYY-MM-DD')
      forms.orchestraId = ''
      forms.orchestraName = ''
      forms.subjectId = ''
      forms.subjectName = ''
      forms.sortType = ''
      forms.sortTypeName = ''
      dropdownItemRef.value?.toggle()
      state.listState.refreshing = true
      console.log(4)
      getList()
    }

    // 搜索
    const onSearchConfirm = () => {
      dropdownItemRef.value?.toggle()
      state.listState.refreshing = true
      console.log(5)
      getList()
    }

    return () => (
      <div class={[!state.listState.dataShow ? 'emptyRootContainer' : '', styles.exerciseRecord]}>
        <OSticky
          position="top"
          background="#F8F8F8"
          onGetHeight={(height: any) => {
            document.documentElement.style.setProperty('--header-height', height + 'px')
          }}
        >
          <OHeader border={false}>
            {{
              right: () => (
                <DropdownMenu
                  class={styles.searchMore}
                  closeOnClickOverlay={false}
                  closeOnClickOutside={false}
                  ref={dropdownMenuRef}
                >
                  <DropdownItem title="筛选" v-model={state.showSearchStatus} ref={dropdownItemRef}>
                    <div class={styles.searchContainer}>
                      {state.actions.length > 0 && (
                        <>
                          <div class={styles.searchTitle}>乐团</div>
                          <div class={[styles.searchTypeGroup, styles.searchTypeFlex]}>
                            {state.actions.map((item: any) => (
                              <div
                                class={[
                                  styles.searchTypeItem,
                                  item.value === forms.orchestraId && styles['is-active']
                                ]}
                                onClick={() => checkOrchestra(item)}
                              >
                                {formatLength(item.name)}
                              </div>
                            ))}
                          </div>
                        </>
                      )}

                      <div class={styles.searchTitle}>时间段</div>
                      <div class={[styles.searchTypeGroup, styles.searchTypeFlex2]}>
                        <div
                          class={styles.searchTypeItem}
                          onClick={() => (state.showPopoverTime = true)}
                        >
                          {forms.startTime}
                        </div>
                        <div
                          class={styles.searchTypeItemLine}
                          onClick={() => (state.showPopoverTime = true)}
                        ></div>
                        <div
                          class={styles.searchTypeItem}
                          onClick={() => (state.showPopoverTime = true)}
                        >
                          {forms.endTime}
                        </div>
                      </div>
                      <div class={styles.searchTitle}>声部</div>
                      <div class={[styles.searchTypeGroup, styles.searchTypeFlex1]}>
                        {state.subjects.map((subject: any) => (
                          <div
                            class={[
                              styles.searchTypeItem,
                              subject.value === forms.subjectId && styles['is-active']
                            ]}
                            onClick={() => checkSubject(subject)}
                          >
                            {subject.name}
                          </div>
                        ))}
                      </div>
                      <div class={styles.searchTitle}>排序方式</div>
                      <div class={[styles.searchTypeGroup, styles.searchTypeFlex]}>
                        {[
                          {
                            name: '按时长',
                            value: 'PRACTICE_TIMES'
                          },
                          {
                            name: '按天数',
                            value: 'PRACTICE_DAY'
                          }
                        ].map((item: any) => (
                          <div
                            class={[
                              styles.searchTypeItem,
                              forms.sortType === item.value && styles['is-active']
                            ]}
                            onClick={() => checkSort(item)}
                          >
                            {item.name}
                          </div>
                        ))}
                      </div>
                    </div>
                    <div class={[styles.searchMoreGroup, 'van-hairline--top']}>
                      <Button type="default" block round onClick={onSearchReset}>
                        重置
                      </Button>
                      <Button type="primary" block round onClick={onSearchConfirm}>
                        查询
                      </Button>
                    </div>
                  </DropdownItem>
                </DropdownMenu>
              )
            }}
          </OHeader>
          <div
            style={{
              backgroundColor: '#fff'
            }}
          >
            <OSearch
              placeholder="请输入学员姓名"
              class={styles.recordSearch}
              onSearch={(val: any) => {
                forms.keyword = val
                state.listState.refreshing = true
                console.log(6)
                getList()
              }}
            ></OSearch>
            <div class={styles.searchPreview}>
              <div
                class={styles.searchPreviewItem}
                onClick={() => {
                  // console.log(dropdownItemRef.value, dropdownMenuRef.value)
                  dropdownItemRef.value?.toggle()
                  nextTick(() => {
                    ;(
                      document.querySelectorAll('.van-dropdown-item--down')[0] as any
                    ).style.top = `calc(var(--van-nav-bar-height) + ${globalState.navBarHeight}px`
                  })
                }}
              >
                {forms.startTime}~{forms.endTime}
              </div>
              {forms.orchestraId && (
                <div class={styles.searchPreviewItem}>
                  {formatLength(forms.orchestraName)}
                  <Icon
                    name="cross"
                    class={styles.cross}
                    onClick={(e: any) => {
                      forms.orchestraId = ''
                      forms.orchestraName = ''
                      e.stopPropagation()
                      state.listState.refreshing = true
                      console.log(8)
                      getList()
                    }}
                  />
                </div>
              )}
              {forms.subjectId && (
                <div class={styles.searchPreviewItem}>
                  {forms.subjectName}
                  <Icon
                    name="cross"
                    class={styles.cross}
                    onClick={(e: any) => {
                      forms.subjectId = ''
                      forms.subjectName = ''
                      e.stopPropagation()
                      state.listState.refreshing = true
                      console.log(2)
                      getList()
                    }}
                  />
                </div>
              )}
              {forms.sortType && (
                <div class={styles.searchPreviewItem}>
                  {forms.sortTypeName}
                  <Icon
                    name="cross"
                    class={styles.cross}
                    onClick={(e: any) => {
                      forms.sortType = ''
                      forms.sortTypeName = ''
                      e.stopPropagation()
                      state.listState.refreshing = true
                      console.log(1)
                      getList()
                    }}
                  />
                </div>
              )}
            </div>
          </div>
        </OSticky>
        {state.listState.dataShow ? (
          <OFullRefresh
            v-model:modelValue={state.listState.refreshing}
            onRefresh={onRefresh}
            style="min-height: calc(100vh - var(--header-height))"
          >
            <List
              // v-model:loading={loading.value}
              finished={state.listState.finished}
              style={{
                paddingTop: '12px'
              }}
              finishedText=" "
              onLoad={getList}
              immediateCheck={false}
            >
              {list.value.map((item: any) => (
                <StudentItem item={item} forms={forms} />
              ))}
            </List>
          </OFullRefresh>
        ) : (
          <OEmpty tips="暂无练习记录" />
        )}

        <Calendar
          v-model:show={state.showPopoverTime}
          firstDayOfWeek={1}
          showConfirm={false}
          type="range"
          maxRange={7}
          minDate={new Date('2023-02-27')}
          defaultDate={[dayjs(forms.startTime).toDate(), dayjs(forms.endTime).toDate()]}
          style={{
            height: '70%'
          }}
          onSelect={(item: any) => {
            forms.startTime = ''
            forms.endTime = ''
            if (!dayjs(item[0]).isBetween(dayjs(forms.startTime), dayjs(forms.endTime))) {
              // forms.startTime = dayjs(item[0]).day(1).format('YYYY-MM-DD')
              // forms.endTime = dayjs(item[0]).day(7).format('YYYY-MM-DD')

              const week = dayjs(item[0]).day()
              if (week === 0) {
                // 星期天
                forms.startTime = dayjs(item[0]).subtract(6, 'day').format('YYYY-MM-DD')
                forms.endTime = dayjs(item[0]).format('YYYY-MM-DD')
              } else if (week === 1) {
                // 星期一
                forms.startTime = dayjs(item[0]).format('YYYY-MM-DD')
                forms.endTime = dayjs(item[0]).add(6, 'day').format('YYYY-MM-DD')
              } else {
                forms.startTime = dayjs(item[0])
                  .subtract(week - 1, 'day')
                  .format('YYYY-MM-DD')
                forms.endTime = dayjs(item[0])
                  .add(7 - week, 'day')
                  .format('YYYY-MM-DD')
              }
            }
            state.showPopoverTime = false
          }}
        />
      </div>
    )
  }
})
