import OPopup from '@/components/o-popup'
import OSticky from '@/components/o-sticky'
import request from '@/helpers/request'
import { state } from '@/state'
import dayjs from 'dayjs'
import {
  Button,
  Cell,
  CellGroup,
  Dialog,
  Field,
  Icon,
  Picker,
  Popup,
  Radio,
  RadioGroup,
  showToast,
  Sticky,
  Tag
} from 'vant'
import { defineComponent, onMounted, reactive } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { weekdays, weekFormat } from '../../create'
import Calendar from '../../modal/calendar'
import ClassList from '../../modal/class-list'
import Timer from '../../modal/timer'
import styles from './index.module.less'
import { forms } from '../../create'

// orchestra

export default defineComponent({
  name: 'standard',
  props: {
    address: {
      type: String,
      default: ''
    }
  },
  setup(props) {
    const route = useRoute()
    const router = useRouter()
    // const forms = reactive({
    //   status: false,
    //   weekStatus: false,
    //   calendarStatus: false,
    //   classStatus: false,
    //   timerStatus: false,
    //   skipHoliday: 1,
    //   week: null,
    //   times: 16,
    //   classList: [] as any, // 没有设置伴学指导的数据
    //   calendarList: [] as any,
    //   calendarDate: null as any,
    //   trainStartDate: null, // 开始日期
    //   trainStartTime: null, // 开始时间
    //   timerList: {} as any, // 可选和不可选时间段
    //   numberStatus: false,
    //   numberDialogStatus: false, // 提示暂无训练次数提示
    //   pickerNum: 16, // 默认16次
    //   timerPickerList: [] as any // 可排课次数
    // })

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

    // 查询没有设置指导老师的班级
    const getClasses = async (show = true) => {
      try {
        const { data } = await request.post('/api-school/classGroup/page', {
          data: {
            page: 1,
            rows: 200,
            schoolId: state.user.data.school.id,
            hasTeacher: false,
            orchestraType: 'DELIVERY'
          }
        })
        // 班级数据
        forms.classList = data.rows || []
        // 判断没有设置伴学指导的班级
        if (forms.classList.length > 0 && show) {
          forms.status = true
        }
      } catch {
        //
      }
    }

    // 获取已排课次数
    const getStandardCourseNum = async () => {
      try {
        const { data } = await request.get(
          '/api-school/orchestra/semesterStandardCourseNum/' + state.user.data.school.id
        )
        const tempPicker = Number(forms.pickerNum - data)
        forms.times = tempPicker
        for (let i = 0; i < tempPicker; i++) {
          forms.timerPickerList.push({
            text: i + 1 + '次',
            value: i + 1
          })
        }

        if (tempPicker <= 0) {
          forms.numberDialogStatus = true
        }
      } catch {
        //
      }
    }

    // 下一步
    const onSubmit = () => {
      // 判断是否有训练次数
      if (forms.times <= 0) {
        forms.numberDialogStatus = true
        return
      }

      // 判断是否有班级没有设置伴学指导
      if (forms.classList.length > 0) {
        forms.status = true
        return
      }

      if (!forms.trainStartDate) {
        showToast('请选择训练开始日期')
        return
      }

      if (!forms.trainStartTime) {
        showToast('请选择训练开始时间')
        return
      }

      if (!forms.week) {
        showToast('请选择周次')
        return
      }

      if (!props.address) {
        showToast('您所在的学校暂未设置地址')
        return
      }

      router.push('/train-content')
    }

    onMounted(() => {
      getList(forms.calendarDate || new Date())
      getClasses()
      getStandardCourseNum()
    })

    return () => (
      <div class={styles.standard}>
        <div class={styles.tips}>
          <Icon name="warning" class={styles.icon} />
          标准训练可对交付团进行整学期标准训练排课
        </div>

        <CellGroup inset class={styles.cellGroup}>
          <Field
            label="训练开始日期"
            placeholder="请选择训练开始日期"
            isLink
            readonly
            inputAlign="right"
            onClick={() => (forms.calendarStatus = true)}
            modelValue={
              forms.trainStartDate ? dayjs(forms.trainStartDate).format('YYYY年MM月DD日') : ''
            }
          />
          <Field
            label="训练开始时间"
            isLink
            readonly
            placeholder="请选择训练开始日期"
            inputAlign="right"
            modelValue={forms.trainStartTime ? dayjs(forms.trainStartTime).format('HH:mm') : ''}
            onClick={() => {
              if (!forms.trainStartDate) {
                showToast('请选择训练开始日期')
                return
              }
              forms.timerStatus = true
            }}
          />
          <Cell title="训练时长" value={forms.trainTimer + '分钟'}></Cell>
          <Field
            label="训练周次"
            placeholder="请选择训练周次"
            modelValue={weekFormat(forms.week)}
            inputAlign="right"
            readonly
          />
          <Cell
            title="训练次数"
            isLink={forms.times <= 0 ? false : true}
            value={forms.times + '次'}
            onClick={() => {
              if (forms.times <= 0) return
              forms.numberStatus = true
            }}
          ></Cell>
          <Cell title="跳过节假日">
            {{
              value: () => (
                <RadioGroup
                  checked-color="#FF8057"
                  v-model={forms.skipHoliday}
                  direction="horizontal"
                  onChange={() => {
                    forms.trainStartDate = null
                    forms.trainStartTime = null
                    forms.calendarDate = null
                    // 初始化日历时间
                    getList()
                  }}
                >
                  <Tag
                    size="large"
                    type="primary"
                    plain={!(forms.skipHoliday === 1)}
                    color="#FF8057"
                    class={styles.radioSection}
                    round
                  >
                    <Radio class={styles.radioItem} name={1}></Radio>是
                  </Tag>
                  <Tag
                    size="large"
                    type="primary"
                    plain={!(forms.skipHoliday === 0)}
                    color="#FF8057"
                    class={styles.radioSection}
                    round
                  >
                    <Radio class={styles.radioItem} name={0}></Radio>否
                  </Tag>
                </RadioGroup>
              )
            }}
          </Cell>
        </CellGroup>

        <OSticky position="bottom">
          <div class={'btnGroup'} style={{ marginTop: '24px' }}>
            <Button type="primary" block round onClick={onSubmit}>
              下一步
            </Button>
          </div>
        </OSticky>

        <Popup v-model:show={forms.weekStatus} position="bottom" round>
          <Picker
            columns={weekdays}
            onCancel={() => (forms.weekStatus = false)}
            onConfirm={(val: any) => {
              forms.week = val.selectedValues[0]
              forms.weekStatus = false
            }}
          />
        </Popup>

        {/* 选择训练开始日期 */}
        <OPopup v-model:modelValue={forms.calendarStatus} position="bottom" destroy>
          <Calendar
            list={forms.calendarList}
            nextMonth={(date: Date) => getList(date)}
            prevMonth={(date: Date) => getList(date)}
            onSelect={(date: any) => {
              forms.calendarStatus = false

              forms.trainStartDate = date
              forms.trainStartTime = null

              const days = dayjs(date).day()
              const selectDays = weekdays[days === 0 ? 6 : days - 1]
              forms.week = selectDays.value

              forms.calendarList.forEach((item: any) => {
                if (dayjs(item.calendarDate).isSame(date)) {
                  forms.timerList = { ...item }
                  setTimeout(() => {
                    forms.timerStatus = true
                  }, 100)
                }
              })
            }}
            onDestory={() => {
              if (forms.trainStartDate) {
                getList(forms.trainStartDate)
              } else {
                getList()
              }
            }}
            v-model:calendarDate={forms.calendarDate}
          />
        </OPopup>

        {/* 选择开始时间 */}
        <OPopup
          v-model:modelValue={forms.timerStatus}
          position="bottom"
          style={{ background: '#F6F6F6' }}
          destroy
        >
          <Timer
            timerList={forms.timerList}
            times={forms.trainTimer}
            onClose={() => (forms.timerStatus = false)}
            onConfirm={(val: any) => {
              forms.trainStartTime = val
            }}
          />
        </OPopup>

        <Popup v-model:show={forms.numberStatus} position="bottom" round>
          <Picker
            columns={forms.timerPickerList}
            onClick={() => (forms.numberStatus = false)}
            onConfirm={(val: any) => {
              const selectedValue = val.selectedValues[0]
              forms.times = selectedValue
            }}
          />
        </Popup>

        <Dialog
          v-model:show={forms.status}
          message={`您有${forms.classList.length}个班级尚未指定伴学指导，请完成指定后再进行训练规划。`}
          messageAlign="left"
          confirmButtonText="去设置"
          cancelButtonText="暂不设置"
          showCancelButton
          onConfirm={() => {
            forms.classStatus = true
          }}
        >
          {{
            title: () => (
              <div class={styles.dialogTitle}>
                <i></i>
                指定伴学指导
              </div>
            )
          }}
        </Dialog>

        <Dialog
          v-model:show={forms.numberDialogStatus}
          message={`暂无可训练次数`}
          messageAlign="center"
          confirmButtonText="确定"
        >
          {{
            title: () => (
              <div class={styles.dialogTitle}>
                <i></i>
                训练次数
              </div>
            )
          }}
        </Dialog>

        <OPopup
          v-model:modelValue={forms.classStatus}
          position="bottom"
          style={{ background: '#F6F6F6' }}
          destroy
        >
          <ClassList
            classList={forms.classList}
            onClose={() => (forms.classStatus = false)}
            onConfirm={() => {
              getClasses(false)
            }}
          />
        </OPopup>
      </div>
    )
  }
})
