import OHeader from '@/components/o-header'
import OSticky from '@/components/o-sticky'
import {
  CellGroup,
  Cell,
  Button,
  Popup,
  DatePicker,
  DatePickerColumnType,
  TimePicker,
  TimePickerColumnType,
  ActionSheet,
  showToast
} 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 { state as globalState } from '@/state'
import { browser } from '@/helpers/utils'
const columnsType = ref<DatePickerColumnType[]>(['year', 'month', 'day'])
const columnsTypeTime = ref<TimePickerColumnType[]>(['hour', 'minute'])
const schoolId = (globalState.user.data.schoolInfos || [])
  .map((item: any) => {
    return item.id
  })
  .join(',')
export default defineComponent({
  name: 'course-adjust',
  setup() {
    const router = useRouter()
    const route = useRoute()
    const state = reactive({
      id: route.query.id,
      showPopoverTime: false,
      showPopoverCourseTime: false,
      showPopoverTeacher: false,
      currentDate: [] as any,
      currentCourseDate: [] as any,
      teachers: [] as any
    })
    const forms = reactive({
      classDate: '',
      teacherId: '',
      courseScheduleId: '',
      startTime: '',
      endTime: ''
    })
    const courseDetail = ref({} as any)
    const getDetail = async () => {
      const { data } = await request.get(`/api-school/courseSchedule/detail/${route.query.id}`, {})
      courseDetail.value = { ...data }
      state.currentDate = [
        dayjs(courseDetail.value.classDate).format('YYYY'),
        dayjs(courseDetail.value.classDate).format('MM'),
        dayjs(courseDetail.value.classDate).format('DD')
      ]

      state.currentCourseDate = [
        dayjs(courseDetail.value.startTime).format('hh'),
        dayjs(courseDetail.value.startTime).format('mm')
      ]
      forms.classDate = courseDetail.value.classDate
      forms.teacherId = courseDetail.value.teacherId
      forms.courseScheduleId = courseDetail.value.id
      forms.startTime = courseDetail.value.startTime
      forms.endTime = courseDetail.value.endTime
      /**
       *   classDate: '',
      teacherId: '',
      courseScheduleId: '',
      startTime: '',
      endTime: ''
       */
    }

    const getTeacherList = async () => {
      try {
        const { data } = await request.post(`/api-school/teacher/page`, {
          data: {
            schoolId,
            page: 1,
            rows: 99999
          }
        })
        state.teachers = data.rows.map((item) => {
          return {
            name: item.nickname,
            value: item.id as string
          }
        })
      } catch (e: any) {
        showToast(e.message)
      }
    }

    const checkTeacher = (val: any) => {
      console.log(val)
      courseDetail.value.teacherName = val.name
      forms.teacherId = val.id
    }
    onMounted(() => {
      getDetail()
      getTeacherList()
    })
    const reset = () => {
      getDetail()
    }

    const submit = async () => {
      console.log(forms)
      try {
        const { data } = await request.post(`/api-school/courseSchedule/adjust`, {
          data: {
            ...forms
          }
        })
        if (browser().iPhone) {
          postMessage({ api: 'back' })
        } else {
          router.back()
        }
        showToast('调整成功')
      } catch (e: any) {
        showToast(e.message)
      }
      console.log('课程调整')
    }
    const checkTimer = (val: any) => {
      // forms.practiceMonth = val.selectedValues[0] + val.selectedValues[1]
      // forms.practiceMonthName = val.selectedValues[0] + '年' + val.selectedValues[1] + '月'
      forms.classDate =
        val.selectedValues[0] + '-' + val.selectedValues[1] + '-' + val.selectedValues[2]
      courseDetail.value.classDate =
        val.selectedValues[0] + '-' + val.selectedValues[1] + '-' + val.selectedValues[2]
      state.showPopoverTime = false
    }

    const checkCourseTimer = (val: any) => {
      forms.startTime =
        forms.classDate + ' ' + val.selectedValues[0] + ':' + val.selectedValues[1] + ':00'
      forms.endTime = dayjs(forms.startTime)
        .add(courseDetail.value.singleCourseTime, 'minute')
        .format('YYYY-MM-DD hh:mm:ss')

      courseDetail.value.startTime = forms.startTime
      state.showPopoverCourseTime = false
    }

    return () => (
      <>
        <div class={styles.courseWrap}>
          <OHeader isBack={true} border={false}></OHeader>
          <div class={styles.courseInfo}>
            <CellGroup inset border={false}>
              <Cell title="乐团名称" value={courseDetail.value.orchestraName} />
              <Cell title="课程类型" value={courseEmnu[courseDetail.value.type]} />
              <Cell
                title="课程开始日期"
                value={dayjs(courseDetail.value.classDate).format('YYYY-MM-DD')}
                is-link
                onClick={() => (state.showPopoverTime = true)}
              />
              <Cell
                title="课程开始时间"
                value={dayjs(courseDetail.value.startTime).format('hh:mm')}
                is-link
                onClick={() => {
                  state.showPopoverCourseTime = true
                }}
              />
              <Cell title="课程时长" value={courseDetail.value.singleCourseTime + '分钟'} />
              <Cell
                title="授课老师"
                value={courseDetail.value.teacherName}
                onClick={() => {
                  state.showPopoverTeacher = true
                }}
                is-link
              />
            </CellGroup>
          </div>
          <div class={styles.wall}></div>
          <div class={['btnGroup btnMore', styles.btnWrap]}>
            <Button color="#ccc" class={styles.unpassBtn} onClick={() => reset()}>
              取消
            </Button>
            <Button color="#FF8057" class={styles.unpassBtn} onClick={() => submit()}>
              确认调整
            </Button>
          </div>
          <Popup v-model:show={state.showPopoverTime} position="bottom" style="{ height: '30%' }">
            <DatePicker
              onCancel={() => {
                state.showPopoverTime = false
              }}
              onConfirm={checkTimer}
              v-model={state.currentDate}
              title="选择年月日"
              columnsType={columnsType.value}
            />
          </Popup>

          <Popup
            v-model:show={state.showPopoverCourseTime}
            position="bottom"
            style="{ height: '30%' }"
          >
            <TimePicker
              onCancel={() => {
                state.showPopoverCourseTime = false
              }}
              onConfirm={checkCourseTimer}
              v-model={state.currentCourseDate}
              title="选择开课时间"
              columnsType={columnsTypeTime.value}
            />
          </Popup>
          <ActionSheet
            style={{ height: '40%' }}
            close-on-click-action
            v-model:show={state.showPopoverTeacher}
            title="选择老师"
            actions={state.teachers}
            onSelect={checkTeacher}
          ></ActionSheet>
        </div>
      </>
    )
  }
})
