import OHeader from '@/components/o-header'
import { CellGroup, Cell, Button, showToast, Field, Tag, showSuccessToast } from 'vant'
import { defineComponent, reactive, ref, onMounted } from 'vue'
import { postMessage } from '@/helpers/native-message'
import styles from './course-adjust.module.less'
import { useRouter, useRoute } from 'vue-router'
import request from '@/helpers/request'
import dayjs from 'dayjs'
import { courseEmnu } from '@/constant'
import { browser } from '@/helpers/utils'
import { state as baseState } from '@/state'
import OPopup from '@/components/o-popup'
import Calendar from '../train-planning/modal/calendar'
import Timer from '../train-planning/modal/timer'
import TeacherList from '../orchestra/modal/teacher-list'
import OSticky from '@/components/o-sticky'

export default defineComponent({
  name: 'course-adjust',
  setup() {
    const router = useRouter()
    const route = useRoute()
    const state = reactive({
      id: route.query.id,
      cacheId: route.query.cacheId,
      showPopoverTime: false,
      showPopoverCourseTime: false,
      showPopoverTeacher: false,
      currentDate: [] as any,
      currentCourseDate: [] as any,
      teachers: [] as any,
      calendarList: [] as any,
      calendarDate: null as any,
      trainStartTime: null, // 开始时间
      timerList: {} as any, // 可选和不可选时间段
      trainTimer: 0,
      selectItem: {} as any,
      arrangeType: 'STANDARD', // 标准排课还是加课
      isBack: route.query.isBack
    })
    const forms = reactive({
      classDate: '',
      teacherName: '',
      teacherId: '',
      courseScheduleId: '',
      startTime: '',
      endTime: ''
    })
    const courseDetail = ref({} as any)
    const getDetail = async () => {
      if (state.cacheId) {
        const { data } = await request.get('/api-school/courseSchedule/detailCache', {
          params: {
            courseScheduleId: state.id,
            cacheId: state.cacheId
          }
        })
        courseDetail.value = { ...data }
        state.arrangeType = data.arrangeType || 'STANDARD'

        forms.classDate = data.classDate
        forms.teacherName = data.teacherName
        forms.teacherId = data.teacherId
        forms.courseScheduleId = data.id
        forms.startTime = data.startTime
        forms.endTime = data.endTime
        // 时间
        state.calendarDate = data.classDate
        return
      }
      const { data } = await request.get(`/api-school/courseSchedule/detail/${state.id}`, {})
      courseDetail.value = { ...data }
      forms.classDate = courseDetail.value.classDate
      forms.teacherId = courseDetail.value.teacherId
      forms.teacherName = courseDetail.value.teacherName
      forms.courseScheduleId = courseDetail.value.id
      forms.startTime = courseDetail.value.startTime
      forms.endTime = courseDetail.value.endTime
      // 时间
      state.calendarDate = data.classDate
    }

    // 获取排课空闲时间
    const getList = async (date?: any) => {
      try {
        const { data } = await request.post('/api-school/orchestra/calendarDateQuery', {
          data: {
            teacherId: forms.teacherId,
            schoolId: baseState.user.data.school.id,
            courseScheduleId: forms.courseScheduleId,
            cacheId: state.cacheId,
            skipHoliday: false,
            calendarDate: dayjs(date).format('YYYY-MM-DD')
          }
        })
        // console.log(data)
        state.calendarList = data || []
      } catch {
        //
      }
    }

    onMounted(async () => {
      await getDetail()
      await getList(forms.classDate)

      // 初始化课程开始时间
      state.calendarList.forEach((item: any) => {
        if (dayjs(item.calendarDate).isSame(forms.classDate)) {
          state.timerList = { ...item }
        }
      })
    })
    const reset = async () => {
      // await getDetail()
      // await getList()
      if (browser().iPhone && !state.cacheId && state.isBack != 'true') {
        // setTimeout(() => {
        postMessage({ api: 'back' })
        // }, 1000)
      } else {
        router.back()
      }
    }

    const submit = async () => {
      console.log(forms)
      try {
        if (!forms.classDate) {
          showToast('请选择课程开始日期')
          return
        }

        if (!forms.startTime) {
          showToast('请选择课程开始时间')
          return
        }

        await request.post(`/api-school/courseSchedule/adjust`, {
          data: {
            ...forms,
            cacheId: state.cacheId
          }
        })

        setTimeout(() => {
          showSuccessToast('调整成功')
        }, 100)
        setTimeout(() => {
          reset()
        }, 1100)
      } catch (e: any) {
        showToast(e.message)
      }
      console.log('课程调整')
    }

    return () => (
      <>
        <div class={styles.courseWrap}>
          <OHeader border={false}></OHeader>
          <div class={styles.courseInfo}>
            <CellGroup inset border={false}>
              <Cell title="乐团名称" value={courseDetail.value.orchestraName} />
              <Cell title="课程类型">
                {{
                  value: () => (
                    <Tag type="primary" size="medium">
                      {courseEmnu[courseDetail.value.type]}
                    </Tag>
                  )
                }}
              </Cell>
              <Cell
                title="授课老师"
                value={forms.teacherName}
                onClick={() => {
                  state.showPopoverTeacher = true
                }}
                is-link
              />
              <Field
                label="上课日期"
                inputAlign="right"
                readonly
                isLink
                placeholder="请选择上课日期"
                onClick={() => (state.showPopoverTime = true)}
                modelValue={forms.classDate ? dayjs(forms.classDate).format('YYYY-MM-DD') : ''}
              />

              <Field
                label="上课时间"
                inputAlign="right"
                readonly
                isLink
                placeholder="请选择上课时间"
                modelValue={forms.startTime ? dayjs(forms.startTime).format('HH:mm') : ''}
                onClick={() => {
                  let freeTimeCount = 0
                  const timeDetailList = state.timerList.timeDetailList || []
                  timeDetailList.forEach((item: any) => {
                    if (item.enable === true) {
                      freeTimeCount += 1
                    }
                  })
                  // 判断是否有排课时间段
                  if (freeTimeCount <= 0) {
                    showToast('当前没有可排课时间段，请重新选择课程开始日期')
                    return
                  }
                  state.showPopoverCourseTime = true
                }}
              />
              <Cell title="课程时长" value={(courseDetail.value.singleCourseTime || 0) + '分钟'} />
            </CellGroup>
          </div>
          <OSticky position="bottom">
            <div class={['btnGroup btnMore']}>
              <Button color="#ccc" round class={styles.unpassBtn} onClick={() => reset()}>
                取消
              </Button>
              <Button color="#FF8057" round class={styles.unpassBtn} onClick={() => submit()}>
                确认调整
              </Button>
            </div>
          </OSticky>

          {/* 选择训练开始日期 */}
          <OPopup v-model:modelValue={state.showPopoverTime} position="bottom" destroy>
            <Calendar
              list={state.calendarList}
              nextMonth={(date: Date) => getList(date)}
              prevMonth={(date: Date) => getList(date)}
              onSelect={(date: any) => {
                state.showPopoverTime = false
                forms.classDate = dayjs(date).format('YYYY-MM-DD')
                state.calendarList.forEach((item: any) => {
                  if (dayjs(item.calendarDate).isSame(date)) {
                    state.timerList = { ...item }
                    setTimeout(() => {
                      state.showPopoverCourseTime = true
                    }, 100)
                  }
                })

                forms.startTime = ''
              }}
              onDestory={() => {
                if (forms.classDate) {
                  getList(forms.classDate)
                } else {
                  getList()
                }
              }}
              v-model:calendarDate={state.calendarDate}
            />
          </OPopup>

          {/* 选择开始时间 */}
          <OPopup
            v-model:modelValue={state.showPopoverCourseTime}
            position="bottom"
            style={{ background: '#F6F6F6' }}
            destroy
          >
            <Timer
              timerList={state.timerList}
              times={courseDetail.value.singleCourseTime || 0}
              onClose={() => (state.showPopoverCourseTime = false)}
              onConfirm={(val: any) => {
                forms.startTime = dayjs(val).format('YYYY-MM-DD HH:mm:ss')

                forms.endTime = dayjs(val)
                  .add(courseDetail.value.singleCourseTime, 'minute')
                  .format('YYYY-MM-DD HH:mm:ss')
              }}
            />
          </OPopup>

          <OPopup v-model:modelValue={state.showPopoverTeacher} position="bottom">
            <TeacherList
              courseType={courseDetail.value.type}
              removeTeacherId={forms.teacherId}
              onClose={() => (state.showPopoverTeacher = false)}
              onSelect={(val: any) => {
                // 换老师之后重置数据
                if (forms.teacherId !== val.id) {
                  forms.classDate = ''
                  forms.startTime = ''
                  forms.endTime = ''
                  forms.teacherId = val.id
                  forms.teacherName = val.nickname
                  state.calendarDate = ''
                  getList()
                }
              }}
            />
          </OPopup>
        </div>
      </>
    )
  }
})
