<template>
  <el-dialog
    class="photoSetDialog"
    title="设置"
    :visible.sync="isShow"
    :close-on-click-modal="false"
    width="1020px"
  >
    <div class="setTimeTd" v-loading="rulesLoading">
      <div class="ruleinfo">
        <!-- <h3>时间表规则</h3> -->
        <div class="ruleBox">
          <span class="nameinfo">时间表名称：{{ currentTimeRule.name }}</span>
          <div class="listGz">
            <p
              class="timeGz"
              v-for="(val, index) in currentTimeRule.listTime"
              :key="index"
            >
              <span>{{ val.startTime }} </span>

              ~
              <span>{{ val.endTime }}</span>
              间隔：<b>{{ val.timeSpan }}分钟</b>
            </p>
          </div>
          <div class="offsetBox">
            <div class="math">
              设置偏移量(max:10)：
              <el-input-number
                v-model="setNum"
                :min="0"
                :max="9"
              ></el-input-number>
            </div>
            <el-button type="primary" @click="setMathFloor()">设置</el-button>
          </div>
        </div>
        <div class="channelBox">
          <span>请选择通道：</span>
          <div class="checkBox">
            <el-radio-group v-model="channelAisle" @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>
      <!-- 装置树状图 -->
      <div class="treeDevice" v-loading="treeloading">
        <el-tree
          ref="tree"
          :data="treeList"
          :props="defaultProps"
          show-checkbox
          node-key="id"
          default-expand-all
          :expand-on-click-node="false"
          :default-checked-keys="defaultCheckedKeys"
          @check-change="handleCheckChange"
        >
          <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.setNum"
                :min="0"
                :max="setNum"
              ></el-input-number>
            </div>
            <div class="xfBack">
              <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="handleclose">取 消</el-button>
      <el-button type="primary" @click="submitForm()" :loading="sureloading"
        >确 定</el-button
      >
    </div>
  </el-dialog>
</template>
<script>
import {
  setScheduleRulel,
  getScheduleRulelAccessList,
  getTermListByChannelJoggle,
  getCmaSchelduleUpload,
  setTermCamera,
  getTermCameraRequest,
} from "@/utils/api/index";

export default {
  data() {
    return {
      isShow: false,
      currentTimeRule: [], //时间表规则
      sureloading: false,
      setNum: 0,
      channelList: [], //通道列表
      channelAisle: 1, //选中的通道
      rulesLoading: false,
      treeloading: false, //树状结构loading
      treeList: [], //获取treelist
      defaultProps: {
        children: "list",
        label: "name",
        disabled: this.disabledFn,
      },
      defaultCheckedKeys: [],
      checkedNodes: [],
      requestid: "", //获取requestid
      deviceTimeLoading: false,
      deviceTimer: null, //装置循环获取
      deviceNum: 1, //循环次数
    };
  },
  mounted() {},
  methods: {
    getdataform(val) {
      console.log(val);
      this.currentTimeRule = val;
      this.rulesLoading = true;
      this.getChannelList();
    },
    //设置偏移量
    setMathFloor() {
      console.log(this.setNum);
      this.handleChange();
    },
    //获取通道
    getChannelList() {
      getScheduleRulelAccessList({})
        .then((res) => {
          console.log(res);
          this.rulesLoading = false;
          this.channelList = res.data.channellist;
          this.handleChange();
        })
        .catch((err) => {});
    },
    //改变通道获取树状结构
    handleChange() {
      console.log(this.channelAisle);
      console.log("点击了通道");
      this.getTreeList();
    },
    //获取树状图
    getTreeList() {
      this.treeloading = true;
      getTermListByChannelJoggle({
        id: this.channelAisle,
      })
        .then((res) => {
          console.log(res);
          this.treeList = this.getChildren(res.data.list);
          this.treeloading = false;
        })
        .catch((err) => {});
    },
    //获取treelist
    getChildren(data) {
      console.log(data);
      return data.map((item) => {
        //console.log(item);
        item = Object.assign({}, item);
        item.setNum = 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;
      });
    },
    //不在线的装置不能选中
    disabledFn(data, node) {
      if (node.level == 3) {
        if (!data.onlinestatus) {
          // 根据自己的节点数据条件设置判断，我只提供了个参考
          return true;
        } else {
          return false;
        }
      }
    },
    handleCheckChange(data, checked) {
      if (checked) {
        this.checkedNodes.push(data);
      } else {
        const index = this.checkedNodes.findIndex(
          (node) => node.id === data.id
        );
        if (index !== -1) {
          this.checkedNodes.splice(index, 1);
        }
      }
    },

    submitForm() {
      if (this.checkedNodes.length === 0) {
        this.$message.warn("请至少选择一个选项");
        return;
      }
      this.sureloading = true;
      console.log(this.checkedNodes);

      const requests = this.checkedNodes.map((node) => {
        console.log(node);
        node.xfloading = true; //下发按钮出现
        node.xferror = false; //下发失败按钮隐藏
        node.xfsuccess = false; //下发成功按钮隐藏
        let params = [
          {
            name: "act",
            value: "schedule",
          },
          {
            name: "flag",
            value: 1,
          },
          {
            name: "channel",
            value: this.channelAisle,
          },
        ];
        // 根据 node 发送 Axios 请求并返回一个 Promise 对象
        let scheduleTimeList = this.currentTimeRule.listTime;
        console.log(this.currentTimeRule.listTime);
        let timeArr = []; //获取时间列表
        //获取当前时间规则，转化成时间点
        for (let i = 0; i < scheduleTimeList.length; i++) {
          console.log(scheduleTimeList[i]);
          var Stime = this.$moment(scheduleTimeList[i].startTime, "HH:mm")
            .add(node.setNum, "minute")
            .format("YYYY-MM-DD HH:mm:ss");

          var Etime = this.$moment(scheduleTimeList[i].endTime, "HH:mm")
            .add(node.setNum, "minute")
            .format("YYYY-MM-DD HH:mm:ss");
          var spanTime = scheduleTimeList[i].timeSpan;
          console.log(Stime, Etime, spanTime);
          if (node.protocol == "65283" || node.protocol == "65285") {
            //湖南 河南
            console.log("湖南,河南", scheduleTimeList.length);

            // 设置时间间隔
            let fistSpan = this.$moment(new Date())
              .startOf("day")
              .minutes(spanTime)
              .format("YYYY-MM-DD HH:mm:ss");
            timeArr.push(fistSpan, Stime, Etime);
            console.log(timeArr);
          } else {
            //其他规约

            while (
              this.$moment(Stime).isBefore(this.$moment(Etime)) ||
              this.$moment(Stime).isSame(this.$moment(Etime))
            ) {
              timeArr.push(Stime);
              Stime = this.$moment(Stime)
                .add(spanTime, "minute")
                .format("YYYY-MM-DD HH:mm:ss");
            }
          }
        }
        console.log(timeArr);
        let group = timeArr.length;
        params.push({
          name: "group",
          value: group,
        });
        for (let m = 0; m < timeArr.length; m++) {
          params.push(
            {
              name: "hour" + (m + 1),
              value: this.$moment(timeArr[m]).hour(),
            },
            {
              name: "min" + (m + 1),
              value: this.$moment(timeArr[m]).minute(),
            },
            {
              name: "preset" + (m + 1),
              value: 255,
            }
          );
        }
        console.log(params);
        return this.setTermFnRule(node, params);
      });
      // 使用 Promise.all 等待所有请求完成
      Promise.all(requests)
        .then(() => {
          console.log(requests);
          // 所有请求都成功完成后的处理逻辑

          console.log("所有请求都已完成。");
        })
        .catch((error) => {
          // 如果有任何一个请求失败的处理逻辑
          console.error("有一个或多个请求失败。", error);
        });
    },
    //下发时间表
    setTermFnRule(node, dataParams) {
      setTermCamera({
        termId: node.id,
        list: dataParams,
      })
        .then((res) => {
          console.log(res);
          this.requestid = res.data.requestId;
          this.getinfoRules(node);
        })
        .catch((err) => {});
    },
    getinfoRules(node) {
      console.log(this.deviceNum);
      getTermCameraRequest({ requestid: this.requestid })
        .then((res) => {
          if (res.data.success == 1) {
            console.log(JSON.parse(res.data.data));
            node.xfloading = false;
            node.xfsuccess = true;
            this.deviceNum = 0;
            this.sureloading = false;
            // this.$message({
            //   duration: 1500,
            //   showClose: true,
            //   message: "时间表下发成功",
            //   type: "success",
            // });
          } else if (res.data.success == 0 && this.deviceNum > 9) {
            node.xfloading = false;
            node.xfsuccess = false;
            node.xferror = true;
            this.sureloading = false;
            this.deviceNum = 0;
          } else {
            // 继续轮询查询接口
            setTimeout(() => {
              this.deviceNum++;
              this.getinfoRules(node);
            }, 2000); // 1秒后继续查询
          }
        })
        .catch((err) => {});
    },
    display() {
      this.isShow = true;
    },
    clearfn() {},
    handleclose() {
      this.isShow = false;
      this.setNum = 0;
      this.treeList = []; //获取treelist
    },
  },
};
</script>
<style lang="less">
.photoSetDialog {
  .setTimeTd {
    .ruleinfo {
      margin-bottom: 16px;
      h3 {
        font-size: 14px;
        margin-bottom: 8px;
      }
      .ruleBox {
        display: flex;
        flex-wrap: wrap;
        align-items: center;
        line-height: 32px;
        margin-bottom: 16px;
        .nameinfo {
          //margin-bottom: 8px;
          margin-right: 16px;
          height: 24px;
          line-height: 24px;
        }
        .timeGz {
          height: 24px;
          line-height: 24px;
          b {
            font-weight: 400;
            color: #169e8c;
          }
        }
      }
      .offsetBox {
        margin-left: 24px;
        display: flex;
        align-items: center;
        .math {
          margin-right: 12px;
        }
      }
    }
    .channelBox {
      margin-bottom: 16px;
      line-height: 32px;
      display: flex;
      height: 32px;
      .checkBox {
        .el-radio {
          margin-right: 12px;
        }
      }
    }
    .treeDevice {
      //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;
        }
        .math {
          margin-left: 24px;
        }
        .xfBack {
          margin-left: 24px;
        }
      }
    }
  }
}
</style>
