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 } 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
    })
    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 refreshing = ref(false)
    const loading = ref(false)
    const finished = ref(false)
    const showContact = ref(true)
    const list = ref([])
    const getList = async () => {
      loading.value = true
      try {
        if (refreshing.value) {
          forms.page = 1
          list.value = []
          refreshing.value = false
        }
        const { endTime, startTime, ...re } = forms
        // , endTime: endTime + ' 23:59:59', startTime: endTime + ' 00:00:00'
        const res = await request.post(
          `${platformApi.value}/musicPracticeRecord/school/studentPracticeThisWeek`,
          {
            data: { ...re }
          }
        )

        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(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 }
        })
        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 = () => {
      finished.value = false
      // 重新加载数据
      // 将 loading 设置为 true，表示处于加载状态
      loading.value = true
      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()
      refreshing.value = true
      getList()
    }

    // 搜索
    const onSearchConfirm = () => {
      dropdownItemRef.value?.toggle()
      refreshing.value = true
      getList()
    }

    return () => (
      <div class={[!showContact.value ? '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 size="large" onClick={onSearchReset}>
                        重置
                      </Button>
                      <Button type="primary" block round size="large" onClick={onSearchConfirm}>
                        查询
                      </Button>
                    </div>
                  </DropdownItem>
                </DropdownMenu>
              )
            }}
          </OHeader>
          <div
            style={{
              backgroundColor: '#fff'
            }}
          >
            <OSearch
              placeholder="请输入学员姓名"
              class={styles.recordSearch}
              onSearch={(val: any) => {
                forms.keyword = val
                refreshing.value = true
                getList()
              }}
            ></OSearch>
            <div class={styles.searchPreview}>
              <div
                class={styles.searchPreviewItem}
                onClick={() => {
                  // console.log(dropdownItemRef.value, dropdownMenuRef.value)
                  // dropdownItemRef.value?.toggle()
                  // dropdownMenuRef.value?.click()
                }}
              >
                {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()
                      refreshing.value = true
                      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()
                      refreshing.value = true
                      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()
                      refreshing.value = true
                      getList()
                    }}
                  />
                </div>
              )}
            </div>
          </div>
        </OSticky>
        {showContact.value ? (
          <OFullRefresh
            v-model:modelValue={refreshing.value}
            onRefresh={onRefresh}
            style="min-height: calc(100vh - var(--header-height))"
          >
            <List
              loading-text=" "
              // v-model:loading={loading.value}
              finished={finished.value}
              style={{
                paddingTop: '12px'
              }}
              finished-text=" "
              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')
            }
            state.showPopoverTime = false
          }}
        />
      </div>
    )
  }
})
