<template>
  <el-dialog
    class="adddeviceDialog"
    :title="title"
    :visible.sync="isShow"
    :close-on-click-modal="false"
    width="670px"
  >
    <el-form
      label-position="left"
      ref="formInfo"
      label-width="auto"
      :rules="rules"
      :model="ruleForm"
    >
      <el-form-item label="名称" prop="name">
        <el-input v-model="ruleForm.name" autocomplete="off"></el-input>
      </el-form-item>
      <div class="addtimeBox" ref="timescrollref">
        <div
          class="timeBoxArr"
          v-for="(item, index) in ruleForm.listTime"
          :key="index"
        >
          <el-form-item
            label="时间"
            :rules="{ required: true, message: '请选择时间', trigger: 'blur' }"
          >
            <!-- <el-time-picker
              is-range
              :picker-options="pickerOptions"
              v-model="item.time"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="HH:mm"
              @change="handleTimeChange"
            >
            </el-time-picker> -->
            <div class="timeBoxList">
              <el-time-picker
                v-model="item.startTime"
                placeholder="开始时间"
                format="HH:mm"
              >
              </el-time-picker>
              <i class="split">~</i>
              <el-time-picker
                v-model="item.endTime"
                placeholder="结束时间"
                format="HH:mm"
              >
              </el-time-picker>
            </div>
          </el-form-item>
          <el-form-item
            class="spanRight"
            label="间隔（分）"
            :prop="'listTime.' + index + '.timeSpan'"
          >
            <!-- <el-input v-model="ruleForm.span" autocomplete="off" type="number"></el-input> -->
            <el-input-number v-model="item.timeSpan" :min="1"></el-input-number>
          </el-form-item>
          <div class="btngrop">
            <el-button
              v-if="index !== 0"
              type="danger"
              icon="el-icon-minus"
              @click="deleteModule(item, index)"
            ></el-button>
            <el-button
              icon="el-icon-plus"
              type="primary"
              @click="addModule()"
              v-if="index + 1 == ruleForm.listTime.length"
            ></el-button>
          </div>
        </div>
      </div>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="ruleForm.remark" autocomplete="off"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="isShow = false">取 消</el-button>
      <el-button type="primary" @click="submitForm()">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { addScheduleRulel, updateScheduleRulel } from "@/utils/api/index";
export default {
  props: {
    title: String,
  },
  data() {
    return {
      isShow: false,
      pickerOptions: {
        disabledDate(time) {
          // 取消开始对时间的限制
          return false;
        },
      },
      rules: {
        name: [{ required: true, message: "请输入名称", trigger: "blur" }],
      },
      ruleForm: {},
    };
  },
  methods: {
    //判断
    getdataform(val) {
      console.log(val);
      if (val == null) {
        return (this.ruleForm = {
          name: "",
          listTime: [
            {
              startTime: "",
              endTime: "",
              timeSpan: "",
            },
          ],
          list: [],
          remark: "",
        });
      }
      //this.ruleForm = val;
      this.ruleForm = JSON.parse(JSON.stringify(val));
      console.log(this.ruleForm.listTime);
      this.ruleForm.listTime.forEach((item) => {
        this.$set(item, "startTime", this.$moment(item.startTime, "HH:mm"));
        this.$set(item, "endTime", this.$moment(item.endTime, "HH:mm"));
        //this.$set(item, "time", [item.startTime, item.endTime]);
      });
    },
    handleTimeChange(value) {
      console.log(value);
      // this.item.time = value;
      // // 当开始时间改变时，重新设置pickerOptions使得结束时间可以大于开始时间
      // this.pickerOptions.disabledDate = (time) => {
      //   return time.getTime() < this.item.time[0].getTime();
      // };
    },
    addModule() {
      //新增一行
      this.ruleForm.listTime.push({
        startTime: "",
        endTime: "",
        timeSpan: "",
      });
      console.log(this.$refs.timescrollref);
      this.$nextTick(() => {
        console.log(this.$refs.timescrollref);
        if (this.$refs.timescrollref) {
          console.log(this.$refs.timescrollref.scrollHeight);
          this.$refs.timescrollref.scrollTop =
            this.$refs.timescrollref.scrollHeight;
        }
      });
    },
    //删除一行
    deleteModule(item, index) {
      console.log(item, index);
      const itemList = this.ruleForm.list.indexOf(item);
      if (itemList !== -1) {
        this.ruleForm.list.splice(index, 1);
      }
    },
    // 保存确定操作
    submitForm() {
      this.$refs.formInfo.validate((valid) => {
        if (valid) {
          // delete this.ruleForm.time;
          this.ruleForm.listTime.forEach((val) => {
            console.log(val);
            this.$set(val, "startTime", new Date(val.startTime));
            this.$set(val, "endTime", new Date(val.endTime));
            // console.log(val.time[0]);
            // console.log(typeof val.time[0]);
            // console.log(new Date(val.time[0]));
            // console.log(new Date(val.time[1]));
            // console.log(new Date(val.time[0]).getHours());
            // console.log(new Date(val.time[0]).getMinutes());
          });
          let arr = [];
          for (var i = 0; i < this.ruleForm.listTime.length; i++) {
            console.log(this.ruleForm.listTime);
            console.log(this.ruleForm.listTime[i].startTime);
            arr.push(
              {
                hour: Math.floor(this.ruleForm.listTime[i].timeSpan / 60),
                minute: this.ruleForm.listTime[i].timeSpan % 60,
                preset: 255,
              },
              {
                hour: this.ruleForm.listTime[i].startTime.getHours(),
                minute: this.ruleForm.listTime[i].startTime.getMinutes(),
                preset: 255,
              },
              {
                hour: this.ruleForm.listTime[i].endTime.getHours(),
                minute: this.ruleForm.listTime[i].endTime.getMinutes(),
                preset: 255,
              }
            );
          }
          console.log(arr);
          this.ruleForm.list = arr;
          if (this.title == "新增") {
            addScheduleRulel(this.ruleForm)
              .then((res) => {
                this.isShow = false;
                this.$message({
                  duration: 1500,
                  showClose: true,
                  message: "添加成功",
                  type: "success",
                });
                this.$parent.getruleList();
              })
              .catch((err) => {
                this.$message({
                  duration: 1500,
                  showClose: true,
                  message: "添加失败",
                  type: "error",
                });
              });
          } else {
            updateScheduleRulel(this.ruleForm)
              .then((res) => {
                this.isShow = false;
                this.$message.success("修改成功");
                this.$parent.getruleList();
              })
              .catch((err) => {
                this.$message.error("修改失败");
              });
          }
        } else {
          return false;
        }
      });
    },
    display() {
      this.isShow = true;
    },
    hide() {
      this.isShow = false;
    },
    // handleclose() {
    //   this.$parent.getruleList();
    // },
  },
  mounted() {},
};
</script>
<style lang="less">
.adddeviceDialog {
  .el-form {
    .addtimeBox {
      max-height: 205px;
      overflow: auto;
    }
    .timeBoxArr {
      display: flex;
      .el-date-editor.el-input,
      .el-date-editor.el-input__inner {
        width: 226px;
        margin-right: 16px;
      }

      .btngrop {
        margin-bottom: 16px;
        margin-left: 16px;
        height: 32px;
        .el-button--small {
          padding: 9px 8px;
          width: 30px;
        }
      }
      .timeBoxList {
        display: flex;
        .el-date-editor.el-input,
        .el-date-editor.el-input__inner {
          width: 100px;
          margin-right: 0px;
        }
        .split {
          padding: 0 4px;
        }
      }
      .spanRight {
        margin-left: 14px;
      }
    }
  }
}
.el-time-spinner__item.disabled {
  cursor: pointer;
}
</style>
