import OEmpty from '@/components/o-empty'
import request from '@/helpers/request'
import dayjs from 'dayjs'
import { Cell, DatePicker, Icon, Image, List, Popover, Popup } from 'vant'
import { computed, defineComponent, onMounted, reactive } from 'vue'
import { useRoute } from 'vue-router'
import styles from './plan.module.less'
import iconTeacher from '@common/images/icon_teacher.png'

export default defineComponent({
  name: 'plan',
  props: {
    termTimes: {
      type: Object,
      default: {}
    }
  },
  setup(props) {
    const startTime = computed(() => props.termTimes.start)
    const endTime = computed(() => props.termTimes.end)
    const route = useRoute()
    const state = reactive({
      timeShow: false,
      currentData: [dayjs().year() + ''],
      showPopover: false,
      actionText: '上学期',
      actionType: 'up',
      actionTerm: [
        { text: '上学期', color: 'var(--van-primary-color)', value: 'up' },
        { text: '下学期', value: 'down' }
      ],
      oPopover: false,
      check: [],
      checkboxRefs: [] as any,
      showQrcode: false,
      isLoading: false,
      list: [] as any,
      listState: {
        dataShow: true, // 判断是否有数据
        loading: false,
        finished: false
      },

      params: {
        startTime: dayjs(dayjs().year() + startTime.value).format('YYYY-MM-DD HH:mm:ss'),
        endTime: dayjs(dayjs().year() + endTime.value)
          .subtract(1, 'day')
          .format('YYYY-MM-DD HH:mm:ss'),
        page: 1,
        rows: 20
      }
    })
    // 选择学期
    const onSelect = (val: any) => {
      console.log(val)
      state.actionTerm.forEach((item: any) => {
        item.color = null
      })
      val.color = 'var(--van-primary-color)'
      state.actionText = val.text
      state.actionType = val.value

      if (val.value === 'up') {
        state.params.startTime = dayjs(Number(state.currentData[0]) - 1 + startTime.value).format(
          'YYYY-MM-DD HH:mm:ss'
        )
        state.params.endTime = dayjs(Number(state.currentData[0]) + endTime.value)
          .subtract(1, 'day')
          .format('YYYY-MM-DD HH:mm:ss')
      } else if (val.value === 'down') {
        state.params.startTime = dayjs(Number(state.currentData[0]) + endTime.value).format(
          'YYYY-MM-DD HH:mm:ss'
        )
        state.params.endTime = dayjs(Number(state.currentData[0]) + startTime.value)
          .subtract(1, 'day')
          .format('YYYY-MM-DD HH:mm:ss')
      }
      onSearch()
    }

    const onConfirmDate = (date: any) => {
      state.currentData = date.selectedValues
      if (state.actionType === 'up') {
        state.params.startTime = dayjs(Number(state.currentData[0]) - 1 + startTime.value).format(
          'YYYY-MM-DD HH:mm:ss'
        )
        state.params.endTime = dayjs(Number(state.currentData[0]) + endTime.value)
          .subtract(1, 'day')
          .format('YYYY-MM-DD HH:mm:ss')
      } else if (state.actionType === 'down') {
        state.params.startTime = dayjs(Number(state.currentData[0]) + endTime.value).format(
          'YYYY-MM-DD HH:mm:ss'
        )
        state.params.endTime = dayjs(Number(state.currentData[0]) + startTime.value)
          .subtract(1, 'day')
          .format('YYYY-MM-DD HH:mm:ss')
      }
      state.timeShow = false
      onSearch()
    }

    // 班级列表
    const getList = async () => {
      try {
        if (state.isLoading) return
        state.isLoading = true
        const res = await request.post('/api-school/classGroup/page', {
          data: {
            ...state.params,
            orchestraId: route.query.id
          }
        })
        state.listState.loading = false
        const result = res.data || {}
        // 处理重复请求数据
        if (state.list.length > 0 && result.current === 1) {
          return
        }
        const rows = result.rows || []
        state.list = state.list.concat(rows)
        state.listState.finished = result.current >= result.pages
        state.params.page = result.current + 1
        state.listState.dataShow = state.list.length > 0
        state.isLoading = false
      } catch {
        state.listState.dataShow = false
        state.listState.finished = true
        state.isLoading = false
      }
    }

    const onSearch = () => {
      state.params.page = 1
      state.list = []
      state.listState.dataShow = true // 判断是否有数据
      state.listState.loading = false
      state.listState.finished = false
      getList()
    }

    onMounted(() => {
      getList()
    })
    return () => (
      <div>
        <div style={{ padding: '12px 13px 16px', background: '#F8F8F8' }}>
          <div class={styles.searchBand} onClick={() => (state.timeShow = true)}>
            {state.currentData[0]}年 <Icon name={state.showPopover ? 'arrow-up' : 'arrow-down'} />
          </div>
          <Popover
            v-model:show={state.oPopover}
            actions={state.actionTerm}
            showArrow={false}
            placement="bottom"
            offset={[0, 12]}
            style={{ zIndex: '9999' }}
            onSelect={onSelect}
          >
            {{
              reference: () => (
                <div class={styles.searchBand} style="margin-left: 16px">
                  {state.actionText} <Icon name={state.oPopover ? 'arrow-up' : 'arrow-down'} />
                </div>
              )
            }}
          </Popover>
        </div>

        {state.listState.dataShow ? (
          <List
            v-model:loading={state.listState.loading}
            finished={state.listState.finished}
            finishedText=" "
            class={[styles.liveList]}
            onLoad={getList}
            immediateCheck={false}
          >
            {state.list.map((item: any) => (
              // <div class={[styles.gridContainer, styles.gridClass]}>
              //   <div class={styles.className}>
              //     <i class={styles.line}></i>
              //     {item.name}
              //   </div>
              //   <Grid border={false} columnNum={3}>
              //     <GridItem>
              //       <p class={styles.title}>{item.preStudentNum || 0}</p>
              //       <p class={styles.name}>在读学生</p>
              //     </GridItem>
              //     <GridItem>
              //       <p class={[styles.title, styles.teacher]}>{item.teacherName || '/'}</p>
              //       <p class={styles.name}>伴学指导</p>
              //     </GridItem>
              //     <GridItem>
              //       <p class={styles.title}>
              //         {item.completeCourseScheduleNum || 0}/{item.courseScheduleNum || 0}
              //       </p>
              //       <p class={styles.name}>课时</p>
              //     </GridItem>
              //   </Grid>
              // </div>
              <div class={[styles.gridContainer, styles.gridClass]}>
                <div class={styles.className}>
                  <i class={styles.line}></i>
                  {item.name}
                </div>
                <Cell center>
                  {{
                    icon: () => (
                      <Image
                        class={styles.img}
                        src={item.teacherAvatar || iconTeacher}
                        fit="cover"
                      />
                    ),
                    title: () => (
                      <>
                        <p class={styles.class}>
                          {item.completeCourseScheduleNum || 0}/{item.courseScheduleNum || 0}
                        </p>
                        <p class={styles.teacherDesc}>课时</p>
                      </>
                    ),
                    value: () => (
                      <>
                        <p class={styles.courseware}>{item.newestLessonPlanDetailName || '-'}</p>
                        <p class={styles.teacherDesc}>最新课件</p>
                      </>
                    )
                  }}
                </Cell>
              </div>
            ))}
          </List>
        ) : (
          <OEmpty btnStatus={false} tips="暂无班级" />
        )}

        <Popup v-model:show={state.timeShow} position="bottom" round>
          <DatePicker
            v-model={state.currentData}
            columnsType={['year']}
            minDate={new Date(2010, 0, 1)}
            maxDate={new Date(2055, 11, 31)}
            onConfirm={onConfirmDate}
            onCancel={() => (state.timeShow = false)}
          />
        </Popup>
      </div>
    )
  }
})
