import Calendar from '@/business-components/calendar'
import request from '@/helpers/request'
import { state } from '@/state'
import Arrange from '@/teacher/live-class/create-components/arrange'
import dayjs from 'dayjs'
import {
  computed,
  defineComponent,
  nextTick,
  onMounted,
  reactive,
  ref,
  watch
} from 'vue'
import styles from './index.module.less'
import { params as classInfo } from '../class-info'
import { Button, Cell, Dialog, Popup, Sticky, Tag, Toast } from 'vant'
import { getWeekCh } from '@/helpers/utils'
import { useRouter } from 'vue-router'
import CourseSchedule from '../course-schedule'

export default defineComponent({
  name: 'createClass',
  props: {
    active: {
      type: Number,
      default: 1
    },
    onBack: {
      type: Function,
      default: () => () => {}
    }
  },
  setup(props) {
    watch(
      () => props.active,
      val => {
        // console.log(val)
        if (val === 2) {
          getList()
        }
      }
    )
    //日期设置
    const data = reactive({
      calendarList: {},
      selectList: []
    })
    const getList = async (date?: Date) => {
      const tempDate = date || dayjs().add(1, 'day').toDate()
      let params = {
        day: dayjs(tempDate).format('DD'),
        month: dayjs(tempDate).format('MM'),
        year: dayjs(tempDate).format('YYYY')
      }
      try {
        let res = await request.post(
          '/api-teacher/courseSchedule/createLiveCourseCalendar',
          {
            data: {
              ...params,
              singleCourseMinutes: classInfo.singleClassTime,
              freeCourseMinutes: classInfo.freeCourseMinutes,
              teacherId: state.user.data?.userId
            }
          }
        )
        const result = res.data || []
        let tempObj = {}
        result.forEach((item: any) => {
          tempObj[item.date] = item
        })
        data.calendarList = tempObj
      } catch {}
    }

    const onSelectDay = (res: any) => {
      // 对数组进行排序
      res.sort((first: any, second: any) => {
        if (first.startTime > second.startTime) return 1
        if (first.startTime < second.startTime) return -1
        return 0
      })
      data.selectList = res
    }
    const showSelectList = computed(() => {
      // 显示时间
      let list = [...data.selectList]
      list.forEach((item: any) => {
        item.title =
          dayjs(item.startTime).format('YYYY-MM-DD') +
          ' ' +
          getWeekCh(dayjs(item.startTime).day()) +
          ' ' +
          item.start +
          '~' +
          item.end
      })
      return list
    })
    const selectType = computed(() => {
      // 循环次数是否足够
      return data.selectList.length < classInfo.classNum ? 'noEnough' : 'enough'
    })
    const onCloseTag = (item: any) => {
      // 删除课程
      Dialog.confirm({
        title: '提示',
        message: '您是否要删除该选择的课程？',
        confirmButtonColor: 'var(--van-primary)'
      }).then(() => {
        const index = data.selectList.findIndex(
          (course: any) => course.startTime === item.startTime
        )
        data.selectList.splice(index, 1)
      })
    }

    const selectStatus = ref(false)
    const onSubmit = async () => {
      if (data.selectList.length <= 0) {
        Toast('请选择课程时间')
        return
      }

      if (data.selectList.length < classInfo.classNum) {
        selectStatus.value = true
        return
      }

      // await this._lookCourse()
      confirmShow.value = true
    }
    const onComfirm = async () => {
      if (selectType.value === 'noEnough') {
        let times = [] as any
        data.selectList.forEach((item: any) => {
          times.push({
            startTime: item.startTime,
            endTime: item.endTime
          })
        })
        console.log(data.selectList)
        const res = await request.post(
          '/api-teacher/courseGroup/lockCourseToCache',
          {
            data: {
              courseNum: classInfo.classNum,
              courseType: 'PIANO_ROOM_CLASS',
              loop: 1,
              teacherId: state.user.data?.userId,
              timeList: [...times]
            }
          }
        )
        if (res.code === 200) {
          res.data.forEach((n: any) => {
            n.start = dayjs(n.startTime).format('HH:mm')
            n.end = dayjs(n.endTime).format('HH:mm')
          })
          data.selectList = res.data
        }
      } else {
        selectStatus.value = false
        nextTick(() => {
          confirmShow.value = true
        })
      }
    }

    const router = useRouter()
    const confirmShow = ref(false)
    // 排课
    const onCourseSchedule = async () => {
      const timeList = data.selectList
      const n = classInfo.studentIds.length
      try {
        let { code, data } = await request.post(
          '/api-teacher/courseSchedule/arrangeCourse',
          {
            data: {
              classNum: classInfo.classNum, //课时数
              consumeTime: Math.ceil(
                n * classInfo.classNum * parseInt(classInfo.singleClassTime)
              ), //消耗时长
              courseName: classInfo.courseName, //课程名称
              singleClssTime: classInfo.singleClassTime, //单课时长
              studentIds: classInfo.studentIds.map(n => n.userId), //学员id集合
              subjectId: classInfo.subjectId, //声部id
              timeList
            }
          }
        )
        if (code === 200) {
          confirmShow.value = false

          setTimeout(() => {
            Toast({
              icon: 'success',
              message: '排课成功',
              duration: 1500,
              onClose: () => {
                router.back()
              }
            })
          }, 100)
        }
      } catch (error) {}
    }
    return () => {
      return (
        <div class={styles.createClass}>
          {props.active === 2 && (
            <Calendar
              maxDays={classInfo.classNum}
              list={data.calendarList}
              prevMonth={(date: Date) => getList(date)}
              nextMonth={(date: Date) => getList(date)}
              selectDay={onSelectDay}
              selectList={data.selectList}
              isSkipHolidays={classInfo.isSkipHolidays}
            />
          )}

          <Cell
            class={[styles.arrangeCell, 'mb12']}
            v-slots={{
              title: () => (
                <div class={styles.rTitle}>
                  <span>已选择课程时间</span>
                </div>
              ),
              label: () => (
                <div class={styles.rTag}>
                  {showSelectList.value.map((item: any) => (
                    <>
                      <Tag
                        plain
                        round
                        closeable
                        size="large"
                        type="primary"
                        class={styles.tag}
                        onClose={() => onCloseTag(item)}
                      >
                        {item.title}
                      </Tag>
                      <br />
                    </>
                  ))}
                </div>
              )
            }}
          ></Cell>

          <Sticky offsetBottom={0} position="bottom">
            <div class={['btnGroup', 'btnMore']}>
              <Button
                block
                round
                type="primary"
                plain
                onClick={() => {
                  props.onBack && props.onBack()
                  // 重置选择的课次
                  data.selectList = []
                }}
              >
                上一步
              </Button>
              <Button block round type="primary" onClick={() => onSubmit()}>
                下一步
              </Button>
            </div>
          </Sticky>
          {/* <Arrange /> */}
          <Popup show={selectStatus.value} class={styles.selectPopup}>
            <div class={styles.selectContainer}>
              <div class={styles.rTitle}>
                <span>提示</span>
              </div>
              <div class={styles.selectPopupContent}>
                <p class={styles.desc}>
                  {selectType.value === 'noEnough'
                    ? '您所选择的上课时间未达到您输入的课时数，系统根据已选时间将自动按周顺延排课。'
                    : '您已选择以下上课时间段，时间段会暂时锁定，锁定期间学员不可购买该时间段课程。'}
                </p>
                {selectType.value === 'enough' && (
                  <p class={styles.times}>
                    {data.selectList.map((item: any) => (
                      <span>
                        {dayjs(item.startTime || new Date()).format(
                          'YYYY-MM-DD'
                        )}{' '}
                        {dayjs(item.startTime || new Date()).format('HH:mm')}~
                        {dayjs(item.endTime || new Date()).format('HH:mm')}
                      </span>
                    ))}
                  </p>
                )}
              </div>

              <div class={styles.selectBtn}>
                <Button
                  class={styles.btn}
                  type="primary"
                  round
                  block
                  plain
                  onClick={() => (selectStatus.value = false)}
                >
                  {selectType.value === 'noEnough' ? '继续选择' : '重新选择'}
                </Button>
                <Button
                  class={styles.btn}
                  type="primary"
                  round
                  block
                  onClick={() => onComfirm()}
                >
                  确认
                </Button>
              </div>
            </div>
          </Popup>

          {/* 确认排课 */}
          <Popup
            position="bottom"
            class={styles.coursePopup}
            v-model:show={confirmShow.value}
            closeable
            round
          >
            <CourseSchedule
              curriculum={data.selectList}
              onClose={() => {
                confirmShow.value = false
              }}
              onComfirm={() => {
                onCourseSchedule()
              }}
            />
          </Popup>
        </div>
      )
    }
  }
})
