import OHeader from '@/components/o-header'
import item from '@/student/coupons/item'
import dayjs from 'dayjs'
// import isBetween from 'dayjs/plugin/isBetween'
// dayjs.extend(isBetween)
import { Button, Cell, CellGroup, Popup, showToast, Sticky, TimePicker } from 'vant'
import { defineComponent, onMounted, reactive, watch } from 'vue'
import styles from './index.module.less'

export default defineComponent({
  name: 'timer',
  props: {
    timerList: {
      type: Object,
      default: () => {}
    },
    times: {
      // 默认时长
      type: Number,
      default: 120
    }
  },
  emits: ['close', 'confirm'],
  setup(props, { slots, attrs, emit }) {
    const defaultTime = dayjs().format('YYYY-MM-DD HH:mm:ss')
    const state = reactive({
      calendarDate: null as any,
      selectTimeStatus: false,
      selectTime: null as any,
      useTimer: [] as any, // 可排课时间段
      useTimerFormat: [] as any,
      usedTimer: [] as any, // 不可排课时间段
      minMinute: 0,
      maxMinute: 59
    })

    const onFormatter = (type: any, option: any) => {
      if (type === 'hour') {
        option.text += '时'
      }
      if (type === 'minute') {
        option.text += '分'
      }
      return option
    }

    const onFilter = (type: any, option: any) => {
      // 时间
      if (type === 'hour') {
        const hour: any = []
        option.forEach((o: any) => {
          state.useTimerFormat.forEach((time: any) => {
            if (
              o.value >= time.startHour &&
              o.value <= time.endHour &&
              o.value != hour[hour.length - 1]?.value
            ) {
              hour.push(o)
            }
          })
        })
        return hour
      }
      return option
    }

    // 时间切换时
    // [6:30, 12:00] [15:00, 18:00]
    const onChange = (val: any) => {
      // 判断是否选择小时
      if (val.columnIndex === 1) return

      // 选择时间
      const selectHour = Number(val.selectedValues[0])

      let minute = 0 // 获取开始的分钟数
      state.useTimerFormat.forEach((item: any) => {
        if (selectHour === item.startHour) {
          minute = item.startMinute
        } else if (selectHour === item.endHour) {
          minute = item.endMinute
        }
      })

      state.minMinute = minute
      state.maxMinute = 59
    }

    //
    const onFormatTimer = (val: Array<any>) => {
      const format: any = []
      val.forEach((item: any) => {
        format.push({
          startHour: Number(dayjs(item.startTime).format('HH')),
          startMinute: Number(dayjs(item.startTime).format('mm')),
          endHour: Number(dayjs(item.endTime).format('HH')),
          endMinute: Number(dayjs(item.endTime).format('mm'))
        })
      })
      return format
    }

    // 确认时间
    const onConfirm = (val: any) => {
      // console.log(val, 'val')
      const selectedValues = val.selectedValues
      const tempDate = dayjs(state.calendarDate)
        .hour(selectedValues[0])
        .minute(selectedValues[1])
        .second(0)
      // console.log(dayjs(tempDate).format('YYYY-MM-DD HH:mm:ss'), 'first', dayjs(tempDate).minute())
      // 时间加上每节课的时间，
      const lastDate = dayjs(tempDate).minute(props.times + dayjs(tempDate).minute())
      // console.log(dayjs(lastDate).format('YYYY-MM-DD HH:mm:ss'), 'second')
      // console.log(
      //   dayjs(tempDate).format('YYYY-MM-DD HH:mm:ss'),
      //   tempDate.toDate(),
      //   'second tempDate',
      //   state.useTimer
      // )

      let isActive = false
      state.useTimer.forEach((item: any) => {
        // if (dayjs(lastDate).isBetween(item.startTime, item.endTime, null, '[]')) {
        //   isActive = true
        // }
        // 判断课程的时间范围在不在可排课时间范围内
        if (
          dayjs(tempDate).valueOf() >= dayjs(item.startTime).valueOf() &&
          dayjs(lastDate).valueOf() <= dayjs(item.endTime).valueOf()
        ) {
          isActive = true
        }
      })

      // console.log(isActive, 'isActive')
      if (!isActive) {
        showToast('您选择的时间超过可排课时间范围')
        return
      }

      state.selectTime = tempDate.toDate()
      state.selectTimeStatus = false
    }

    watch(
      () => props.timerList,
      () => {
        init()
      }
    )

    const init = () => {
      console.log(props.timerList, 'timerList')
      state.calendarDate = props.timerList?.calendarDate
      const timeDetailList = props.timerList?.timeDetailList || []

      const useTimer: any = [] // 可排课时间段
      const usedTimer: any = [] // 不可排课时间段

      timeDetailList.forEach((time: any) => {
        if (time.enable) {
          useTimer.push(time)
        } else {
          usedTimer.push(time)
        }
      })
      // 初始化时间
      state.useTimer = [...useTimer]
      const useFormat = onFormatTimer(useTimer)
      state.useTimerFormat = useFormat
      state.usedTimer = [...usedTimer]
      console.log(onFormatTimer(useTimer), 'onFormatTimer')
      console.log(state.useTimer, state.usedTimer, 'onUseTimer')

      // 判断有可排课数据
      if (useFormat.length > 0) {
        const temp = useFormat[0]
        state.minMinute = temp.startMinute
        state.maxMinute = 59
      }
    }

    onMounted(() => {
      init()
    })
    return () => (
      <div class={styles.timer}>
        <OHeader title="训练时间" desotry={false} />

        {/* <div class={styles.selectTimer}>{dayjs(state.calendarDate).format('YYYY年MM月DD日')}</div> */}

        <CellGroup inset class={styles.cellGroup} style={{ marginTop: '12px' }}>
          {state.useTimer.map((item: any) => (
            <Cell
              center
              value={`${dayjs(item.startTime).format('HH:mm')}~${dayjs(item.endTime).format(
                'HH:mm'
              )}`}
              title="可选时间"
            ></Cell>
          ))}

          {state.usedTimer.map((item: any) => (
            <Cell
              center
              title={`${dayjs(item.startTime).format('HH:mm')}~${dayjs(item.endTime).format(
                'HH:mm'
              )}`}
              value="冲突时间"
              class={styles.noTime}
            ></Cell>
          ))}
        </CellGroup>

        <CellGroup inset class={styles.cellGroup}>
          <Cell
            center
            title={'训练开始时间'}
            value={state.selectTime ? dayjs(state.selectTime).format('HH:mm') : ''}
            isLink
            onClick={() => (state.selectTimeStatus = true)}
          ></Cell>
        </CellGroup>

        <Sticky position="bottom">
          <div class={'btnGroup'}>
            <Button
              round
              block
              type="primary"
              onClick={() => {
                if (!state.selectTime) {
                  showToast('请选择训练开始时间')
                  return
                }
                emit('confirm', state.selectTime)
                emit('close')
              }}
            >
              确认
            </Button>
          </div>
        </Sticky>

        <Popup v-model:show={state.selectTimeStatus} position="bottom" round>
          <TimePicker
            minMinute={state.minMinute}
            maxMinute={state.maxMinute}
            formatter={onFormatter}
            filter={onFilter}
            onChange={onChange}
            onConfirm={onConfirm}
            onCancel={() => (state.selectTimeStatus = false)}
          />
        </Popup>
      </div>
    )
  }
})
