<template>
  <div>
    <!-- <el-form-item
      label="跳过节假日"
      :prop="'classs.' + type + '.holiday'"
      :rules="[{ required: true, message: '否跳过节假日' }]"
    >
      <el-radio-group v-model="form.holiday">
        <el-radio :label="true">是</el-radio>
        <el-radio :label="false">否</el-radio>
      </el-radio-group>
    </el-form-item> -->

    <el-table v-if="form && form.cycle&&form.cycle.length>0" :data="form.cycle" :show-header="false">
      <el-table-column>
        <template slot-scope="scope">
          <div>
            <el-form-item
              :prop="
                'classs.' + type + '.cycle.' + scope.$index + '.coreTeacher'
              "
              label-width="88px"
              :rules="[{ required: true, message: '请选择主教老师' }]"
            >
              <el-select
                v-model.trim="scope.row.coreTeacher"
                placeholder="请选择主教老师"
                clearable
                filterable
              >

                <el-option
                  v-for="(item, index) in teacherList"
                  :key="index"
                  :label="item.realName"
                  :value="String(item.id)"
                >
                  <span style="float: left">{{ item.realName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{
                    String(item.id)
                  }}</span>
                </el-option>
              </el-select>

            </el-form-item>
            <el-form-item
              prop="assistant"
              v-if="
                activeType != 'HIGH' &&
                activeType != 'HIGH_ONLINE' &&
                activeType != 'MUSIC_NETWORK' &&
                type != 'HIGH' &&
                type != 'HIGH_ONLINE' &&
                type != 'MUSIC_NETWORK'
              "
            >

              <el-select
                v-model.trim="scope.row.assistant"
                placeholder="请选择助教老师"
                filterable
                clearable
                multiple
                collapse-tags
              >
                <el-option
                  v-for="(item, index) in cooperationList"
                  :key="index"
                  :label="item.realName"
                  :value="item.id"
                >
                  <span style="float: left">{{ item.realName }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{
                    String(item.id)
                  }}</span>
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              :prop="'classs.' + type + '.cycle.' + scope.$index + '.time'"
              :rules="[{ required: true, message: '请选择课程时长' }]"
              inline-message
            >
              <el-select
                v-model.trim="scope.row.time"
                style="width: 180px !important"
                placeholder="请选择课程时长"
                clearable
                :disabled="!!selectPrice"
                @change="
                  (val) => {
                    startTimeChange(scope, val);
                  }
                "
                filterable
              >
                <el-option
                  v-for="(item, index) in pricesArray"
                  :key="index"
                  :disabled="
                    surplustime + (parseFloat(scope.row.time) || 0) < item
                  "
                  :label="item"
                  :value="item"
                >
                </el-option>
              </el-select>

            </el-form-item>
            <el-form-item
              :prop="
                'classs.' + type + '.cycle.' + scope.$index + '.expectCourseNum'
              "
              :rules="[
                { required: true, message: '请输入预计课时数' },
                { pattern: /^\+?[1-9]\d*$/, message: '请输入大于0的正整数' },
                { validator: validateNum },
              ]"
              inline-message
            >

              <el-input
                style="width: 180px !important"
                type="number"
                v-model.trim="scope.row.expectCourseNum"
                placeholder="请输入预计课数"
                @input="
                  (val) => {
                    getUseTime(scope.row);
                  }
                "
              >
              </el-input>
            </el-form-item>
            <el-form-item
              inline-message
              :rules="[{ required: true, message: '请选择循环周期' }]"
              :prop="'classs.' + type + '.cycle.' + scope.$index + '.dayOfWeek'"
            >
              <el-select
                v-model.trim="scope.row.dayOfWeek"
                style="width: 180px !important"
                placeholder="请选择循环周期"
                clearable
                filterable
                @change="
                  (val) => {
                    getUseTime(scope.row);
                  }
                "
              >
                <el-option
                  v-for="(item, index) in weekDateList"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              :prop="
                'classs.' + type + '.cycle.' + scope.$index + '.startClassTime'
              "
              :rules="[{ required: true, message: '请选择开始时间' }]"
              inline-message
            >
              <el-time-picker
                style="width: 180px !important"
                v-model.trim="scope.row.startClassTime"
                format="HH:mm"
                value-format="HH:mm"
                placeholder="请选择开始时间"
                @change="timeChange(scope.row)"
                :picker-options="{
                  selectableRange: ['04:30:00 - 23:59:59'],
                }"
              >

              </el-time-picker>
            </el-form-item>
            <el-form-item
              :prop="
                'classs.' + type + '.cycle.' + scope.$index + '.endClassTime'
              "
              inline-message
            >
              <el-time-picker
                style="width: 180px !important"
                v-model.trim="scope.row.endClassTime"
                format="HH:mm"
                disabled
                value-format="HH:mm"
                placeholder="请选择结束时间"
                :picker-options="{
                  selectableRange: [
                    scope.row.startClassTime + ':00 - 23:59:59',
                  ],
                }"
              >
              </el-time-picker>
            </el-form-item>
            <el-form-item
              :prop="'classs.' + type + '.cycle.' + scope.$index + '.holiday'"
              :rules="[{ required: true, message: '请选择是否跳过节假日' }]"
              inline-message
            >
              <el-select
                v-model.trim="scope.row.holiday"
                style="width: 180px !important"
                placeholder="是否跳过节假日"
                filterable
                @change="holidayChange(scope.row)"
              >
                <el-option label="是" :value="true"></el-option>
                <el-option label="否" :value="false"> </el-option>
              </el-select>
            </el-form-item>
            <el-form-item
              inline-message
              :prop="'classs.' + type + '.cycle.' + scope.$index + '.startDate'"
              :rules="[{ required: true, message: '请选择排课起始日期' }]"
            >
              <el-date-picker
                v-model.trim="scope.row.startDate"
                :picker-options="pickerOptions"
                style="width: 180px !important"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="排课起始日期"
                @change="
                  (val) => {
                    changeStartDate(val, scope.row);
                  }
                "
              >
              </el-date-picker>
            </el-form-item>
            <el-form-item
              inline-message
              :prop="'classs.' + type + '.cycle.' + scope.$index + '.endDate'"
              :rules="[
                { required: true, message: '请选择排课结束日期' },
                { required: true, trigger: 'change', validator: validatePass },
              ]"
            >
              <el-date-picker
                v-model.trim="scope.row.endDate"
                :disabled="true"
                :picker-options="pickerOptions"
                style="width: 180px !important"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="排课结束日期"
              >
              </el-date-picker>
            </el-form-item>

            <i
              @click="remove(scope.$index, scope)"
              v-if="form.cycle.length > 1"
              class="close-icon el-icon-circle-close"
            ></i>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <el-button
      icon="el-icon-circle-plus-outline"
      type="info"

      plain
      :disabled="surplustime < (selectPrice || 0 || Math.min(...pricesArray))"
      @click="create"
      style="margin-top: 10px; width: 100%"
      >添加循环</el-button
    >
  </div>
</template>
<script>
import { diffTimerFormMinute, addTimerFormMinute } from "@/utils/date";
import { classTimeList } from "@/utils/searchArray";
import dayjs from "dayjs";

const classTimeListByType = {};
for (const item of classTimeList) {
   classTimeListByType[item.value] = item.label;

}

export default {
  props: [
    "form",
    "type",
    "surplustime",
    "prices",
    "selectPrice",
    "holidays",
    "teacherList",
    "activeType",
    "cooperationList",
    "coreid",
    "assistant",
    "endSchoolTerm",
    "startCourseDate",
  ],
  data() {
    const validatePass = (rule, value, callback) => {
      // console.log(this.endSchoolTerm, "结束", value);
      let timer = dayjs(this.endSchoolTerm).valueOf() - dayjs(value).valueOf();
      if (this.endSchoolTerm && timer < 0) {
        callback(new Error(`结束时间不能超过${this.endSchoolTerm}`));
      } else {
        callback();
      }
    };

    const validateNum = (rule, value, callback) => {
      // validUsername
      if (this.surplustime < 0) {
        callback(new Error("排课时长超过规则限制"));
      } else {
        callback();
      }
    };
    return {
      classTimeListByType,
      useTime: 0,
      validatePass,
      validateNum,
      pickerOptions: this.getPickerOptions(),
    };
  },
  mounted() {

    this.updateUseTime()
  },
  computed: {
    weekDateList() {
      return [
        { value: "1", label: "星期一" },
        { value: "2", label: "星期二" },
        { value: "3", label: "星期三" },
        { value: "4", label: "星期四" },
        { value: "5", label: "星期五" },
        { value: "6", label: "星期六" },
        { value: "7", label: "星期日" },
      ];
    },
    pricesArray() {
      return (this.prices[this.type] || "").split(",").filter((item) => !!item);
    },
  },
  methods: {
    updateUseTime() {
      let time = 0;
      for (const item of this.form.cycle) {
        time += (item.time || 0) * (item.expectCourseNum || 0);
      }
      this.useTime = time;
      this.$emit("setUserTime", time, this.type);
    },
    create() {
      if (this.endSchoolTerm) {
        if (this.surplustime <= 0) {
          this.$message.error("已排课时长使用完毕,请修改预计课时数");
          return;
        }
      } else {
        if (this.surplustime <= this.useTime) {
          this.$message.error("已排课时长使用完毕,请修改预计课时数");
          return;
        }
      }

      const initVal = { coreTeacher: this.coreid, assistant: this.assistant };
      if (this.selectPrice) {
        initVal.time = this.selectPrice;
      }
      this.form.cycle.push(initVal);
      this.updateUseTime();
    },

    remove(index) {
      this.form.cycle.splice(index, 1);
      this.updateUseTime();
    },
    startTimeChange(item, val) {
      this.getUseTime(item.row);
      if (item.row.time && item.row.startClassTime) {
        let str = dayjs(new Date()).format("YYYY-MM-DD");
        this.$set(
          item.row,
          "endClassTime",
          addTimerFormMinute(str, item.row.startClassTime, item.row.time)
        );
      } else {
        this.$set(item.row, "endClassTime", "");
      }
      if (val) {
        let activeTime = val * Math.max(item.row.expectCourseNum || 0, 0);
        if (this.endSchoolTerm) {
          this.$set(
            item.row,
            "expectCourseNum",
            parseInt((this.surplustime + activeTime) / val)
          );
        } else {
          this.$set(
            item.row,
            "expectCourseNum",
            parseInt((this.surplustime - this.useTime + activeTime) / val)
          );
        }

        // this.surplusTime
      } else {
        this.$set(item.row, "expectCourseNum", 0);
      }
      this.getUseTime(item.row);
    },
    timeChange(item) {
      if (item.time && item.startClassTime) {
        let str = dayjs(new Date()).format("YYYY-MM-DD");
        this.$set(
          item,
          "endClassTime",
          addTimerFormMinute(str, item.startClassTime, item.time)
        );
      } else {
        this.$set(item, "endClassTime", "");
      }
      this.updateUseTime();
    },
    holidayChange(row) {
      this.updateEndTime(row);
    },
    getUseTime(row) {
      this.updateEndTime(row);
      this.useTime = 0;
      this.form.cycle.forEach((item) => {
        this.useTime +=
          (item.expectCourseNum ? parseInt(item.expectCourseNum) : 0) *
          parseInt(item.time);
      });

      this.updateUseTime();
      //  this.$emit('setUserTime', this.useTime, this.type)
    },
    addData(startDate, dayOfWeek) {
      let num;
      let dayjs = this.$helpers.dayjs;
      let date = dayjs(startDate).toDate();
      dayOfWeek - date.getDay() >= 0
        ? (num = dayOfWeek - date.getDay())
        : (num = dayOfWeek - date.getDay() + 7);
      return num;
    },
    updateEndTime(row) {
      if (row.dayOfWeek && row.startDate && typeof row.holiday === "boolean") {
        // const num = this.addData(row.startDate, row.dayOfWeek)
        // const week = dayjs(row.startDate).get('day') == 0 ? 7 : dayjs(row.startDate).get('day')
        const selectWeek = row.dayOfWeek == 7 ? 0 : row.dayOfWeek;
        let exp = Math.max(row.expectCourseNum, 0);
        let end = dayjs(row.startDate);
        // console.log(selectWeek, end.get('day'))
        if (row.holiday) {
          // exp >0 还有未排的课
          while (exp > 0) {
            if (
              selectWeek == end.get("day") &&
              !this.holidays.includes(end.format("YYYY-MM-DD"))
            ) {
              exp--;
            }
            end = end.add(1, "day");
            if (exp === 0) {
              end = end.subtract(1, "day");
            }
          }
        } else {
          while (exp > 0) {
            if (selectWeek == end.get("day")) {
              exp--;
            }
            end = end.add(1, "day");
            if (exp === 0) {
              end = end.subtract(1, "day");
            }
          }
        }
        const enumd = this.addData(end.format("YYYY-MM-DD"), row.dayOfWeek);
        console.log(enumd);
        // end = end.add(enumd, 'day')
        this.$set(row, "endDate", end.format("YYYY-MM-DD"));
      } else {
        this.$set(row, "endDate", "");
      }

      // if (row.dayOfWeek && row.startDate && typeof row.holiday === 'boolean') {
      //     // const num = this.addData(row.startDate, row.dayOfWeek)
      //     const week = dayjs(row.startDate).get('day') == 0 ? 7 : dayjs(row.startDate).get('day')
      //     const selectWeek = row.dayOfWeek
      //     const exp = Math.max(row.expectCourseNum - (selectWeek >= week ? 1 : 0), 0)
      //     let end = dayjs(row.startDate).add((exp*7), 'day')
      //     if (row.holiday) {
      //       for (const d of this.holidays) {
      //         if (dayjs(d).isBetween(row.startDate, end.format('YYYY-MM-DD'), null, '[]') && row.dayOfWeek - 1 == dayjs(d).get('day')) {
      //           end = end.add(7, 'day')
      //         }
      //       }
      //     }
      //     const enumd = this.addData(end.format('YYYY-MM-DD'), row.dayOfWeek)
      //     end = end.add(enumd, 'day')
      //     this.$set(
      //     row,
      //     "endDate",
      //     end.format('YYYY-MM-DD')
      //   );
      // } else {
      //   this.$set(
      //     row,
      //     "endDate",
      //     ''
      //   );
      // }
    },
    changeStartDate(val, row) {
      this.updateEndTime(row);
      this.updateUseTime();
    },
    getPickerOptions() {
      let that = this;
      return {
        firstDayOfWeek: 1,
        disabledDate(time) {
          if (that.startCourseDate) {
            // 对比时间
            let startTime = dayjs(that.startCourseDate).valueOf();
            let nowDate = new Date().getTime();
            let minTime;
            startTime - nowDate > 0
              ? (minTime = startTime)
              : (minTime = nowDate);

            let maxTime = dayjs(that.endSchoolTerm).valueOf();
            return (
              time.getTime() + 86400000 <= minTime ||
              maxTime <= time.getTime() - 86400000
            );
          } else {
            return time.getTime() + 86400000 <= new Date().getTime();
          }
        },
      };
    },
  },
};
</script>
<style lang="less" scoped>
::v-deep  .close-icon {
  cursor: pointer;
  font-size: 16px;
  margin-bottom: 24px;
  line-height: 40px;
}
</style>
