<template>
  <div class="setTime">
    <el-dialog
      title="选择拍照时间表"
      :visible.sync="dialogVisible"
      width="1100px"
    >
      <div class="setBox">
        <div class="head">
          <h3>通道：</h3>
          <el-select
            v-model="channelVal"
            placeholder="请选择通道"
            ref="multiSelect"
            class="channelDiv"
          >
            <el-option
              v-for="item in channelListOption"
              :key="item.channelid"
              :label="
                item.alias !== null && item.alias !== ''
                  ? item.alias
                  : item.channelname
              "
              :value="item.channelid"
            >
              {{
                item.alias !== null && item.alias !== ""
                  ? item.alias
                  : item.channelname
              }}
            </el-option>
          </el-select>
          <!-- <el-select
            v-model="channelVal"
            placeholder="请选择"
            class="channelDiv"
          >
            <el-option
              v-for="item in channelOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select> -->
          <h3>预置位：</h3>
          <el-select
            v-model="presetVal"
            placeholder="请选择"
            class="channelDiv"
            filterable
          >
            <el-option
              v-for="n in 255"
              :key="n"
              :label="n"
              :value="n"
            ></el-option>
          </el-select>
          <h3>选择时间段：</h3>
          <el-time-picker
            is-range
            v-model="timeValue"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
            placeholder="选择时间范围"
          >
          </el-time-picker>
          <h3 class="timespan">时间间隔：</h3>
          <el-input-number v-model="timeNum"></el-input-number>
          <el-button type="primary" class="showList" @click="showTimeList"
            >时间列表</el-button
          >
          <el-button type="primary" class="serachBtn" @click="deviceTimeClick"
            >查询</el-button
          >
        </div>
        <div class="contain">
          <ul>
            <li v-for="(time, index) in timeList" :key="index">
              {{ formatTime(time) }}

              <el-input
                v-if="
                  deviceData.protocol != '65283' &&
                  deviceData.protocol != '65285' &&
                  deviceData.protocol != '65290' &&
                  deviceData.protocol != '65298'
                "
                v-model="selectedValues[index]"
                placeholder="请输入"
              ></el-input>
            </li>
          </ul>
          <div class="tagsBox" v-if="deviceTimeList.length !== 0">
            <el-tag v-for="(item, index) in deviceTimeList" :key="index"
              >时间点：{{ $moment(item).format("HH:mm") }} + 预置位:
              {{ item.preset || 255 }}</el-tag
            >
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeTimeFun">取 消</el-button>
        <el-button type="primary" @click="handleSetTimeClick"
          >下发时间表</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  getChannelByTermidJoggle,
  getTermStatus,
  setTermCamera,
  getTermCameraRequest,
} from "@/utils/api/index";
export default {
  data() {
    return {
      deviceData: "", //设备信息
      dialogVisible: false,
      timeValue: [], //开始时间，结束时间
      timeNum: 30, //时间间隔
      timeList: [], // 存储生成的时间点列表
      channelVal: 1,
      channelListOption: [], //通道数组
      // channelOptions: [
      //   {
      //     value: 1,
      //     label: "通道1",
      //   },
      //   {
      //     value: 2,
      //     label: "通道2",
      //   },
      // ],
      selectedValues: [], // 存储每个时间点对应的选中值
      presetVal: 1, //默认预置位
      timeparams: [], //点击获取时间点
      deviceTimer: null, //装置循环获取
      deviceNum: 1, //循环次数
      deviceTimeList: [],
      attemptCount: 0, // 新增的尝试次数计数器
      maxAttempts: 9, // 设置最大尝试次数
    };
  },
  mounted() {
    // 获取当前日期
    let today = new Date();
    // 设置今天的零点
    let startOfDay = new Date(today);
    startOfDay.setHours(0, 0, 0, 0); // 将小时、分钟、秒和毫秒均设为0
    // 设置今天的23点59分59秒
    let endOfDay = new Date(today);
    endOfDay.setHours(23, 59, 59, 999); // 将小时设为23，分钟设为59，秒设为59，毫秒设为999（或您希望的任意毫秒值）
    // 更新value1数组
    this.timeValue = [startOfDay, endOfDay];
  },
  methods: {
    display(val) {
      this.dialogVisible = true;
      this.deviceData = val;
      console.log(this.deviceData);
      this.getChannelList();
    },
    //获取通道的接口
    getChannelList() {
      console.log(this.deviceData);
      getChannelByTermidJoggle({ termid: this.deviceData.id })
        .then((res) => {
          console.log(res);
          this.channelListOption = res.data.list;
        })
        .catch((err) => {
          console.log(err); //代码错误、请求失败捕获
        });
    },
    showTimeList() {
      // 清空之前的时间点列表
      this.timeList = [];
      // 获取时间间隔的毫秒数
      const intervalMs = this.timeNum * 60 * 1000;
      // 克隆开始时间，避免修改原始timeValue数组中的startOfDay对象
      let currentTime = new Date(this.timeValue[0]);
      // 循环生成时间点，直到达到或超过结束时间
      while (currentTime <= this.timeValue[1]) {
        // 将当前时间点添加到列表中
        this.timeList.push(new Date(currentTime));
        // 增加时间间隔
        currentTime.setTime(currentTime.getTime() + intervalMs);
      }
      // 打印时间点列表到控制台（可选）
      console.log(this.timeList.map(this.formatTime));
      console.log(this.presetVal);
      this.selectedValues = this.timeList.map(() => this.presetVal);
    },
    formatTime(date) {
      // 格式化日期时间为字符串，例如 "HH:mm"
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      return `${hours}:${minutes}`;
    },
    handleSetTimeClick() {
      this.timeparams = [];
      this.timeList.forEach((time, index) => {
        if (this.selectedValues[index] !== undefined) {
          // 直接向数组中添加一个新对象
          this.timeparams.push({
            time: this.formatTime(time),
            preset: this.selectedValues[index],
          });
        }
      });
      console.log(this.timeparams);
      this.getsetTimeFun();
    },
    getsetTimeFun() {
      getTermStatus({ termId: this.deviceData.id }).then((res) => {
        console.log(res);
        if (res.data.isonline) {
          console.log(this.channelVal, this.setNum, this.deviceData.protocol);
          let params = [
            {
              name: "act",
              value: "schedule",
            },
            {
              name: "udp",
              value: 1,
            },
            {
              name: "flag",
              value: 1,
            },
            {
              name: "channel",
              value: this.channelVal,
            },
          ];

          if (
            this.deviceData.protocol == "65283" ||
            this.deviceData.protocol == "65285" ||
            this.deviceData.protocol == "65290" ||
            this.deviceData.protocol == "65298"
          ) {
            //我是时间间隔
            let timeArr = [];
            console.log("我是其它，时间间隔");
            console.log(this.timeValue);
            console.log(this.timeNum);
            var Stime = this.$moment(this.timeValue[0], "HH:mm").format(
              "YYYY-MM-DD HH:mm:ss"
            );
            //结束时间不添加偏移量
            var Etime = this.$moment(this.timeValue[1], "HH:mm").format(
              "YYYY-MM-DD HH:mm:ss"
            );
            var spanTime = this.timeNum;
            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);
            let group = timeArr.length;
            params.push({
              name: "group",
              value: group,
            });
            let timeArrList = [];
            for (var k = 0; k < timeArr.length; k++) {
              //console.log(moment(dayArr[k]).hour());
              timeArrList.push({
                hour: this.$moment(timeArr[k]).hour(),
                minute: this.$moment(timeArr[k]).minute(),
                preset: 255,
              });
            }
            console.log(timeArrList);
            for (let m = 0; m < timeArrList.length; m++) {
              console.log(timeArrList[m]);
              params.push(
                {
                  name: "hour" + (m + 1),
                  value: timeArrList[m].hour,
                },
                {
                  name: "min" + (m + 1),
                  value: timeArrList[m].minute,
                },
                {
                  name: "preset" + (m + 1),
                  value: timeArrList[m].preset,
                }
              );
            }
          } else {
            let group = this.timeparams.length;
            params.push({
              name: "group",
              value: group,
            });
            //时间点下发拍照时间表
            for (let m = 0; m < this.timeparams.length; m++) {
              console.log(this.timeparams[m].time);
              let time = this.$moment(this.timeparams[m].time, "HH:mm"); // 使用 moment 库解析时间点
              console.log(time);
              params.push(
                {
                  name: "hour" + (m + 1),
                  value: time.hour(),
                },
                {
                  name: "min" + (m + 1),
                  value: time.minute(),
                },
                {
                  name: "preset" + (m + 1),
                  value: this.timeparams[m].preset,
                }
              );
            }
            console.log(params);
            let timeArrList = [];
            for (var k = 0; k < this.timeparams.length; k++) {
              //console.log(moment(dayArr[k]).hour());
              console.log(this.timeparams[k].time);
              let time = this.$moment(this.timeparams[k].time, "HH:mm"); // 使用 moment 库解析时间点
              console.log(time);
              timeArrList.push({
                hour: time.hour(),
                minute: time.minute(),
                preset: this.timeparams[k].preset,
              });
            }
            console.log(timeArrList);
            var parmsobj = {
              termid: this.deviceData.id,
              channelid: this.channelVal,
              list: timeArrList,
            };
          }

          console.log(params);

          this.setTermFnRule(params);
        } else {
          this.sureloading = false;
          this.$message({
            duration: 1500,
            showClose: true,
            message: "装置下线，发送指令失败",
            type: "error",
          });
        }
      });
    },
    //下发时间表
    setTermFnRule(dataParams) {
      setTermCamera({
        termId: this.deviceData.id,
        list: dataParams,
      })
        .then((res) => {
          console.log(res);
          this.requestid = res.data.requestId;
          clearInterval(this.timer);
          this.deviceTimer = window.setInterval(() => {
            this.getinfoRules();
            this.deviceNum++;
            console.log(this.deviceNum, this.deviceNum * 1000);
          }, 1000 * this.deviceNum);
        })
        .catch((err) => {});
    },
    getinfoRules() {
      getTermCameraRequest({ requestid: this.requestid })
        .then((res) => {
          if (res.data.success == 1) {
            this.sureloading = false;
            window.clearInterval(this.deviceTimer);
            this.deviceTimer = null;
            this.deviceNum = 1;
            console.log(JSON.parse(res.data.data));
            this.isShowset = false;
            this.$message({
              duration: 1500,
              showClose: true,
              message: "时间表下发成功",
              type: "success",
            });
            this.dialogVisible = false;
          } else if (this.deviceNum > 9) {
            this.sureloading = false;
            window.clearInterval(this.deviceTimer);
            this.deviceTimer = null;
            this.deviceNum = 1;
            this.failedFlag = true;
            this.$message({
              duration: 1500,
              showClose: true,
              message: "时间表下发失败",
              type: "error",
            });
            this.dialogVisible = false;
          }
        })
        .catch((err) => {});
    },

    //获取装置的时间表
    deviceTimeClick() {
      console.log("点击了获取装置时间表");
      if (this.deviceData.onlinestatus === 1) {
        this.deviceTimeLoading = true;
        let params = [
          {
            name: "act",
            value: "schedule",
          },
          {
            name: "udp",
            value: 1,
          },
          {
            name: "flag",
            value: 0,
          },
          {
            name: "channel",
            value: this.channelVal,
          },
        ];
        this.setTermFn(params);
      } else {
        this.$message({
          duration: 1500,
          showClose: true,
          message: "装置下线，发送指令失败",
          type: "error",
        });
      }
    },
    //装置获取拍照时间表和下发公用接口
    setTermFn(dataParams) {
      console.log("点击了统一的接口", dataParams);
      setTermCamera({
        termId: this.deviceData.id,
        list: dataParams,
      })
        .then((res) => {
          console.log(res);
          this.requestid = res.data.requestId;
          // 清除可能存在的旧定时器
          if (this.deviceTimer) {
            clearInterval(this.deviceTimer);
          }
          // 设置新的定时器，每秒调用一次 getinfo
          this.deviceTimer = window.setInterval(() => {
            this.getinfo();
          }, 1000);
        })
        .catch((err) => {
          if (this.deviceTimer) {
            clearInterval(this.deviceTimer);
            this.deviceTimer = null;
          }
        });
    },
    //获取时间表
    getinfo() {
      getTermCameraRequest({ requestid: this.requestid })
        .then((res) => {
          if (res.data.success == 1) {
            this.deviceTimeLoading = false;
            clearInterval(this.deviceTimer);
            this.deviceTimer = null;
            this.attemptCount = 0; // 重置尝试次数计数器
            console.log(JSON.parse(res.data.data));
            //this.deviceTimeList = JSON.parse(res.data.data).groupData;
            this.processingData(JSON.parse(res.data.data).groupData); //执行数据转化

            this.$message({
              duration: 1500,
              showClose: true,
              message: "装置时间表已更新",
              type: "success",
            });
          } else {
            this.attemptCount++; // 尝试次数加1
            if (this.attemptCount >= this.maxAttempts) {
              // 达到最大尝试次数，停止定时器并显示错误消息
              clearInterval(this.deviceTimer);
              this.deviceTimer = null;
              this.deviceTimeLoading = false;
              this.$message({
                duration: 1500,
                showClose: true,
                message: "查询失败",
                type: "error",
              });
            }
          }
        })
        .catch((err) => {});
    },
    //根据规约处理时间表数据
    processingData(val) {
      console.log(this.deviceData.protocol);
      if (
        this.deviceData.protocol == "65283" ||
        this.deviceData.protocol == "65285" ||
        this.deviceData.protocol == "65290" ||
        this.deviceData.protocol == "65298"
      ) {
        //湖南规约
        console.log("湖南");
        console.log(val);
        var hnarr = [];
        for (var i = 0; i < val.length; i++) {
          if (i % 3 == 0) {
            var hnobj = {};
            hnobj.span = val[i].hour * 60 + val[i].minute;
            console.log("时间间隔");
          } else if (i % 3 == 1) {
            console.log("开始时间");
            console.log("a");
            hnobj.startTime = this.$moment(val[i]).format("HH:mm");
          } else if (i % 3 == 2) {
            console.log("结束时间");
            hnobj.endTime = this.$moment(val[i]).format("HH:mm");
            hnarr.push(hnobj);
          }
        }
        console.log("222222222222222222");
        console.log(hnarr);
        console.log("22222222222222222222222");
        let dayArr = [];
        //根据开始时间结束时间生产数组
        for (let k = 0; k < hnarr.length; k++) {
          console.log(hnarr[k].startTime);
          console.log(hnarr[k].endTime);
          console.log(hnarr[k].span);
          let Stime = this.$moment(hnarr[k].startTime, "HH:mm").format(
            "YYYY-MM-DD HH:mm:ss"
          );

          let Etime = this.$moment(hnarr[k].endTime, "HH:mm").format(
            "YYYY-MM-DD HH:mm:ss"
          );
          let spanTime = hnarr[k].span;
          if (this.$moment(Etime).isBefore(this.$moment(Stime))) {
            let zeroEnd = this.$moment("23:59", "HH:mm").format(
              "YYYY-MM-DD HH:mm:ss"
            );
            let zeroStart = this.$moment("00:00", "HH:mm").format(
              "YYYY-MM-DD HH:mm:ss"
            );
            while (
              this.$moment(Stime).isBefore(this.$moment(zeroEnd)) ||
              this.$moment(Stime).isSame(this.$moment(zeroEnd))
            ) {
              dayArr.push(Stime);
              Stime = this.$moment(Stime)
                .add(spanTime, "minute")
                .format("YYYY-MM-DD HH:mm:ss");
            }
            while (
              this.$moment(zeroStart).isBefore(this.$moment(Etime)) ||
              this.$moment(zeroStart).isSame(this.$moment(Etime))
            ) {
              dayArr.push(zeroStart);
              zeroStart = this.$moment(zeroStart)
                .add(spanTime, "minute")
                .format("YYYY-MM-DD HH:mm:ss");
            }
          } else {
            while (
              this.$moment(Stime).isBefore(this.$moment(Etime)) ||
              this.$moment(Stime).isSame(this.$moment(Etime))
            ) {
              dayArr.push(Stime);
              Stime = this.$moment(Stime)
                .add(spanTime, "minute")
                .format("YYYY-MM-DD HH:mm:ss");
            }
          }

          // // 将结束日期的天放进数组
          console.log(dayArr);
        }
        this.deviceTimeList = [...new Set(dayArr)];
      } else {
        //其他规约
        this.deviceTimeList = val;
      }
    },
    closeTimeFun() {
      this.dialogVisible = false;
      this.timeList = [];
      this.deviceTimeList = [];
    },
  },
};
</script>
<style lang="less">
.setTime {
  .setBox {
    .head {
      display: flex;
      align-items: center;
      //justify-content: space-around;
      h3 {
        margin-bottom: 0px;
      }
      .channelDiv {
        width: 120px;
        margin-right: 12px;
      }
      .el-date-editor {
        width: 220px;
      }
      .timespan {
        margin-left: 12px;
      }
      .showList {
        margin-left: 12px;
        width: 90px !important;
        margin-bottom: 0px !important;
      }
      .serachBtn {
        margin-left: 8px !important;
        width: 60px !important;
        margin-bottom: 0px !important;
      }
    }
    .contain {
      height: 410px;
      margin-top: 20px;
      display: flex;
      ul {
        display: flex;
        flex-wrap: wrap;
        align-content: flex-start; //加这个属性就能解决
        overflow: auto;
        height: 410px;
        width: 60%;
        li {
          width: 200px;
          list-style: none;
          height: 40px;
          line-height: 40px;
          .el-input {
            width: 80px;
            margin-left: 12px;
          }
        }
      }
      .tagsBox {
        width: 40%;
        overflow: auto;
        height: 410px;
        .el-tag {
          margin-bottom: 12px;
          margin-right: 12px;
        }
      }
    }
  }
}
</style>
