import Calendar from '@/business-components/calendar'
import request from '@/helpers/request'
import { Button, Cell, Dialog, Popup, Sticky, Tag, Toast } from 'vant'
import { defineComponent } from 'vue'
import styles from './arrange.module.less'
import dayjs from 'dayjs'
import { createState } from './createState'
import { state } from '@/state'
import { getWeekCh } from '@/helpers/utils'

export default defineComponent({
  name: 'arrange',
  data() {
    return {
      selectStatus: false,

      calendarList: {}
    }
  },
  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-teacher/courseSchedule/createLiveCourseCalendar',
          {
            data: {
              ...params,
              singleCourseMinutes: createState.live.singleCourseMinutes,
              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]
      result.forEach((item: any) => {
        const isExist = list.some(
          (course: any) => course.startTime === item.startTime
        )
        !isExist && list.push({ ...item })
      })
      // 对数组进行排序
      list.sort((first: any, second: any) => {
        if (first.startTime > second.startTime) return 1
        if (first.startTime < second.startTime) return -1
        return 0
      })
      createState.selectCourseList = [...list]
    },
    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-teacher/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 {}
    },
    async _unLookCourse() {
      try {
        await request.get('/api-teacher/courseGroup/unlockCourseToCache', {
          params: {
            teacherId: state.user.data?.userId
          }
        })
        this.selectStatus = false
        createState.live.coursePlanList.forEach((item: any) => {
          item.startTime = ''
          item.endTime = ''
        })
      } catch {}
    },
    async onReset() {
      if (this.selectType === 'noEnough') {
        this.selectStatus = false
      } else if (this.selectType === 'enough') {
        await this._unLookCourse()
      }
      createState.coursePlanStatus = false
    },
    async onSure() {
      await this._lookCourse(() => {
        this.selectStatus = false
        createState.active = 4
      })
    }
  },
  render() {
    return (
      <div class={styles.arrange}>
        <Calendar
          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}
        />

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

        <Sticky offsetBottom={0} position="bottom">
          <div class={['btnGroup', 'btnMore']}>
            <Button
              block
              round
              type="primary"
              plain
              onClick={() => {
                createState.active = 2
              }}
            >
              上一步
            </Button>
            <Button block round type="primary" onClick={this.onSubmit}>
              下一步
            </Button>
          </div>
        </Sticky>

        <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'
                  ? '您所选择的上课时间未达到您输入的课时数，系统根据已选时间将自动按周顺延排课。'
                  : '您已选择以下上课时间，请确认后点击确认按'}
              </p>
              {createState.live.coursePlanList &&
                createState.live.coursePlanList.length > 0 &&
                this.selectType === 'enough' && (
                  <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>
    )
  }
})
