<template>
  <el-dialog
    class="photoSetDialog"
    title="设置"
    :visible.sync="isShow"
    :close-on-click-modal="false"
    width="1020px"
    @close="handleclose"
  >
    <div class="setTimeTd" v-loading="timeboxLoading">
      <div class="headTitle">
        <div class="rulesInfo">
          <h3>时间表规则：</h3>
          <div class="timeBox" v-for="(val, index) in rulesList" :key="index">
            <div class="timeSlot">
              {{
                new Date(val.startTime).getHours() < 10
                  ? "0" + new Date(val.startTime).getHours()
                  : new Date(val.startTime).getHours()
              }}:
              {{
                new Date(val.startTime).getMinutes() < 10
                  ? "0" + new Date(val.startTime).getMinutes()
                  : new Date(val.startTime).getMinutes()
              }}
              ~
              {{
                new Date(val.endTime).getHours() < 10
                  ? "0" + new Date(val.endTime).getHours()
                  : new Date(val.endTime).getHours()
              }}:
              {{
                new Date(val.endTime).getMinutes() < 10
                  ? "0" + new Date(val.endTime).getMinutes()
                  : new Date(val.endTime).getMinutes()
              }}
            </div>
            <div class="timespan">
              间隔：<b>{{ val.span }}分钟</b>
            </div>
          </div>
        </div>
      </div>
      <div class="mathFloor">
        <span class="mathTitle">设置偏移量(max:10)：</span>
        <el-input-number v-model="mathMam" :min="0" :max="10"></el-input-number>
        <el-button type="primary" @click="setMathFloor()">设置</el-button>
      </div>
      <div class="channelBox">
        <span class="channelTitle">选择通道：</span>
        <div class="checkBox" v-if="channelList.length !== 0">
          <el-radio-group v-model="checkedAisle" @change="handleChange">
            <el-radio
              :label="val.id"
              border
              v-for="val in channelList"
              :key="val.id"
              >{{ val.name }}</el-radio
            >
          </el-radio-group>
        </div>
      </div>
      <div class="treebox" v-loading="treeloading">
        <el-tree
          ref="tree"
          :data="treeList"
          :props="defaultProps"
          show-checkbox
          node-key="id"
          default-expand-all
          :expand-on-click-node="false"
          @check="getCheckedNodes"
        >
          <div
            class="custom-tree-node"
            slot-scope="{ node, data }"
            v-if="!data.list"
          >
            <span class="zzCmdidbox">{{
              data.name == null ? data.cmdid : data.name
            }}</span
            >-- <span>{{ data.id }}</span
            >-- <span>{{ data.onlinestatus == 0 ? "离线" : "在线" }}</span
            >--
            <span>{{ data.protocol }}</span>
            <div class="math">
              偏移时间(分)：
              <el-input-number
                v-model="data.offsetNum"
                :min="0"
                :max="mathMam"
              ></el-input-number>
            </div>
            <div class="xfBack" v-if="allCheckNode.indexOf(data) != -1">
              <el-tag v-if="data.xfloading"
                ><i class="el-icon-loading"></i>下发中</el-tag
              >
              <el-tag v-if="data.xferror" type="danger"
                ><i class="el-icon-error"></i>下发失败</el-tag
              >
              <el-tag v-if="data.xfsuccess" type="success"
                ><i class="el-icon-success"></i>下发成功</el-tag
              >
              <el-button size="mini" v-if="data.xferror" @click="reissue(data)"
                >重新下发</el-button
              >
            </div>
          </div>
          <div v-else class="custom-tree-node" slot-scope="{ data }">
            <span>{{ data.name == null ? data.cmdid : data.name }}</span>
          </div>
        </el-tree>
      </div>
    </div>
    <div slot="footer" class="dialog-footer">
      <!-- <el-button @click="getCheckedNodes">获取</el-button> -->
      <el-button @click="handleclose">取 消</el-button>
      <el-button type="primary" @click="submitForm()">确 定</el-button>
    </div>
  </el-dialog>
</template>
<script>
import {
  setScheduleRulel,
  getScheduleRulelAccessList,
  getTermListByChannelJoggle,
  //setTermCamera,
  //getTermCameraRequest,
  getCmaSchelduleUpload,
} from "@/utils/api/index";
// import moment from "moment";
export default {
  data() {
    return {
      isShow: false,
      timeboxLoading: false,
      rulesTimeList: "", //当前时间表数据
      rulesList: [],
      rulesid: "", //规则id
      mathMam: 0, //偏移量默认为0
      checkedAisle: 1, //选中通道数据
      channelList: [], //通道数据内容
      treeloading: false,
      treeList: [], //树结构
      defaultProps: {
        children: "list",
        label: "name",
        disabled: this.disabledFn,
      },
      allCheckNode: [], //获取选中的节点
      groupNum: "", //时间表组数
      xfloading: false,
      xferror: false,
      xfsuccess: false,
      requestList: [], //requesids数组
      timer: null,
      imun: 0,

      successTermid: [], //成功的
      errorTermid: [], //失败的
    };
  },
  mounted() {},
  methods: {
    //判断
    getdataform(val) {
      console.log(val);
      this.rulesTimeList = val;
      this.rulesid = val.id;
      this.rulesList = val.listTime;
      this.timeboxLoading = true;
      this.getChannelList();
    },
    //设置偏移量
    setMathFloor() {
      console.log(this.mathMam);
      this.handleChange();
    },
    //不在线的装置不能选中
    disabledFn(data, node) {
      if (node.level == 3) {
        if (!data.onlinestatus) {
          // 根据自己的节点数据条件设置判断，我只提供了个参考
          return true;
        } else {
          return false;
        }
      }
    },
    // //获取所选值
    getCheckedNodes(nodeObj) {
      console.log(nodeObj);
      this.allCheckNode = this.$refs.tree.getCheckedNodes();
      console.log(this.allCheckNode);
      // console.log(nodeObj);
      // console.log(this.allCheckNode);
      // this.isactive = nodeObj.id || nodeObj.termid;
      // this.isCheck = this.$refs.tree.getCheckedNodes().indexOf(nodeObj) > -1;
      // console.log(this.isCheck);
      // this.showtag = false;
    },
    // 给数组里的每一个对象都添加一个offsetNum偏移属性
    getChildren(data) {
      //console.log(data);
      return data.map((item) => {
        //console.log(item);
        item = Object.assign({}, item);
        item.offsetNum = Math.floor(Math.random() * 10);
        item.xfsuccess = false;
        item.xferror = false;
        item.xfloading = false;
        if (!!item.list && item.list.length > 0) {
          item.list = this.getChildren(item.list);
        }
        return item;
      });
    },
    // 保存确定操作
    submitForm() {
      console.log(this.allCheckNode);
      this.xfloading = true;
      var ruleBox = []; //定义时间表规则大数组参数
      //首先循环时间规则
      for (let i = 0; i < this.allCheckNode.length; i++) {
        if (
          this.allCheckNode[i].bsManufacturer == null ||
          this.allCheckNode[i].bsManufacturer == undefined
        ) {
          this.allCheckNode[i].xfloading = true;
          let timearr = [];
          let dayArr = [];
          for (let j = 0; j < this.rulesList.length; j++) {
            var Stime = this.$moment(this.rulesList[j].startTime).add(
              this.allCheckNode[i].offsetNum,
              "minute"
            );

            var Etime = this.$moment(this.rulesList[j].endTime).add(
              this.allCheckNode[i].offsetNum,
              "minute"
            );

            var spanTime = this.rulesList[j].span;
            console.log(Stime, Etime, spanTime);
            //湖南规约
            if (this.allCheckNode[i].protocol == "65283") {
              timearr.push(
                {
                  hour: Math.floor(spanTime / 60),
                  minute: spanTime % 60,
                  preset: 255,
                },
                {
                  hour: Stime.hour(),
                  minute: Etime.minute(),
                  preset: 255,
                },
                {
                  hour: Stime.hour(),
                  minute: Etime.minute(),
                  preset: 255,
                }
              );
              console.log(timearr);
            } else {
              //其他规约
              let startDay = Stime;
              let endDay = Etime;
              let startVal = this.$moment(new Date(startDay)).format(
                "YYYY-MM-DD HH:mm"
              );
              while (this.$moment(startVal).isBefore(endDay)) {
                dayArr.push(startVal);
                // 自增
                startVal = this.$moment(new Date(startVal))
                  .add(spanTime, "minute")
                  .format("YYYY-MM-DD HH:mm");
              }
            }
          }
          console.log(dayArr);
          for (var k = 0; k < dayArr.length; k++) {
            //console.log(moment(dayArr[k]).hour());
            timearr.push({
              hour: this.$moment(dayArr[k]).hour(),
              minute: this.$moment(dayArr[k]).minute(),
              preset: 255,
            });
          }
          console.log(timearr);
          var parmsobj = {
            termid: this.allCheckNode[i].id,
            channelid: this.checkedAisle,
            offset: this.allCheckNode[i].offsetNum,
            list: timearr,
          };
          ruleBox.push(parmsobj);
        }
      }
      //设置下发时间表规则
      setScheduleRulel({
        list: ruleBox,
        scheduleid: this.rulesid,
      })
        .then((res) => {
          console.log(res);
          this.requestList = res.data.list;
          // this.requestTime();
          this.timer = window.setInterval(() => {
            //console.log(this.requestList);
            this.requestTime();
            this.imun++;
          }, 3000);
        })
        .catch((err) => {});
    },
    //根据requestid查询时间表下发状态
    requestTime() {
      this.sureloading = true;
      getCmaSchelduleUpload({
        list: this.requestList,
      })
        .then((res) => {
          this.requestArr = res.data.list;
          console.log(this.requestList);
          this.requestList = this.requestArr.filter(function (
            value,
            index,
            arr
          ) {
            console.log(value, index, arr);
            return value.status !== 1;
          });
          if (this.requestList.length == 0) {
            console.log(this.successTermid);
            console.log(this.errorTermid);
            this.$message.success("下发成功");
            clearInterval(this.timer);
            this.timer = null;
          } else if (this.imun > 9) {
            console.log(this.requestList);
            for (let m = 0; m < this.requestList.length; m++) {
              console.log(this.requestList[m]);
              this.errorTermid.push(this.requestList[m].termid);
            }
            console.log(this.errorTermid);

            clearInterval(this.timer);
            this.timer = null;
            this.imun = 0;
            // this.$message.warning("下发失败，请稍后再试！");
          }
        })
        .catch((err) => {});
    },

    //重新下发
    reissue(val) {
      console.log(val);
      val.xfloading = true;
      val.xferror = false;
      setTimeout(() => {
        val.xfloading = false;
        val.xfsuccess = true;
        val.xferror = false;
      }, 2000);
    },
    //获取通道
    getChannelList() {
      getScheduleRulelAccessList({})
        .then((res) => {
          console.log(res);
          this.channelList = res.data.channellist;

          this.handleChange();
        })
        .catch((err) => {});
    },
    //改变通道获取树状结构
    handleChange() {
      console.log(this.checkedAisle);
      this.treeloading = true;
      getTermListByChannelJoggle({
        id: this.checkedAisle,
      })
        .then((res) => {
          console.log(res);
          this.timeboxLoading = false;
          //this.treeList = res.data.list;
          this.treeList = this.getChildren(res.data.list);
          this.treeloading = false;
        })
        .catch((err) => {});
    },
    display() {
      this.isShow = true;
    },
    clearfn() {},
    handleclose() {
      this.isShow = false;
    },
  },
};
</script>
<style lang="less">
.photoSetDialog {
  .setTimeTd {
    //background-color: #fcc;
    .headTitle {
      .rulesInfo {
        display: flex;
        align-items: center;
        line-height: 32px;
        h3 {
          font-size: 14px;
          font-weight: normal;
        }
        .timeBox {
          display: flex;
          align-items: center;
          font-size: 14px;
          margin-right: 8px;
          .timeSlot {
            font-size: 14px;
            margin-right: 8px;
          }
          .timespan {
            b {
              font-size: 14px;
              font-weight: normal;
              color: #169e8c;
            }
          }
        }
      }
    }
    .mathFloor {
      margin-top: 8px;
      .mathTitle {
        font-size: 14px;
        font-weight: normal;
      }
      .el-button {
        margin-left: 8px;
      }
    }
    .channelBox {
      display: flex;
      align-items: center;
      line-height: 32px;
      margin-top: 8px;
      .channelTitle {
        font-size: 14px;
      }
      .el-radio {
        margin-right: 8px;
      }
    }
    .treebox {
      margin-top: 8px;
      background-color: #169e8c;
      height: 366px;
      // overflow: auto;
      display: flex;
      align-items: flex-start;
      border: 1px solid #eee;
      padding: 8px;
      border-radius: 4px;
      position: relative;
      .el-tree {
        width: 100%;
        height: 100%;
        overflow: auto;

        .el-tree-node {
          .el-tree-node__content {
            height: 32px;
            border-bottom: 1px solid #eee;
          }
        }
        .custom-tree-node {
          display: flex;
          align-items: center;
          .zzCmdidbox {
            width: 180px;
          }
          .math {
            margin-left: 32px;
          }
          .xfBack {
            margin-left: 32px;
          }
          .el-input-number--small {
            line-height: 26px;
          }
          .el-input--small .el-input__inner {
            height: 26px;
            line-height: 26px;
          }
          .el-input-number__increase {
            height: 24px;
          }
        }
      }
    }
  }
}
</style>
