<template>
  <el-dialog :title="title" :visible.sync="open" width="700px">
    <el-form ref="form"
             v-loading="loadingChange"
             class="add-form auto-width"
             :model="form"
             :rules="rules"
             :validate-on-rule-change="false"
             label-width="120px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="校区:" prop="deptId">
            <dept-select v-model="form.deptId" :disabled="!canChangeCourse" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="课程:" prop="courseId">
            <div class="input-with-color-picker-container">
              <course-select
                v-model="form.courseId"
                :dept-id="form.deptId"
                :disabled="!canChangeCourse"
                clearable
                mounted-load-all
                style="width: 80%"
              />
              <el-tooltip class="item" effect="dark" content="选择颜色,便于课表中区分" placement="right">
                <el-color-picker  v-model="form.claColor" :predefine="colorArray" />
              </el-tooltip>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="12" style="text-align: left">
          <el-form-item label="规则类型:">
            <el-radio-group v-model="form.ruleType" @change="handleRuleTypeChange">
              <el-radio
                v-for="dict in ruleTypeOptions"
                :key="dict.dictValue"
                :label="dict.dictValue"
              >{{ dict.dictLabel }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="课表字体大小:" prop="fontSize">
            <div class="input-with-color-picker-container">
              <el-select
                v-model="form.fontSize"
                filterable
                clearable
                style="width: 160px"
                size="small"
              >
                <el-option
                  v-for="item in fontSizeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
              <el-tooltip class="item" effect="dark" content="选择颜色,便于课表中区分" placement="right">
                <el-color-picker  v-model="form.fontColor" :predefine="colorArray" />
              </el-tooltip>
            </div>
          </el-form-item>
        </el-col>
        <div v-if="form.ruleType === '1'">
          <el-col :span="12">
            <el-form-item label="开始日期:" prop="beginDate">
              <el-date-picker
                v-model="form.beginDate"
                clearable
                size="small"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择开始日期"
                :picker-options="beginDatePickerOptions"
                @change="beginDateChange"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束日期:" prop="endDate">
              <el-date-picker
                v-model="form.endDate"
                clearable
                size="small"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="选择结束日期"
                :picker-options="endDatePickerOptions"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24" style="text-align: left">
            <el-form-item label="重复方式:">
              <el-radio-group v-model="form.repeatType">
                <el-radio
                  v-for="dict in repeatTypeOptions"
                  :key="dict.dictValue"
                  :label="dict.dictValue"
                >{{ dict.dictLabel }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <el-col v-if="form.repeatType !== '2'" :span="24" style="text-align: left">
            <el-form-item label="上课星期:" prop="weekDays">
              <el-checkbox v-model="checkAllWeekDay" :indeterminate="isIndeterminate" @change="handleCheckAllChange">全选</el-checkbox>
              <el-checkbox-group v-model="form.weekDays" @change="handleCheckedChange">
                <el-checkbox v-for="dict in weekDayOptions" :key="dict.dictValue" :label="dict.dictValue" name="weekDays">{{ dict.dictLabel }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>

        </div>
        <div v-if="form.ruleType !== '1'">
          <el-col :span="24" style="text-align: left">
            <el-form-item label="上课日期:" prop="chooseDate">
              <el-date-picker
                v-model="form.chooseDate"
                clearable
                size="small"
                type="dates"
                value-format="yyyy-MM-dd"
                placeholder="选择开始日期"
              />
            </el-form-item>
          </el-col>
        </div>
        <el-col :span="12">
          <el-form-item label="上课时间:" prop="startTime">
            <el-time-select
              v-model="form.startTime"
              size="small"
              :picker-options="{
                start: '00:00',
                step: '00:01',
                end: '23:59'
              }"
              @change="startTimeChange"
              placeholder="选择上课时间"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="时长（分钟）:" prop="claDuration">
            <el-input-number v-model="form.claDuration" @change="startTimeChange" controls-position="right" :min="0" placeholder="请输入时长" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="下课时间:" prop="endTime">
            <el-time-select
              v-model="form.endTime"
              size="small"
              :disabled="true"
              placeholder="选择下课时间"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="任课教练:" prop="teacherId">
            <staff-select v-model="form.teacherId" :dept-id="form.deptId"  placeholder="请选择上课教练" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最多预约人数:" prop="atClassCnt">
            <el-input-number v-model="form.atClassCnt" controls-position="right"  placeholder="请输入人数" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="最少开课人数:" prop="lessCnt">
            <el-input-number v-model="form.lessCnt" controls-position="right" :min="0" placeholder="请输入人数" />
          </el-form-item>
        </el-col>

        <el-col :span="12">
          <el-form-item label="教室:" prop="roomId">
            <room-select v-model="form.roomId" :dept-id="form.deptId" placeholder="请选择教练" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="上课主题:" prop="classTheme">
            <el-input v-model="form.classTheme" size="small" placeholder="请输入上课主题" />
          </el-form-item>
        </el-col>
      </el-row>
      <span style="color: #999; font-size: 12px;">{{form.ruleId?'* 说明：本操作会同时修改未上课且无会员预约/预约失败/取消预约的相关课表信息，已经上完的课程不会被修改；':''}}</span>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button :loading="loadingChange" type="primary" @click="submitForm">确 定</el-button>
      <el-button @click="cancel">取 消</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { selectDictLabel } from '@/utils/commonUtils'
import claSelect from '@/components/sc/course/cla/claSelect'
import courseSelect from '@/components/sc/course/courseSelect'
import deptSelect from '@/components/system/dept/deptSelect'
import staffSelect from '@/components/system/staff/staffSelect'
import roomSelect from '@/components/sc/base/roomSelect'
import moment from 'moment'
import { addRule, getRule, updateRule } from '@/api/school/sc/cla/claTimeRule'
let that
export default {
  components: {
    courseSelect,
    deptSelect,
    staffSelect,
    roomSelect
  },
  props: {
    colorArray: {
      type: Array,
      default: function() {
        return ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C']
      }
    }
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      loadingChange: false,
      title: '排课',
      // 是否显示弹出层
      open: false,
      // 规则类型数据字典
      ruleTypeOptions: [],
      // 重复方式数据字典
      repeatTypeOptions: [],
      // 上课星期数据字典
      weekDayOptions: [],
      // 字体大小数据字典
      fontSizeList:[
        {
        label: '12px',
        value: 12
        },
        {
          label: '13px',
          value: 13
        },
        {
          label: '14px',
          value: 14
        },
        {
          label: '15px',
          value: 15
        },
      ],
      // 表单参数
      form: {
        atClassCnt:20,
        claColor:'#409EFF',
        fontColor:'#000000',
        fontSize:12
      },
      isIndeterminate: true,
      checkAllWeekDay: false,
      beginDatePickerOptions: {
        disabledDate(time) {
          return moment(time).add(1, 'days').valueOf() < Date.now()
        }
      },
      endDatePickerOptions: {
        disabledDate(time) {
          return time.valueOf() < moment(that.form.beginDate).valueOf()
        }
      },
      canChangeCourse: true
    }
  },
  computed: {
    rules() {
      const tempRules = {
        deptId: [
          { required: true, message: '请选择校区', trigger: 'change' }
        ],
        courseId: [
          { required: true, message: '课程不能为空', trigger: 'change' }
        ],
        ruleType: [
          { required: true, message: '规则类型不能为空', trigger: 'blur' }
        ],
        repeatType: [
          { required: true, message: '重复方式不能为空', trigger: 'blur' }
        ],
        weekDays: [
          { required: true, message: '上课星期不能为空', trigger: 'change' }
        ],
        startTime: [
          { required: true, message: '上课时间不能为空', trigger: 'change' },
          {
            pattern: /^([01]?[0-9]|2[0-3]):([0-5][0-9])$/,
            message: "时间格式应为HH:mm",
            trigger: "change"
          }
        ],
        // endTime: [
        //   { required: true, message: '下课时间不能为空', trigger: 'blur' },
        //   {
        //     pattern: /^([01]?[0-9]|2[0-3]):([0-5][0-9])$/,
        //     message: "时间格式应为HH:mm",
        //     trigger: "blur"
        //   }
        // ],
        teacherId: [
          { required: true, message: '任课教练不能为空', trigger: 'change' }
        ],
        claDuration: [
          {
            pattern: /^[1-9]\d*$/,
            message: '请输入正整数',
            trigger:  ['blur','change']
          }
        ],
        atClassCnt: [
          { required: true, message: '最多预约人数不能为空', trigger: ['blur','change'] }
        ],
      }
      if (this.form.ruleType === '1') {
        tempRules['beginDate'] = [
          { required: true, message: '开始日期不能为空', trigger: 'change' }
        ]
        tempRules['endDate'] = [
          { required: true, message: '结束日期不能为空', trigger: 'change' }
        ]
      } else if (this.form.ruleType === '2') {
        tempRules['chooseDate'] = [
          { required: true, message: '请选择上课日期', trigger: 'change' }
        ]
      }
      return tempRules
    }
  },
  watch: {
    'form.ruleType': {
      handler(newValue, oldValue) {
        if (newValue === '1') {
          // 重复
          this.form.repeatType = '1'
          this.form.filterHoliday = false
        } else {
          // 单次
          this.form.repeatType = undefined
          this.form.beginDate = undefined
          this.form.endDate = undefined
          this.form.filterHoliday = false
        }
      }
    },
    'form.repeatType': {
      handler(newValue, oldValue) {
        if (newValue === '2') {
          // 隔日重复
          this.form.weekDays = []
        }
      }
    }
  },
  created() {
    this.getDictListByDictType('cla_time_rule_type').then(response => {
      this.ruleTypeOptions = response.data
    })
    this.getDictListByDictType('cla_time_repeat_type').then(response => {
      this.repeatTypeOptions = response.data
    })
    this.getDictListByDictType('week_day').then(response => {
      this.weekDayOptions = response.data
    })
    that = this
  },
  methods: {
    // 重复方式
    repeatTypeFormat(row, column) {
      return selectDictLabel(this.repeatTypeOptions, row.repeatType)
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()

    },
    // 表单重置
    reset() {
      this.form = {
        deptId: undefined,
        courseId: undefined,
        ruleType: '1',
        beginDate: undefined,
        endDate: undefined,
        repeatType: '1',
        weekDays: [],
        filterHoliday: false,
        startTime: '',
        endTime: '',
        teacherId: undefined,
        classTheme: undefined,
        chooseDate: undefined,
        roomId: '',
        lessCnt:0,
        atClassCnt:20,
        claDuration:0,
        claColor: '#409EFF',
        fontColor:'#000000',
        fontSize:12

      }
      this.resetForm('form')

      this.canChangeCourse = true
    },
    loadInfo(id) {
      this.loadingChange = true
      this.reset()
      getRule(id).then(response => {

        this.loadingChange = false
        const date = response.data
        date.weekDays = date.weekDay?.split(',')
        if (date.startTime !== undefined && date.startTime.length > 5) {
          date.startTime = date.startTime.substr(0, 5)
        }
        if (date.endTime !== undefined && date.endTime.length > 5) {
          date.endTime = date.endTime.substr(0, 5)
        }
        if (date.onceDate) {
          date.chooseDate = date.onceDate.split(',')
        }
        this.form = date

        console.log(this.form)
        this.open = true

      }).catch(() => {
        this.loadingChange = false
      })

    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.loadingChange = true
          this.form.weekDay = this.form.weekDays?.toString()
          this.form.onceDate = this.form.chooseDate?.toString()
          if (this.form.ruleId) {
            updateRule(this.form).then(response => {
              this.loadingChange = false
              if (response.respCode === '0000') {
                this.msgSuccess('修改成功')
                this.open = false
                this.$emit('success')
              } else {
                this.msgError(response.respMsg)
              }
            }).catch(() => {
              this.loadingChange = false
            })
          } else {
            addRule(this.form).then(response => {
              this.loadingChange = false
              if (response.respCode === '0000') {
                this.msgSuccess('新增成功')
                this.open = false
                this.$emit('success')
              } else {
                this.msgError(response.respMsg)
              }
            }).catch(() => {
              this.loadingChange = false
            })
          }
        }
      })
    },
    beginDateChange(value) {
      if (moment(value).valueOf() > moment(this.form.endDate).valueOf()) {
        this.form.endDate = undefined
      }
    },
    // 开始时间变化时更新结束时间
    startTimeChange() {
      this.form.endTime = this.calculateEndTime(this.form.startTime, this.form.claDuration);
    },
    handleCheckAllChange(val) {
      this.form.weekDays = val ? this.weekDayOptions.map(item => {
        return item.dictValue
      }) : []
      this.isIndeterminate = false
    },
    handleCheckedChange(value) {
      const checkedCount = value.length
      if (checkedCount<1){
        this.checkAllWeekDay =false;
        this.isIndeterminate =true;
        return;
      }
      this.checkAllWeekDay = checkedCount === this.weekDayOptions.length
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.weekDayOptions.length
    },
    // 规则类型变更
    handleRuleTypeChange(ruleType) {
      if (ruleType === '2') {
        // 单次排课
      } else if (ruleType === '1') {
        // 重复排课
      }
    },
    /**
     * 计算结束时间（时长单位：分钟）
     * @param {String} startTime - 开始时间（HH:mm）
     * @param {Number} duration - 时长（分钟）
     * @returns {String} 计算后的结束时间
     */
    calculateEndTime(startTime, duration) {
      if (!startTime || !duration) return '';

      // 拆分开始时间为小时和分钟
      const [startHour, startMinute] = startTime.split(':').map(Number);

      // 计算总分钟数
      const totalStartMinutes = startHour * 60 + startMinute;
      // 总结束分钟数（直接使用分钟数相加）
      let totalEndMinutes = totalStartMinutes + duration;

      // 处理超过24小时的情况（取模）
      totalEndMinutes = totalEndMinutes % (24 * 60);

      // 计算结束小时和分钟
      const endHour = Math.floor(totalEndMinutes / 60);
      const endMinute = totalEndMinutes % 60;

      // 补零并格式化为 HH:mm
      return `${endHour.toString().padStart(2, '0')}:${endMinute.toString().padStart(2, '0')}`;
    },
  }
}
</script>
