import request from '@/helpers/request'
import { Button, Popup, Tag, Toast } from 'vant'
import { defineComponent } from 'vue'
import styles from './index.module.less'
import dayjs from 'dayjs'
import { createState } from '../createState'
import { state } from '@/state'
import { getWeekCh } from '@/helpers/utils'
import ColCalendar from '@/components/col-calendar'
import { ElButton, ElDialog, ElMessageBox, ElTag } from 'element-plus'

export default defineComponent({
  name: 'arrange',
  data() {
    return {
      selectStatus: false,
      calendarList: {},
      calendarDate: new Date() as Date // 日历当前时间
    }
  },
  computed: {
    showSelectList() {
      let list = [...createState.selectCourseList]
      list.forEach((item: any) => {
        item.title =
          dayjs(item.startTime).format('YYYY-MM-DD') +
          ' ' +
          getWeekCh(dayjs(item.startTime).day()) +
          ' ' +
          item.start +
          '~' +
          item.end
      })
      return list
    },
    selectType() {
      // 循环次数是否足够
      return createState.selectCourseList.length < createState.live.courseNum
        ? 'noEnough'
        : 'enough'
    }
  },
  async mounted() {
    const initDate = dayjs().add(1, 'day').toDate()
    await this.getList(initDate)

    if (createState.coursePlanStatus) {
      this.selectStatus = true
    }
  },
  methods: {
    async getList(date?: Date) {
      let params = {
        day: dayjs(date || new Date()).format('DD'),
        month: dayjs(date || new Date()).format('MM'),
        year: dayjs(date || new Date()).format('YYYY')
      }
      try {
        let res = await request.post(
          '/api-website/courseSchedule/createLiveCourseCalendar',
          {
            data: {
              ...params,
              singleCourseMinutes: createState.live.singleMins,
              freeCourseMinutes: createState.live.freeMinutes,
              teacherId: state.user.data?.userId
            }
          }
        )
        const result = res.data || []
        let tempObj = {}
        result.forEach((item: any) => {
          tempObj[item.date] = item
        })
        this.calendarList = tempObj
      } catch {}
    },
    onSelectDay(obj: any) {
      const result = obj || []
      let list = [...createState.selectCourseList]
      console.log(obj, list)
      result.forEach((item: any) => {
        const isExist = list.some(
          (course: any) => course.startTime === item.startTime
        )
        !isExist && list.push({ ...item })
      })
      // 去掉不在
      let tempList: any[] = []
      list.forEach((item: any) => {
        const isExist = result.some(
          (course: any) => course.startTime === item.startTime
        )
        // const index = result.findIndex(
        //   (course: any) => course.startTime === item.startTime
        // )
        // !isExist && list.splice(index, 1)
        isExist && tempList.push(item)
      })
      // 对数组进行排序
      tempList.sort((first: any, second: any) => {
        if (first.startTime > second.startTime) return 1
        if (first.startTime < second.startTime) return -1
        return 0
      })
      createState.selectCourseList = [...tempList]
    },
    onCloseTag(item: any) {
      Dialog.confirm({
        title: '提示',
        message: '您是否要删除该选择的课程？',
        confirmButtonColor: 'var(--van-primary)'
      }).then(() => {
        const index = createState.selectCourseList.findIndex(
          (course: any) => course.startTime === item.startTime
        )
        createState.selectCourseList.splice(index, 1)
      })
    },
    async onSubmit() {
      if (createState.selectCourseList.length <= 0) {
        Toast('请选择课程时间')
        return
      }

      if (createState.selectCourseList.length < createState.live.courseNum) {
        this.selectStatus = true
        return
      }

      await this._lookCourse()
    },
    async _lookCourse(callBack?: Function) {
      try {
        let times = [] as any
        createState.selectCourseList.forEach((item: any) => {
          times.push({
            startTime: item.startTime,
            endTime: item.endTime
          })
        })
        const res = await request.post(
          '/api-website/courseGroup/lockCourseToCache',
          {
            data: {
              courseNum: createState.live.courseNum,
              courseType: 'LIVE',
              loop: this.selectType === 'noEnough' ? 1 : 0,
              teacherId: state.user.data?.userId,
              timeList: [...times]
            }
          }
        )
        const result = res.data || []
        result.forEach((item: any, index: number) => {
          createState.live.coursePlanList[index] = {
            ...createState.live.coursePlanList[index],
            startTime: item.startTime,
            endTime: item.endTime,
            classNum: index + 1
          }
        })
        createState.coursePlanStatus = true
        this.selectStatus = true
        callBack && callBack()
      } catch (e: any) {
        // 报错时需要重置日历表的数据
        const message = e.message
        Dialog.alert({
          title: '提示',
          confirmButtonColor: 'var(--van-primary)',
          message
        }).then(() => {
          this.getList(this.calendarDate || new Date())
          createState.selectCourseList = []
          this.selectStatus = false
        })
      }
    },
    async _unLookCourse() {
      try {
        await request.get('/api-website/courseGroup/unlockCourseToCache', {
          params: {
            teacherId: state.user.data?.userId
          }
        })
        this.selectStatus = false
        setTimeout(() => {
          createState.live.coursePlanList.forEach((item: any) => {
            item.startTime = ''
            item.endTime = ''
          })
        }, 500)
      } catch {}
    },
    async onReset() {
      // 是否有锁课状态 或 是锁课类型的
      if (createState.coursePlanStatus || this.selectType === 'enough') {
        await this._unLookCourse()
      } else if (this.selectType === 'noEnough') {
        this.selectStatus = false
      }
      // 只能重置课程时间
      createState.live.coursePlanList.forEach((item: any) => {
        item.startTime = ''
        item.endTime = ''
      })

      setTimeout(() => {
        createState.coursePlanStatus = false
      }, 500)
    },
    async onSure() {
      // 判断是否有锁课状态 或 是锁课类型的 并且已经有课的
      console.log(
        this.selectType,
        createState.coursePlanStatus,
        createState.live.coursePlanList
      )
      let courseLength = 0
      createState.live.coursePlanList.forEach((item: any) => {
        item.startTime && courseLength++
      })
      if (this.selectType === 'enough' || courseLength > 0) {
        this.selectStatus = false
        createState.active = 4
        return
      }
      const status = createState.coursePlanStatus
      await this._lookCourse(() => {
        if (status) {
          this.selectStatus = false
          createState.active = 4
        }
      })
    }
  },
  render() {
    return (
      <div class={[styles.arrange]}>
        <div class="px-[235px] pt-7">
          <div class="border-dashed border-[#EDEDED] border-2 rounded-lg px-8 pt-4 pb-6">
            <ColCalendar
              selectList={createState.selectCourseList}
              list={this.calendarList}
              maxDays={createState.live.courseNum || 0}
              nextMonth={(date: Date) => this.getList(date)}
              prevMonth={(date: Date) => this.getList(date)}
              selectDay={this.onSelectDay}
              v-model:calendarDate={this.calendarDate}
            />
          </div>

          <div class={[styles.arrangeCell, '!my-4']}>
            <div class={styles.rTitle}>
              <span>已选择课程时间</span>
            </div>

            <div class={styles.rTag}>
              {this.showSelectList.map((item: any) => (
                <>
                  <ElTag
                    round
                    size="large"
                    effect="light"
                    class={['mb-2 !border-[#2DC7AA] !color-[#2DC7AA]']}
                    closable
                    onClose={() => this.onCloseTag(item)}
                  >
                    {item.title}
                  </ElTag>
                  <br />
                </>
              ))}
            </div>
          </div>
        </div>

        <div class="border-t border-t-[#E5E5E5] text-center pt-6 pb-7">
          <ElButton
            class="!w-40 !h-[38px]"
            onClick={() => {
              createState.active = 2
              // 重置选择的课次
              createState.selectCourseList = []
            }}
          >
            上一步
          </ElButton>
          <ElButton
            type="primary"
            class="!w-40 !h-[38px]"
            onClick={this.onSubmit}
          >
            下一步
          </ElButton>
        </div>

        <ElDialog
          modelValue={this.selectStatus}
          onUpdate:modelValue={e => (this.selectStatus = e)}
          width={'400px'}
          title="提示"
        >
          <div class={styles.selectContainer}>
            <div class={styles.selectPopupContent}>
              <p class={styles.desc}>
                {this.selectType === 'noEnough' && !createState.coursePlanStatus
                  ? '您所选择的上课时间未达到您输入的课时数，系统根据已选时间将自动按周顺延排课。'
                  : '您已选择以下上课时间段，时间段会暂时锁定，锁定期间学员不可购买该时间段课程。'}
              </p>
              {createState.live.coursePlanList &&
                createState.live.coursePlanList.length > 0 &&
                createState.coursePlanStatus && (
                  <p class={styles.times}>
                    {createState.live.coursePlanList.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}>
              <ElButton
                type="primary"
                round
                plain
                class="!w-40 !h-[38px]"
                onClick={this.onReset}
              >
                {this.selectType === 'noEnough' ? '继续选择' : '重新选择'}
              </ElButton>
              <ElButton
                type="primary"
                round
                class="!w-40 !h-[38px]"
                onClick={this.onSure}
              >
                确认
              </ElButton>
            </div>
          </div>
        </ElDialog>
        {/* <Popup show={this.selectStatus} class={styles.selectPopup}>
          <div class={styles.selectContainer}>
            <div class={styles.rTitle}>
              <span>提示</span>
            </div>
            <div class={styles.selectPopupContent}>
              <p class={styles.desc}>
                {this.selectType === 'noEnough' && !createState.coursePlanStatus
                  ? '您所选择的上课时间未达到您输入的课时数，系统根据已选时间将自动按周顺延排课。'
                  : '您已选择以下上课时间段，时间段会暂时锁定，锁定期间学员不可购买该时间段课程。'}
              </p>
              {createState.live.coursePlanList &&
                createState.live.coursePlanList.length > 0 &&
                createState.coursePlanStatus && (
                  <p class={styles.times}>
                    {createState.live.coursePlanList.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={this.onReset}
              >
                {this.selectType === 'noEnough' ? '继续选择' : '重新选择'}
              </Button>
              <Button
                class={styles.btn}
                type="primary"
                round
                block
                onClick={this.onSure}
              >
                确认
              </Button>
            </div>
          </div>
        </Popup> */}
      </div>
    )
  }
})
