<template>
  <el-dialog
    class="photoSetDialog"
    title="设置"
    :visible.sync="isShow"
    :close-on-click-modal="false"
    width="1020px"
    @close="handleclose"
  >
    <div class="setTimeTd">
      <div class="ruleBox">
        <h3>时间表规则</h3>
        <div class="flexTimeGz">
          <p class="timeGz" v-for="(val, index) in ruleSchedule" :key="index">
            <span>
              {{
                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()
              }}</span
            >
            ~
            <span
              >{{
                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()
              }}</span
            >
            间隔：<b>{{ val.span }}分钟</b>
          </p>
        </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>

      <!-- <h3>设置通道</h3> -->
      <div class="chooseTDBox">
        <label>选择通道:</label>
        <div class="checkBox">
          <el-radio-group v-model="checkedAisle" @change="handleChange">
            <el-radio
              :label="val.id"
              border
              v-for="val in aisleList"
              :key="val.id"
              >{{ val.name }}</el-radio
            >
          </el-radio-group>
        </div>
      </div>
      <div
        class="flexnr"
        v-loading="loading"
        v-if="newzzList.length !== 0 || loading"
      >
        <el-tree
          :class="sureloading ? 'noallow' : ''"
          :data="newzzList"
          show-checkbox
          :props="defaultProps"
          ref="tree"
          node-key="id"
          :default-expand-all="true"
          @check-change="getCheckedNodes"
        >
          <div
            v-if="!data.list"
            class="custom-tree-node nodelist"
            slot-scope="{ data }"
          >
            <span class="mr10">{{
              data.name == null ? data.cmdid : data.name
            }}</span>
            <div class="math">
              偏移时间(分)：
              <el-input-number
                v-model="data.offsetNum"
                :min="0"
                :max="mathMam"
              ></el-input-number>
            </div>
            <div class="deStatus" v-if="allCheckNode.indexOf(data) != -1">
              <el-tag v-if="xfload && showtag"
                ><i class="el-icon-loading"></i>下发中</el-tag
              >
              <el-tag
                type="danger"
                v-if="
                  nosuccessData.findIndex((item) => item.termid === data.id) !==
                    -1 &&
                  showtag &&
                  !xfload
                "
                >下发失败</el-tag
              >
              <el-tag
                type="success"
                v-if="
                  nosuccessData.findIndex((item) => item.termid === data.id) ==
                    -1 &&
                  showtag &&
                  !xfload
                "
                >下发成功</el-tag
              >
            </div>
            <!-- <div
              class="deStatus"
              v-if="allCheckNode.indexOf(data) != -1 && showtag"
            >
              <el-tag
                type="success"
                v-if="xfsuccess && allCheckNode.indexOf(data) != -1 && showtag"
                >下发成功</el-tag
              >
              <el-tag v-if="xfload && showtag"
                ><i class="el-icon-loading"></i>下发中</el-tag
              >
              <el-tag
                type="danger"
                v-if="xferror && allCheckNode.indexOf(data) != -1 && showtag"
                >下发失败</el-tag
              >
            </div> -->
          </div>
          <span v-else class="custom-tree-node" slot-scope="{ data }">
            <span>{{ data.name == null ? data.cmdid : data.name }}</span>
          </span>
        </el-tree>
      </div>

      <div class="flexnr" v-else>
        <p class="nochannel">暂无图像监测装置</p>
      </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()" :loading="sureloading"
        >确 定</el-button
      >
    </div>
  </el-dialog>
</template>
<script>
import {
  setScheduleRulel,
  getScheduleRulelAccessList,
  getTermListByChannelJoggle,
  getCmaSchelduleUpload,
} from "@/utils/api/index";
import moment from "moment";
export default {
  props: {
    title: String,
  },
  data() {
    return {
      isactive: "",
      contentStyle: { width: "90px" },
      isShow: false,
      selid: 0, //选中时间表id
      ruleSchedule: [], //时间表规则
      checkedAisle: 1, //选中通道数据
      aisleList: [], //通道数据内容
      listnr: [], //通道树状结构
      defaultProps: {
        children: "list",
        label: "name",
        disabled: this.disabledFn,
      },
      termidArr: [],
      ruleid: "",
      parmsList: [], //选中的通道
      multipleSelection: [],
      //新是数据结构参数
      newzzList: [],
      zzListCheck: [],
      loading: false,

      //全选
      checkAll: true,
      isIndeterminate: true, //全选设置默认选中
      timer: null,
      termidArrNum: -1,
      requestList: [],

      timer: null,
      i: 0,
      isCheck: false,
      checkNode: null,
      zzsuccess: false,
      zzpending: false,
      zzerror: false,

      allCheckNode: [], //获取选中的节点

      requestArr: [], //通过requestid获取状态
      termzzid: [],
      flag: false,
      sureloading: false,
      showtag: false,
      checkOffset: "",
      mathMam: 0,

      //未下发成功
      nosuccessData: [],
      xfsuccess: false,
      xfload: false,
      xferror: false,
    };
  },
  mounted() {},
  methods: {
    //判断
    getdataform(val) {
      console.log(val);
      this.selid = val.id;
      this.ruleSchedule = val.listTime;
      console.log(this.ruleSchedule);
      // console.log(this.ruleSchedule, "时间规则");
      this.getlistnr();
    },
    //获取所有通道
    getlistnr() {
      getScheduleRulelAccessList({})
        .then((res) => {
          this.listnr = res.data.list;
          this.aisleList = res.data.channellist;
          this.handleChange();
        })
        .catch((err) => {});
    },

    //选择通道
    handleChange() {
      console.log(this.checkedAisle);
      this.loading = true;
      getTermListByChannelJoggle({
        id: this.checkedAisle,
      })
        .then((res) => {
          console.log(res);
          this.newzzList = res.data.list;
          console.log(this.newzzList);
          this.newzzList = this.getChildren(this.newzzList);
          console.log(this.newzzList);
          this.loading = false;
        })
        .catch((err) => {});
    },
    //不在线的装置不能选中
    disabledFn(data, node) {
      if (node.level == 3) {
        if (!data.onlinestatus) {
          // 根据自己的节点数据条件设置判断，我只提供了个参考
          return true;
        } else {
          return false;
        }
      }
    },
    // 给数组里的每一个对象都添加一个isEdit属性
    getChildren(data) {
      //console.log(data);
      return data.map((item) => {
        //console.log(item);
        item = Object.assign({}, item);
        item.offsetNum = Math.floor(Math.random() * 10);

        if (!!item.list && item.list.length > 0) {
          item.list = this.getChildren(item.list);
        }
        return item;
      });
    },
    handleCheckBox() {
      console.log(this.zzListCheck);
    },
    //设置偏移量
    setMathFloor() {
      console.log(this.mathMam);
      this.handleChange();
    },

    // //获取所选值
    getCheckedNodes(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;
    },

    // 保存确定操作
    submitForm() {
      //console.log(this.termidArr);
      this.sureSum();
      this.showtag = true;
      this.xfload = true;
      this.sureloading = true;
    },
    //时间表
    sureSum() {
      console.log(this.checkedAisle);

      var ruleBox = [];
      //循环装置
      for (var i = 0; i < this.allCheckNode.length; i++) {
        console.log(this.allCheckNode[i].bsManufacturer);
        if (
          this.allCheckNode[i].bsManufacturer == null ||
          this.allCheckNode[i].bsManufacturer == undefined
        ) {
          console.log(this.allCheckNode[i].offsetNum);
          //循环时间规则
          let timearr = [];
          let dayArr = [];
          for (var j = 0; j < this.ruleSchedule.length; j++) {
            console.log(this.ruleSchedule);
            console.log(this.ruleSchedule[j].startTime);
            // var Stime = moment(this.ruleSchedule[j].startTime).format("HH:mm");
            // var Etime = moment(this.ruleSchedule[j].endTime).format("HH:mm");

            var Stime = moment(this.ruleSchedule[j].startTime)
              .add(this.allCheckNode[i].offsetNum, "minute")
              .format();
            var Etime = moment(this.ruleSchedule[j].endTime)
              .add(this.allCheckNode[i].offsetNum, "minute")
              .format();
            var lastETime = moment(this.ruleSchedule[j].endTime).format();

            var spanTime = this.ruleSchedule[j].span;
            console.log(spanTime);
            console.log(moment(this.ruleSchedule[j].endTime).hour());
            //判断湖南规约
            if (this.allCheckNode[i].protocol == "65283") {
              console.log("湖南规约");
              console.log(Stime, Etime);
              console.log(typeof Stime);
              console.log(
                moment(this.ruleSchedule[j].endTime)
                  .add(this.allCheckNode[i].offsetNum, "minute")
                  .hour()
              );
              console.log(
                moment(this.ruleSchedule[j].endTime)
                  .add(this.allCheckNode[i].offsetNum, "minute")
                  .minute()
              );

              //如果偏移之后的时间是第二天，那么不做偏移
              console.log(moment().isSame(moment(Etime), "day"));
              //判断是不是同一天
              if (moment().isSame(moment(Etime), "day")) {
                //如果是同一天
                timearr.push(
                  {
                    hour: Math.floor(this.ruleSchedule[j].span / 60),
                    minute: this.ruleSchedule[j].span % 60,
                    preset: 255,
                  },
                  {
                    hour: moment(this.ruleSchedule[j].startTime)
                      .add(this.allCheckNode[i].offsetNum, "minute")
                      .hour(),
                    minute: moment(this.ruleSchedule[j].startTime)
                      .add(this.allCheckNode[i].offsetNum, "minute")
                      .minute(),
                    preset: 255,
                  },
                  {
                    hour: moment(this.ruleSchedule[j].endTime)
                      .add(this.allCheckNode[i].offsetNum, "minute")
                      .hour(),
                    minute: moment(this.ruleSchedule[j].endTime)
                      .add(this.allCheckNode[i].offsetNum, "minute")
                      .minute(),
                    preset: 255,
                  }
                );
              } else {
                timearr.push(
                  {
                    hour: Math.floor(this.ruleSchedule[j].span / 60),
                    minute: this.ruleSchedule[j].span % 60,
                    preset: 255,
                  },
                  {
                    hour: moment(this.ruleSchedule[j].startTime)
                      .add(this.allCheckNode[i].offsetNum, "minute")
                      .hour(),
                    minute: moment(this.ruleSchedule[j].startTime)
                      .add(this.allCheckNode[i].offsetNum, "minute")
                      .minute(),
                    preset: 255,
                  },
                  {
                    hour: moment(this.ruleSchedule[j].endTime).hour(),
                    minute: moment(this.ruleSchedule[j].endTime).minute(),
                    preset: 255,
                  }
                );
              }

              console.log(timearr);
            }
            ////判断河南规约
            if (
              this.allCheckNode[i].protocol == "65286" ||
              this.allCheckNode[i].protocol == "65282" ||
              this.allCheckNode[i].protocol == "65280" ||
              this.allCheckNode[i].protocol == "65296" ||
              this.allCheckNode[i].protocol == "65281" ||
              this.allCheckNode[i].protocol == "65284" ||
              this.allCheckNode[i].protocol == "65285"
            ) {
              console.log("河南规约");
              //偏移时间
              //this.getDayArr(startDay, endDay);

              let startDay = Stime;
              let endDay = Etime;
              var lastendDay = lastETime;
              console.log(lastETime);
              console.log(startDay, endDay);
              let startVal = this.$moment(new Date(startDay)).format(
                "YYYY-MM-DD HH:mm"
              );
              console.log(startVal);
              console.log(moment().isSame(moment(endDay), "day"));
              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(startVal);
              }

              // // 将结束日期的天放进数组
              if (!moment().isSame(moment(endDay), "day")) {
                // console.log("dayArr最后一天啊");
                // console.log(dayArr);
                // console.log(
                //   this.$moment(new Date(lastETime)).format("YYYY-MM-DD HH:mm")
                // );
                // dayArr.push(
                //   this.$moment(new Date(lastETime)).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: moment(dayArr[k]).hour(),
              minute: moment(dayArr[k]).minute(),
              preset: 255,
            });
          }
          // return dayArr;
          var parmsobj = {
            termid: this.allCheckNode[i].id,
            channelid: this.checkedAisle,
            offset: this.allCheckNode[i].offsetNum,
            list: timearr,
          };
          //console.log(parmsobj);
          ruleBox.push(parmsobj);
        }
        //console.log(ruleBox);
      }
      setScheduleRulel({
        list: ruleBox,
        scheduleid: this.selid,
      })
        .then((res) => {
          console.log(res);
          this.requestList = res.data.list;
          this.requestTime();
          this.timer = window.setInterval(() => {
            //console.log(this.requestList);
            this.requestTime();
            this.i++;
          }, 3000);
        })
        .catch((err) => {
          // this.$message({
          //   duration: 1500,
          //   showClose: true,
          //   message: "添加失败",
          //   type: "error",
          // });
        });
    },
    //获取到时间规则，把时间规则转化为对应的规约格式
    //湖南规约
    getHnTime() {},
    //河南规约
    getZzTime() {},
    //根据requestid查询时间表下发状态
    requestTime() {
      this.sureloading = true;
      getCmaSchelduleUpload({
        list: this.requestList,
      })
        .then((res) => {
          this.requestArr = res.data.list;
          this.requestList = this.requestArr.filter(function (
            value,
            index,
            arr
          ) {
            console.log(value, index, arr);
            return value.status !== 1;
          });

          if (this.requestList.length == 0) {
            this.zzsuccess = true;
            this.$message.success("下发成功");
            clearInterval(this.timer);
            this.timer = null;
            this.sureloading = false;
            this.xfload = false;
          } else if (this.i > 9) {
            console.log(this.requestArr);
            this.nosuccessData = this.requestArr;

            // this.allCheckNode.forEach((item, i) => {

            //   this.$refs.tree.setChecked(item.id, false, true);
            // });

            // this.nosuccessData.forEach((item, i) => {
            //   this.$refs.tree.setChecked(item.termid, true, true);
            // });

            this.i = 0;
            // this.$message.warning("下发失败，请稍后再试！");
            clearInterval(this.timer);
            this.timer = null;

            this.xfload = false;

            this.sureloading = false;
          }
        })
        .catch((err) => {});
    },
    display() {
      this.isShow = true;
    },
    clearfn() {
      clearTimeout(this.timer);
      this.timer = null;
    },
    handleclose() {
      this.isShow = false;
      this.newzzList = [];
      this.checkedAisle = 1;
      this.mathMam = 0;
      console.log(this.allCheckNode, "1111111111");
      clearTimeout(this.timer);
      this.timer = null;
      this.sureloading = false;
      this.showtag = false;
    },
  },
};
</script>
<style lang="less">
.photoSetDialog {
  .el-dialog__body {
    // height: 360px;
    // overflow: auto;
  }

  .flexnr {
    height: 360px;
    overflow: auto;
    display: flex;
    align-items: flex-start;
    border: 1px solid #eee;
    padding: 16px;
    border-radius: 4px;
    position: relative;

    .el-tree {
      flex: 1;
      border: 1px solid #eee;
      .el-tree-node {
        .el-tree-node__content {
          height: 40px;
          border-bottom: 1px solid #eee;
          .mr10 {
            margin-right: 10px;
            width: 180px;
          }
          .nodelist {
            display: flex;
            align-items: center;
            .math {
              margin-left: 32px;
            }
            .deStatus {
              margin-left: 24px;
            }
          }
        }
      }
    }
    .noallow {
      .el-tree-node .el-tree-node__content {
        pointer-events: none;
      }
    }

    .dybox {
      h4 {
        font-size: 14px;
        color: #333;
        line-height: 24px;
        font-weight: normal;
      }
      .xlbox {
        h4 {
          font-size: 14px;
          color: #333;
          line-height: 24px;
          font-weight: normal;
        }
        margin-left: 16px;
        .zzbox {
          h4 {
          }
          .el-checkbox-group {
            // display: flex;
            // flex-direction: column;
            margin-left: 22px;
            .el-checkbox {
              line-height: 28px;
              //width: 196px;
              .el-checkbox__label {
                b {
                  margin-left: 18px;
                  font-weight: normal;
                  font-size: 12px;
                }
              }
            }
          }
        }
      }
    }
    .nochannel {
      width: 100%;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
  .w50 {
    width: 50px;
  }
  .setTimeTd {
    .ruleBox {
      display: flex;
      align-items: center;
    }
    h3 {
      margin: 8px 0px;
      font-size: 16px;
      line-height: 24px;
    }
    .flexTimeGz {
      display: flex;
      flex-wrap: wrap;
      .timeGz {
        line-height: 32px;
        margin-right: 16px;
        b {
          font-weight: normal;
          color: #169e8c;
        }
        span {
          margin: 0px 8px;
        }
      }
    }
    .mathFloor {
      margin-left: 20px;
      .el-button {
        margin-left: 12px;
      }
    }

    .setCheckbox {
      .el-table__header .el-table-column--selection .cell .el-checkbox:after {
        color: #333;
        content: "全选";
        font-size: 16px;
        margin-left: 12px;
        font-weight: bold;
      }
    }
  }
  .chooseTDBox {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
    margin-top: 12px;
    label {
      margin-right: 8px;
    }
  }
  .treeTable {
    margin-top: 16px;
  }
}
</style>
