<!--  -->
<template>
  <div>
    <el-button type="primary" style="margin-bottom: 12px;" @click="onAdjustment">批量调整</el-button>
    <div class="tableWrap">
      <el-table style="width: 100%" :header-cell-style="{ background: '#EDEEF0', color: '#444' }" :data="tableList"
        @selection-change="handleSelectionChange">
        <el-table-column type="selection" :selectable="isDisabled" width="55"></el-table-column>
        <el-table-column align="center" label="课程编号">
          <template slot-scope="scope">
            <div>{{ scope.row.id || '' }}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="课程名称">
          <template slot-scope="scope">
            <div>{{ scope.row.name }}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" label="课程状态">
          <template slot-scope="scope">
            <div>{{ scope.row.status | coursesStatus }}</div>
          </template>
        </el-table-column>
        <el-table-column align="center" prop="classDate" label="上课日期">
          <template slot-scope="scope">
            {{ scope.row.classDate | dayjsFormat }}
            {{ scope.row.startClassTime | dayjsFormat('HH:mm') }}~{{ scope.row.endClassTime | dayjsFormat('HH:mm') }}
          </template>
        </el-table-column>
        <!-- <el-table-column align="center" prop="startClassTime" label="开始时间"></el-table-column>
        <el-table-column align="center" prop="endClassTime" label="结束时间"></el-table-column> -->
        <el-table-column label="操作" width="180" align="center">
          <template slot-scope="scope">
            <div>
              <el-button type="text" v-if="scope.row.id &&
                !scope.row.isSettlement &&
                $helpers.permission(
                  'courseSchedule/classStartDateAdjust/liveReset'
                )
                " @click="resetClass(scope.row)">调整</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog :title="adjustmentName" width="800px" :visible.sync="adjustmentVisible">
      <el-form :model="adjustmentForm" label-position="right" label-width="120px" ref="adjustmentForm"
        :rules="adjustmentRules" :inline="true">
        <el-form-item label="已选择课时数">
          <el-input disabled v-model.trim="adjustmentForm.count"></el-input>
        </el-form-item>

        <!-- <el-form-item label="课程类型" prop="courseType">
          <el-select clearable v-model.trim="adjustmentForm.courseType" disabled>
            <el-option label="线上课" value="ONLINE"></el-option>
            <el-option label="线下课" value="OFFLINE"></el-option>
          </el-select>
        </el-form-item> -->
        <!-- <el-form-item label="教学地点" v-if="adjustmentForm.courseType == 'OFFLINE'">
          <el-select v-model.trim="adjustmentForm.address" filterable clearable>
            <el-option v-for="(item, index) in schoolList" :key="index" :value="item.id" :label="item.name"></el-option>
          </el-select>
        </el-form-item> -->
        <br />
        <el-form-item label="排课起始时间" prop="courseTime">
          <el-date-picker v-model.trim="adjustmentForm.courseTime" :picker-options="pickerOptions()"
            style="width:200px!important;" type="date" value-format="yyyy-MM-dd" placeholder="选择日期"></el-date-picker>
          <el-checkbox style="margin-left:10px;" v-model.trim="adjustmentForm.checked">是否跳过节假日</el-checkbox>
        </el-form-item>
      </el-form>
      <div class="WeekWrap">
        <h3 style="margin-bottom:20px;">
          循环次数
          <el-button type="text" style="margin-left:10px;" @click="addWeek">添加</el-button>
        </h3>
        <div class="countWrap" style="margin-bottom:10px;">
          <div class="countItem" style="margin-bottom:20px;" v-for="(item, index) in weekList" :key="index">
            <span>循环周期:</span>
            <el-select v-model.trim="item.dayOfWeek" filterable clearable>
              <el-option v-for="(item, index) in weekDateList" :key="index" :label="item.label"
                :value="item.value"></el-option>
            </el-select>
            <span style="margin-left:10px;">开始时间</span>
            <el-time-picker style="margin-left:10px;" placeholder v-model.trim="item.startClassTime" @change="val => {
              changeStartTimes(val, item);
            }" format="HH:mm" value-format="HH:mm" :picker-options="{
  selectableRange: '06:00:00 - 21:00:00'
}"></el-time-picker>
            <span style="margin-left:10px;">结束时间</span>
            <el-time-picker style="margin-left:10px;" placeholder v-model.trim="item.endClassTime" format="HH:mm"
              value-format="HH:mm" disabled :picker-options="{
                selectableRange: '06:00:00 - 21:00:00'
              }"></el-time-picker>
            <el-button style="margin-left:10px;" type="danger" :disabled="index < 1" @click="removeWeek(item)"
              icon="el-icon-delete" circle></el-button>
          </div>
        </div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="adjustmentVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitAdjustment">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="课程调整" width="400px" :before-close="handleClose" :visible.sync="courseVisible">
      <el-form :model="maskForm" class="maskForm" ref="maskForm" :rules="maskRules" label-position="right"
        label-width="80px" :inline="true">
        <el-form-item label="上课日期" prop="date">
          <el-date-picker v-model.trim="maskForm.date" type="date" :picker-options="coursesDate()"
            value-format="yyyy-MM-dd" placeholder="选择日期"></el-date-picker>
        </el-form-item>
        <el-form-item label="开始时间" prop="startTime">
          <el-time-picker placeholder="起始时间" v-model.trim="startTime" @change="changeStartTime" format="HH:mm"
            value-format="HH:mm" :picker-options="{
              selectableRange: `${nowTime} - 23:30:00`
            }"></el-time-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-time-picker placeholder="结束时间" format="HH:mm" value-format="HH:mm" v-model="maskForm.endTime" disabled>
          </el-time-picker>
        </el-form-item>
        <!--v-if="maskForm.teachMode=='OFFLINE'"-->
        <!-- <el-form-item label="课程类型" prop="courseType">
            <el-select clearable v-model.trim="maskForm.teachMode">
              <el-option label="线上课" value="ONLINE"></el-option>
              <el-option label="线下课" value="OFFLINE"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="教学地点" v-if="maskForm.teachMode == 'OFFLINE'">
            <el-select v-model.trim="maskForm.address" filterable clearable>
              <el-option v-for="(item, index) in schoolList" :key="index" :value="item.id" :label="item.name"></el-option>
            </el-select>
          </el-form-item> -->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="courseVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitResetClass">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { resetCourse } from "@/api/buildTeam";
import { vipCourseAdjust } from "@/api/vipSeting";
import { liveCourseList } from '../../api'
import { diffTimerFormMinute, addTimerFormMinute } from "@/utils/date";
import dayjs from 'dayjs';
export default {
  data() {
    return {
      id: this.$route.query.id,
      adjustmentName: "",
      tableList: [],
      rules: {
        // 分页规则
        limit: 10, // 限制显示条数
        page: 1, // 当前页
        total: 0, // 总条数
        page_size: [10, 20, 40, 50] // 选择限制显示条数
      },
      chioseVipList: [],
      activeList: [],
      adjustmentVisible: false,
      adjustmentForm: {
        count: "",
        courseTime: "",
        checked: false,
        addCount: "",
        courseType: "ONLINE",
        fee: "",
        address: ""
      },
      adjustmentRules: {
        courseTime: [{ required: true, message: "请选择开始时间" }],
        addCount: [{ required: true, message: "请输入加课次数" }],
        courseType: [{ required: true, message: "请选择课程类型" }],
        fee: [{ required: true, message: "请输入费用" }],
        address: [{ required: true, message: "请选择教学地点" }]
      },
      weekDateList: [
        { value: "1", label: "星期一" },
        { value: "2", label: "星期二" },
        { value: "3", label: "星期三" },
        { value: "4", label: "星期四" },
        { value: "5", label: "星期五" },
        { value: "6", label: "星期六" },
        { value: "7", label: "星期日" }
      ],
      weekList: [
        {
          dayOfWeek: "",
          startTime: "",
          endTime: "",
          moid: new Date().getTime()
        }
      ],
      courseVisible: false,
      maskForm: {
        date: "",
        startTime: "",
        endTime: "",
        id: "",
        address: "",
        teachMode: ""
      },
      maskRules: {
        date: [{ required: true, message: "请选择上课时间", trigger: "blur" }]
      },
      startTime: "",
    };
  },
  mounted() {
    this.getList();
  },
  methods: {
    async getList() {
      try {
        const { data } = await liveCourseList({
          liveGroupId: this.id,
          rows: this.rules.limit,
          page: this.rules.page,
        })
        this.tableList = data.list;
        // this.rules.total = data.pageInfo.total;
        this.courseTime = data.singleClassMinutes;

      } catch {
      }
    },
    isDisabled(row, index) {
      if (row.isSettlement || !row.id) {
        return false;
      } else {
        return true;
      }
    },
    addWeek() {
      // 添加循环周期
      this.weekList.push({
        dayOfWeek: "",
        startClassTime: "",
        endClassTime: "",
        id: new Date()
      });
    },
    // 删除循环周
    removeWeek(item) {
      for (let i in this.weekList) {
        if (this.weekList[i].id == item.id) {
          this.weekList.splice(i, 1);
        }
      }
    },
    handleSelectionChange(val) {
      this.chioseVipList = val;
      this.adjustmentForm.count = val.length;
      this.activeList = val;
    },
    onAdjustment() {
      this.adjustmentName = "批量调整";
      if (this.adjustmentForm.count <= 0) {
        this.$message.error("请至少勾选一节课");
      } else {
        this.adjustmentVisible = true;
      }
    },
    coursesDate(dateStr) {
      let self = this;
      return {
        firstDayOfWeek: 1,
        disabledDate: time => {
          return time.getTime() + 86400000 <= new Date().getTime();
        }
      };
    },
    pickerOptions(dateStr) {
      return {
        firstDayOfWeek: 1,
        disabledDate(time) {
          return time.getTime() + 86400000 <= new Date().getTime();
        }
      };
    },
    resetClass(row) {
      /**
       * maskForm.startTime
       */
      this.maskForm.date = row.classDate.split(" ")[0];
      this.startTime = row.startClassTimeStr.substring(0, 5);
      this.maskForm.endTime = row.endClassTimeStr.substring(0, 5);
      // this.maskForm.endTime = row.endClassTimeStr;
      this.maskForm.id = row.id;
      this.maskForm.address = row.schoolId || null;
      this.maskForm.teachMode = row.teachMode;
      // 修改课时
      this.courseVisible = true;
    },
    handleClose() {
      this.courseVisible = false;
      this.startTime = "";
      this.maskForm = {
        date: "",
        startTime: "",
        endTime: "",
        id: "",
        address: "",
        teachMode: ""
      };
      this.$refs["maskForm"].resetFields();
    },
    submitResetClass() {
      //   endClassTimeStr: this.maskForm.endTime,
      if (!this.startTime) {
        this.$message.error("请填写修改时间");
        return;
      }
      let classTime = this.maskForm.date
        ? new Date(this.maskForm.date)
        : new Date();
      let ymd =
        classTime.getFullYear() +
        "-" +
        (classTime.getMonth() + 1) +
        "-" +
        classTime.getDate();
      let tempStartTime = this.startTime;
      if (this.startTime.length <= 5) {
        tempStartTime = tempStartTime + ":00";
      }
      let obj = {
        startClassTime: ymd + " " + this.startTime,
        // startClassTimeStr: this.startTime,
        id: this.maskForm.id,
        classDate: this.maskForm.date,
        schoolId: this.maskForm.address || null,
        teachMode: this.maskForm.teachMode || null,
        groupType: "LIVE"
      };
      resetCourse(obj).then(res => {
        if (res.code == 200) {
          this.$message.success("修改成功");
          this.courseVisible = false;
          this.getList();
        } //else {
        //   this.$message.error(res.msg)
        // }
      });
    },
    submitAdjustment() {
      this.$refs["adjustmentForm"].validate(item => {
        if (item) {
          let week = this.weekList;
          if (!week[0] || !week[0].startClassTime || !week[0].dayOfWeek) {
            this.$message.error("至少排一节课");
            return;
          }
          // 开始
          let obj = {};
          obj.courseCreateStartTime = this.adjustmentForm.courseTime;
          let idArr = this.activeList.map(item => {
            return item.id;
          });

          let courseScheduleIds = idArr.join(",");
          obj.courseScheduleIds = courseScheduleIds;
          obj.courseTimes = this.weekList;
          obj.holiday = this.adjustmentForm.checked;
          obj.teachMode = this.adjustmentForm.courseType || null;
          obj.groupType = "LIVE";
          obj.vipGroupId = this.id;
          obj.schoolId = this.adjustmentForm.address || null;
          vipCourseAdjust(obj).then(res => {
            if (res.code == 200) {
              this.$message.success("恭喜您修改成功");
              this.adjustmentVisible = false;
              this.getList();
            }
          });
        }
      });
    },
    changeStartTime(val) {
      this.$nextTick(res => {
        if (val) {
          this.$set(
            this.maskForm,
            "endTime",
            addTimerFormMinute(this.maskForm.date, val, this.courseTime)
          );
        } else {
          this.$set(this.maskForm, "endTime", "");
        }
        if (!this.maskForm.endTime) {
          this.$set(this, "startTime", "");
        }
      });
    },
    changeStartTimes(val, item) {
      this.$nextTick(res => {
        if (val) {
          let str = dayjs(new Date()).format("YYYY-MM-DD");
          this.$set(
            item,
            "endClassTime",
            addTimerFormMinute(str, val, this.courseTime)
          );
        } else {
          this.$set(item, "endClassTime", "");
        }
        if (!item.endClassTime) {
          console.log(item.startClassTime);
          this.$set(item, "startClassTime", "");
        }
      });
    },
  },
  computed: {
    nowTime() {
      // console.log(that.maskForm.date)
      let str = "06:00:00";
      if (this.maskForm.date == dayjs(new Date()).format("YYYY-MM-DD")) {
        str = dayjs(new Date()).format("HH:mm:ss");
      }

      return str;
    }
  },
  filters: {
    formatterTime(val) {
      let result;
      if (val) {
        result = val.split(" ")[0];
      } else {
        result = "";
      }
      return result;
    },
    formatterStatus(val) {
      let arr = [
        "未开始",
        "报名中",
        "进行中",
        "取消",
        "已结束",
        "报名结束",
        "暂停"
      ];
      return arr[val];
    }
  }
};
</script>
<style lang="scss" scoped>
::v-deep .el-dropdown-link {
  cursor: pointer;
  color: var(--color-primary);
}

::v-deep .el-icon-arrow-down {
  font-size: 12px;
}

.vipwrap {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;

  .newBand {
    margin-right: 20px;
  }
}

.resetClassForm {

  ::v-deep .el-date-editor.el-input,
  ::v-deep .el-date-editor.el-input__inner {
    width: 180px !important;
  }
}

.countWrap {

  ::v-deep .el-date-editor.el-input,
  ::v-deep .el-date-editor.el-input__inner {
    width: 100px !important;
  }
}

.maskForm {
  ::v-deep .el-input {
    width: 220px !important;
  }
}

.titlewrap {
  display: flex;
  flex-direction: row;
  justify-content: flex-start;
  align-items: center;
}
</style>
