import OHeader from '@/components/o-header'
import OPopup from '@/components/o-popup'
import OSticky from '@/components/o-sticky'
import { trainCourseEmnu } from '@/constant'
import request from '@/helpers/request'
import { verifiyNumberInteger } from '@/helpers/toolsValidate'
import { state } from '@/state'
import dayjs from 'dayjs'
import { Button, Cell, CellGroup, Field, Popup, showToast, TimePicker } from 'vant'
import { defineComponent, onMounted, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { forms } from '../../create'
import PracticeClass from '../../modal/practice-class'
import styles from './index.module.less'

export default defineComponent({
  name: 'practice-detail',
  setup() {
    const router = useRouter()
    const f = reactive({
      selectItem: {} as any,
      currentTime: [] as any,
      minHour: 0,
      minMinute: 0,
      maxHour: 24,
      maxMinute: 60,
      firstTime: null as any,
      lastTime: null as any
    })

    const configParams = async () => {
      // 获取基础数据
      const { data } = await request.get('/api-school/sysParamConfig/queryByParamNameList', {
        params: {
          paramNames: 'course_start_time,course_end_time'
        }
      })
      const tempData = data || []
      tempData.forEach((item: any) => {
        console.log(item.paramValue, 'paramValue')
        const day = dayjs(forms.trainStartDate).format('YYYY-MM-DD')
        if (item.paramName === 'course_start_time') {
          const firstTime = dayjs(day + ' ' + item.paramValue)
          f.minHour = Number(firstTime.format('HH'))
          f.minMinute = Number(firstTime.format('mm'))
          f.firstTime = firstTime
        } else if (item.paramName === 'course_end_time') {
          const lastTime = dayjs(day + ' ' + item.paramValue)
          f.maxHour = Number(lastTime.format('HH'))
          f.lastTime = lastTime
        }
      })
    }

    const onChange = (val: any) => {
      // 判断是否选择小时
      if (val.columnIndex === 1) return

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

      if (selectHour === f.minHour) {
        f.minMinute = Number(f.firstTime.format('mm'))
        f.maxMinute = 60
      } else if (selectHour === f.maxHour) {
        console.log(selectHour, 'hour')
        f.minMinute = 0
        f.maxMinute = Number(f.lastTime.format('mm'))
      } else {
        f.minMinute = 0
        f.maxMinute = 60
      }
    }

    // 选择日期
    const onConfirmTimer = (item: any) => {
      const times = dayjs(
        dayjs(f.lastTime).format('YYYY-MM-DD') + ' ' + item.selectedValues.join(':') + ':00'
      ).add(f.selectItem.trainTimer, 'minute')

      if (times.isAfter(f.lastTime)) {
        showToast('开始时间超过可选时间范围')
        return
      }

      f.selectItem.startTime = dayjs(
        dayjs(f.lastTime).format('YYYY-MM-DD') + ' ' + item.selectedValues.join(':') + ':00'
      ).format('YYYY-MM-DD HH:mm:ss')
      f.selectItem.endTime = times.format('YYYY-MM-DD HH:mm:ss')

      forms.timerStatus = false
    }
    const checkForms = () => {
      const list = forms.classPracticeList

      let status = false
      let message = ''
      list.forEach((item: any) => {
        console.log(item)
        if (!status && !item.trainTimer) {
          status = true
          message = '请输入训练时长'
        }
        if (!status && !item.startTime) {
          status = true
          message = '请选择开始时间'
        }
        if (!status && !item.times) {
          status = true
          message = '请输入课时数'
        }
        if (!status && item.classIdList.length <= 0) {
          status = true
          message = '请选择训练班级'
        }
      })

      if (status) {
        showToast(message)
      }
      return status
    }

    const onSubmit = async () => {
      if (checkForms()) return
      try {
        const list = forms.classPracticeList
        const trainingPlanClassList: any = []

        list.forEach((item: any) => {
          trainingPlanClassList.push({
            classGroupIdList: item.classIdList,
            courseNum: item.times,
            startTime: dayjs(item.startTime).format('HH:mm:ss'),
            endTime: dayjs(item.endTime).format('HH:mm:ss'),
            singleCourseTime: item.trainTimer
          })
        })
        const params = {
          week: forms.week,
          schoolId: state.user.data.school.id,
          skipHoliday: forms.skipHoliday ? true : false,
          type: 'PRACTISE',
          startDate: dayjs(forms.trainStartDate).format('YYYY-MM-DD'),
          trainingPlanClassList
        }
        console.log(params)

        const { data } = await request.post('/api-school/orchestra/trainingPlanList', {
          data: {
            ...params
          }
        })
        // 初始化 课程预览时选中的乐团编号 课程预览时选中的课程组编号
        forms.selectOrchestraId = null
        forms.selectClassGroupId = null
        forms.planList = {
          orchestra: [] as any, // 所有的乐团
          classes: {} as any, // 所有的班级
          course: {} as any // 所有的课程
        }
        console.log(data, 'date')
        router.push({
          path: '/course-preview',
          query: {
            cacheId: data
          }
        })
      } catch {
        //
      }
    }

    const onFormatterInt = (val: any) => {
      if (val && val >= 1) {
        return verifiyNumberInteger(val)
      } else {
        return ''
      }
    }

    onMounted(() => {
      configParams()
    })
    return () => (
      <div class={styles.practiceDetail}>
        <OHeader />

        {forms.classPracticeList.map((item: any) => (
          <>
            <div class={styles.title}>
              <i></i>
              {trainCourseEmnu[item.classType]}
            </div>
            <CellGroup inset class={styles.cellGroup}>
              <Field
                label="训练时长"
                placeholder="请输入训练时长"
                inputAlign="right"
                v-model={item.trainTimer}
                formatter={onFormatterInt}
                maxlength={3}
                type="tel"
                onUpdate:modelValue={(val: any) => {
                  console.log(val)
                  item.startTime = null
                }}
              >
                {{ extra: () => <span style={{ paddingLeft: '6px' }}>分钟</span> }}
              </Field>
              <Field
                label="开始时间"
                placeholder="请选择开始时间"
                inputAlign="right"
                readonly
                isLink
                modelValue={item.startTime ? dayjs(item.startTime).format('HH:mm') : ''}
                onClick={() => {
                  if (!item.trainTimer) {
                    showToast('请输入训练时长')
                    return
                  }
                  f.selectItem = item
                  forms.timerStatus = true
                }}
              />
              <Field
                label="课时数"
                placeholder="请输入课时数"
                inputAlign="right"
                v-model={item.times}
                formatter={onFormatterInt}
                maxlength={2}
                type="tel"
              >
                {{ extra: () => <span style={{ paddingLeft: '6px' }}>课时</span> }}
              </Field>
              <Cell
                title="训练班级"
                isLink
                onClick={() => {
                  f.selectItem = item
                  forms.classStatus = true
                }}
              >
                {{
                  value: () => (
                    <div class={styles.value}>
                      {item.classIdList.length <= 0 ? (
                        <div class={styles.tips}>请选择训练班级</div>
                      ) : (
                        <div>
                          已选<span style={{ padding: '0 4px' }}>{item.classIdList.length}</span>
                          个班级
                        </div>
                      )}
                    </div>
                  )
                }}
              </Cell>
            </CellGroup>
          </>
        ))}

        <OSticky position="bottom">
          <div class={'btnGroup'}>
            <Button type="primary" block round onClick={onSubmit}>
              下一步
            </Button>
          </div>
        </OSticky>

        <OPopup
          v-model:modelValue={forms.classStatus}
          position="bottom"
          style={{ background: '#f6f6f6' }}
          destroy
        >
          <PracticeClass
            onClose={() => (forms.classStatus = false)}
            classType={f.selectItem.classType}
            selectItem={f.selectItem.classIdList}
            onConfirm={(val: any) => {
              f.selectItem.classIdList = val
            }}
          />
        </OPopup>

        <Popup v-model:show={forms.timerStatus} position="bottom" round>
          <TimePicker
            v-model={f.currentTime}
            minHour={f.minHour}
            minMinute={f.minMinute}
            maxHour={f.maxHour}
            maxMinute={f.maxMinute}
            onChange={onChange}
            onCancel={() => (forms.timerStatus = false)}
            onConfirm={(val: any) => onConfirmTimer(val)}
          />
        </Popup>
      </div>
    )
  }
})
