<template>
  <div class="setTime">
    <el-dialog
      title="选择拍照时间表"
      :visible.sync="dialogVisible"
      width="1100px"
    >
      <div class="setBox">
        <div class="head">
          <div class="left">
            <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>
          </div>
          <div class="left">
            <el-button type="primary" class="serachBtn" @click="deviceTimeClick"
              >查询</el-button
            ><span class="timeTotal">({{ deviceTimeList.length }})</span>
          </div>
        </div>
        <div class="contain">
          <div class="xfTime">
            <div class="timelist">
              <ul>
                <li
                  v-for="(item, index) in timeList"
                  :key="index"
                  @click="deleteTime(index)"
                >
                  <el-tag :type="selectedIndex === index ? 'danger' : ''"
                    >时间点:{{ item.time }} + 预置位:{{ item.preset }}</el-tag
                  >
                </li>
              </ul>
            </div>
            <div class="timeBtnGrop">
              <el-button type="primary" @click="addTimeList">增加</el-button>
              <el-button type="primary" @click="timeFrameVisible = true"
                >批量增加</el-button
              >
              <el-button type="primary" @click="deleteSelectedTime"
                >删除</el-button
              >
              <el-button type="primary" @click="clearAllTime"
                >清除全部</el-button
              >
              <el-button
                type="primary"
                class="xfsjbBtn"
                @click="handleSetTimeClick"
                :loading="sureloading"
                >下发时间表</el-button
              >
            </div>
          </div>
          <div
            class="tagsBox"
            v-loading="timeloading"
            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 class="tagsBox" v-loading="timeloading" v-else>
            <el-empty description="暂无时间表"></el-empty>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeTimeFun">取 消</el-button>
      </span>
      <el-dialog
        width="340px"
        title="拍照时间"
        :visible.sync="timeInnerVisible"
        append-to-body
        class="timeinnerClass"
      >
        <div class="timePoint">
          <div class="timeinput">
            <h3>时间：</h3>
            <el-time-picker
              v-model="timePointVal"
              :picker-options="{
                selectableRange: '00:00:00 - 23:59:59',
              }"
              placeholder="任意时间点"
              default-time="00:00:00"
            >
            </el-time-picker>
          </div>
          <div class="timeprt">
            <h3>预置位：</h3>
            <el-input v-model="presetVal" placeholder="请输入"></el-input>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="timeInnerVisible = false">取 消</el-button>
          <el-button type="primary" @click="sureTime">确 定</el-button>
        </span>
      </el-dialog>
      <el-dialog
        width="340px"
        title="拍照时间范围"
        :visible.sync="timeFrameVisible"
        append-to-body
        class="timeinnerClass"
      >
        <div class="timePoint">
          <div class="timeinput timepick">
            <h3>时间：</h3>
            <el-time-picker
              is-range
              v-model="timeValue"
              range-separator="至"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              placeholder="选择时间范围"
            >
            </el-time-picker>
          </div>
          <div class="timeSpan">
            <h3>间隔：</h3>
            <el-input-number v-model="timeNum"></el-input-number>
          </div>
          <div class="timeprt">
            <h3>预置位：</h3>
            <el-input v-model="presetspanVal" placeholder="请输入"></el-input>
          </div>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="timeFrameVisible = false">取 消</el-button>
          <el-button type="primary" @click="surepickTime">确 定</el-button>
        </span>
      </el-dialog>
    </el-dialog>
  </div>
</template>
<script>
import {
  getChannelByTermidJoggle,
  getTermStatus,
  setTermCamera,
  getTermCameraRequest,
} from "@/utils/api/index";
export default {
  data() {
    return {
      timeloading: false,
      deviceData: "", //设备信息
      dialogVisible: false,
      timeList: [], // 存储生成的时间点列表
      channelVal: 1,
      channelListOption: [], //通道数组
      timeInnerVisible: false, //新增时间点弹窗
      presetVal: 255, //默认预置位
      timePointVal: "", //默认时间
      deviceTimeList: [], //查询出来的时间表
      timeparams: [], //点击获取时间点
      deviceTimer: null, //装置循环获取
      deviceNum: 1, //循环次数
      attemptCount: 0, // 新增的尝试次数计数器
      maxAttempts: 9, // 设置最大尝试次数

      timeFrameVisible: false, //批量时间
      timeValue: [], //开始时间，结束时间
      timeNum: 30, //时间间隔
      presetspanVal: 255, //时间间隔预置位

      selectedIndex: null, // 用于存储选中的时间点索引
      sureloading: false,
    };
  },
  mounted() {
    // 获取当前日期
    let today = new Date();
    // 设置今天的零点
    let startOfDay = new Date(today);
    startOfDay.setHours(0, 0, 0, 0); // 将小时、分钟、秒和毫秒均设为0
    this.timePointVal = startOfDay;
    // 获取当前日期
    let todayspan = new Date();
    // 设置今天的零点
    let startOfDayspan = new Date(todayspan);
    startOfDayspan.setHours(0, 0, 0, 0); // 将小时、分钟、秒和毫秒均设为0
    // 设置今天的23点59分59秒
    let endOfDayspan = new Date(todayspan);
    endOfDayspan.setHours(23, 59, 59, 999); // 将小时设为23，分钟设为59，秒设为59，毫秒设为999（或您希望的任意毫秒值）
    // 更新value1数组
    this.timeValue = [startOfDayspan, endOfDayspan];
  },
  methods: {
    display(val) {
      this.dialogVisible = true;
      this.deviceData = val;
      console.log(this.deviceData);
      this.getChannelList();
      this.deviceTimeClick();
    },
    //获取通道的接口
    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); //代码错误、请求失败捕获
        });
    },
    // 点击时间点时触发，记录选中的索引
    deleteTime(index) {
      this.selectedIndex = index;
    },
    // 点击删除按钮时触发，删除选中的时间点
    deleteSelectedTime() {
      if (this.selectedIndex !== null) {
        this.timeList.splice(this.selectedIndex, 1);
        this.selectedIndex = null; // 重置选中的索引
      }
    },
    //添加时间点和预置位
    addTimeList() {
      this.timeInnerVisible = true;
    },
    //优化时间
    formatTime(date) {
      // 格式化日期时间为字符串，例如 "HH:mm"
      const hours = String(date.getHours()).padStart(2, "0");
      const minutes = String(date.getMinutes()).padStart(2, "0");
      return `${hours}:${minutes}`;
    },
    //保存当前时间点位
    sureTime() {
      console.log(this.timePointVal, this.presetVal);

      // 格式化时间
      const newTime = this.formatTime(this.timePointVal);
      const newPreset = this.presetVal;

      // 检查是否已经存在相同的时间点和预置位
      const isDuplicate = this.timeList.some(
        (item) => item.time === newTime && item.preset === newPreset
      );

      // 如果没有重复，则添加到 timeList
      if (!isDuplicate) {
        this.timeList.push({
          time: newTime,
          preset: newPreset,
        });
      } else {
        this.$message({
          duration: 1500,
          showClose: true,
          message: "重复的时间点和预置位，未添加到列表中",
          type: "warning",
        });
      }
      // console.log(this.timePointVal, this.presetVal);
      // this.timeList.push({
      //   time: this.formatTime(this.timePointVal),
      //   preset: this.presetVal,
      // });
      this.timeInnerVisible = false;
    },
    //时间间隔生成时间点
    surepickTime() {
      // 获取时间间隔的毫秒数
      const intervalMs = this.timeNum * 60 * 1000;
      // 克隆开始时间，避免修改原始timeValue数组中的startOfDay对象
      let currentTime = new Date(this.timeValue[0]);
      // let currentTime = this.timeValue[0];
      // 循环生成时间点，直到达到或超过结束时间
      console.log(currentTime);
      console.log(this.timeValue[0]);
      console.log(this.timeValue[1]);
      console.log(this.timeValue);
      while (currentTime <= this.timeValue[1]) {
        // 将当前时间点添加到列表中
        this.timeList.push({
          time: this.formatTime(currentTime),
          preset: this.presetspanVal,
        });
        // 增加时间间隔
        currentTime.setTime(currentTime.getTime() + intervalMs);
      }
      // 打印时间点列表到控制台（可选）

      console.log(this.timeList);
      this.timeFrameVisible = false;
    },

    handleSetTimeClick() {
      this.sureloading = true;
      this.timeparams = [];
      this.timeList.forEach((time) => {
        // 直接向数组中添加一个新对象
        this.timeparams.push({
          time: time.time,
          preset: time.preset,
        });
      });
      this.timeparams = this.timeparams.reduce((acc, current) => {
        const key = `${current.time}-${current.preset}`; // 生成唯一键
        if (!acc.some((item) => `${item.time}-${item.preset}` === key)) {
          acc.push(current); // 添加到结果数组
        }
        return acc;
      }, []);
      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.$message({
              duration: 1500,
              showClose: true,
              message: "时间表下发成功",
              type: "success",
            });
            this.dialogVisible = false;
            this.closeTimeFun();
          } else if (this.deviceNum > 9) {
            this.sureloading = false;
            window.clearInterval(this.deviceTimer);
            this.deviceTimer = null;
            this.deviceNum = 1;
            this.$message({
              duration: 1500,
              showClose: true,
              message: "时间表下发失败",
              type: "error",
            });
            this.dialogVisible = false;
            this.closeTimeFun();
          }
        })
        .catch((err) => {});
    },
    //查询
    //获取装置的时间表
    deviceTimeClick() {
      console.log("点击了获取装置时间表");
      this.timeloading = true;
      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;
            this.timeloading = 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.timeloading = false;

              this.$message({
                duration: 1500,
                showClose: true,
                message: "查询失败",
                type: "error",
              });
              this.deviceTimeList = [];
            }
          }
        })
        .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;
      }
    },
    clearAllTime() {
      this.timeList = [];
      this.timeparams = [];
      this.deviceTimeList = [];
      this.selectedIndex = null;
    },
    closeTimeFun() {
      this.dialogVisible = false;
      this.timeList = [];
      this.deviceTimeList = [];
      this.timeparams = [];
      this.selectedIndex = null;
    },
  },
};
</script>
<style lang="less">
.setTime {
  .setBox {
    .head {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .left,
      .right {
        display: flex;
        align-items: center;
      }
      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;
      }
      .timeTotal {
        margin-left: 12px;
      }
    }
    .contain {
      height: 410px;
      margin-top: 20px;
      display: flex;
      width: 100%;
      .xfTime {
        width: 670px;
        display: flex;
        border: 1px solid #e0e0e0;
        border-radius: 4px;
        box-sizing: border-box;
        .timelist {
          width: 530px;
          border-right: 1px solid #e0e0e0;
          padding: 12px;
          padding-right: 0px;
          ul {
            display: flex;
            flex-wrap: wrap;
            align-content: flex-start; //加这个属性就能解决
            overflow: auto;
            height: 390px;
            //width: 60%;
            li {
              width: 174px;
              list-style: none;
              height: 40px;
              line-height: 40px;
              .el-input {
                width: 80px;
                margin-left: 12px;
              }
            }
          }
        }
        .timeBtnGrop {
          display: flex;
          flex-direction: column;
          margin-top: 12px;

          .el-button {
            width: 94px;
            margin-left: 6px;
          }
          .xfsjbBtn {
            justify-items: end;
            margin-top: auto;
          }
        }
      }
      .tagsBox {
        width: 390px;
        margin-left: 20px;
        overflow: auto;
        height: 410px;
        border: 1px solid #e0e0e0;
        .el-tag {
          margin-bottom: 12px;
          margin-right: 12px;
        }
      }
    }
  }
}
.timeinnerClass {
  .timePoint {
    .timeinput {
      display: flex;
      align-items: center;
      margin-bottom: 12px;
      h3 {
        font-weight: normal;
        width: 80px;
      }
    }
    .timepick {
      .el-date-editor {
        width: 220px;
      }
    }
    .timeSpan {
      display: flex;
      align-items: center;
      margin-bottom: 12px;
      h3 {
        font-weight: normal;
        width: 80px;
      }
    }
    .timeprt {
      display: flex;
      align-items: center;

      h3 {
        font-weight: normal;
        width: 80px;
      }
      .el-input {
        width: 220px;
      }
    }
  }
}
</style>
