<template>
  <div class="app-container" v-loading="loading">
    <img
      class="right-line"
      src="../../../assets/images/right_line.png"
      alt=""
    />
    <div class="delay-title">定时开关机功能</div>
    <div class="device-container">
      <div class="device-li">
        <div class="device-name">定时名称</div>
        <div class="device-name">定时开机</div>
        <div class="device-name">定时关机</div>
        <div class="device-name">启动状态</div>
      </div>
      <div class="device-li" v-for="(item, index) in delayList" :key="index">
        <div class="device-name">{{ item.name }}</div>
        <div class="device-name">
          <el-input
            size="mini"
            v-model="item.delayOpenHour"
            @keyup.enter.native="handleEnter(item, 'openHour')"
            @input="handleInput(item, 'delayOpenHour', 'hour')"
          ></el-input>
          <div class="slip">:</div>
          <el-input
            size="mini"
            v-model="item.delayOpenMinute"
            @keyup.enter.native="handleEnter(item, 'openMinute')"
            @input="handleInput(item, 'delayOpenMinute', 'minute')"
          ></el-input>
        </div>
        <div class="device-name">
          <el-input
            size="mini"
            v-model="item.delayCloseHour"
            @keyup.enter.native="handleEnter(item, 'closeHour')"
            @input="handleInput(item, 'delayCloseHour', 'hour')"
          ></el-input>
          <div class="slip">:</div>
          <el-input
            size="mini"
            v-model="item.delayCloseMinute"
            @keyup.enter.native="handleEnter(item, 'closeMinute')"
            @input="handleInput(item, 'delayCloseMinute', 'minute')"
          ></el-input>
        </div>
        <div class="device-name">
          <el-switch
            style="display: block"
            active-color="#13ce66"
            inactive-color="#ff4949"
            active-text="开启"
            inactive-text="禁用"
            v-model="item.delayStatus"
            @change="handleStatus(item)"
          >
          </el-switch>
        </div>
      </div>
    </div>
    <img class="left-line" src="../../../assets/images/left_line.png" alt="" />
  </div>
</template>

<script>
import { policyListData } from "@/api/centerairC/strategy";
import { operationConrol } from "@/api/centerairC/sysMonitor";
export default {
  data() {
    return {
      loading: false,
      delayList: [],
    };
  },
  mounted() {
    this.getPolicyList();
  },
  methods: {
    // 请求列表
    getPolicyList() {
      return new Promise((resolve, reject) => {
        let data = {
          systemType: "0",
          funPolicyType: "3",
        };
        policyListData(data)
          .then((res) => {
            console.log("设备定时开关返回res", res);
            if (res.code === 200) {
              let handleList = res.rows;
              this.delayList = [];
              handleList.forEach((element, index) => {
                if (element.values && element.values.length > 0) {
                  // 初始化一个空对象来存储非蝶阀处理后的结果
                  let delayItem = {
                    name: element.name,
                  };
                  const limitedChildren = element.values;
                  limitedChildren.forEach((child) => {
                    // console.log("定时${index}开_时", `定时${index}开_时`);
                    // console.log("child.pointName", child.pointName);
                    if (child.pointName) {
                      // 定时开机-小时
                      if (child.pointName == `定时${index + 1}开_时`) {
                        // console.log("定时开机-时·························");
                        delayItem.delayOpenHour = child.curValue;
                        delayItem.delayOpenHourId = child.cpmId;
                      }
                      //   定时开机-分钟
                      else if (
                        child.pointName.includes(`定时${index + 1}开_分`)
                      ) {
                        delayItem.delayOpenMinute = child.curValue;
                        delayItem.delayOpenMinuteId = child.cpmId;
                      }
                      // 定时关机-小时
                      else if (
                        child.pointName.includes(`定时${index + 1}关_时`)
                      ) {
                        delayItem.delayCloseHour = child.curValue;
                        delayItem.delayCloseHourId = child.cpmId;
                      }
                      //   定时关机-分钟
                      else if (
                        child.pointName.includes(`定时${index + 1}关_分`)
                      ) {
                        delayItem.delayCloseMinute = child.curValue;
                        delayItem.delayCloseMinuteId = child.cpmId;
                      }
                      // 启动状态
                      else if (child.pointName.includes(`启动标志`)) {
                        delayItem.delayStatus =
                          Number(child.curValue) == 0 ? false : true;
                        delayItem.delayStatusId = child.cpmId;
                      }
                    }
                  });
                  // 将处理后的对象添加到 delayList 中
                  if (Object.keys(delayItem).length > 1) {
                    this.delayList.push(delayItem);
                  }
                }
              });
              console.log("处理后的数组", this.delayList);
              //   this.delayList = res.rows;
            } else {
              this.delayList = [];
            }
            // 成功时解析 Promise
            resolve(res);
          })
          .catch((error) => {
            // 失败时拒绝 Promise
            reject(error);
          });
      });
    },

    // 处理输入事件，过滤非数字字符
    handleInput(item, propertyName, name) {
      console.log("校验", item[propertyName]);
      // 如果值为空，不进行后续校验
      if (item[propertyName] === "") {
        return;
      }
      let isValid = true;
      // 实时校验并过滤非数字字符
      let inputValue = String(item[propertyName]).replace(/[^\d]/g, "");
      if (name === "hour") {
        isValid =
          !isNaN(inputValue) &&
          parseInt(inputValue) >= 0 &&
          parseInt(inputValue) <= 23;
        if (!isValid) {
          this.$message.error("输入值在0-23区间，请重新输入");
          item[propertyName] = "";
          return;
        }
      } else if (name === "minute") {
        isValid =
          !isNaN(inputValue) &&
          parseInt(inputValue) >= 0 &&
          parseInt(inputValue) <= 59;
        if (!isValid) {
          this.$message.error("输入值在0-59区间，请重新输入");
          item[propertyName] = "";
          return;
        }
      }
      item[propertyName] = inputValue;
    },
    handleEnter(item, name) {
      let id = "";
      let value = "";
      let title = "";
      let unit = "";
      if (name === "openHour") {
        id = item.delayOpenHourId;
        value = item.delayOpenHour;
        title = "定时开机-小时";
        unit = "时";
      } else if (name === "openMinute") {
        id = item.delayOpenMinuteId;
        value = item.delayOpenMinute;
        title = "定时开机-分钟";
        unit = "分";
      } else if (name === "closeHour") {
        id = item.delayCloseHourId;
        value = item.delayCloseHour;
        title = "定时关机-小时";
        unit = "时";
      } else if (name === "closeMinute") {
        id = item.delayCloseMinuteId;
        value = item.delayCloseMinute;
        title = "定时关机-分钟";
        unit = "分";
      }

      if (value === "") {
        this.$message.warning("请输入当前设置值!");
        return;
      }
      console.log("请求后端", item);
      this.$confirm(
        `确定要把"${item.name}"的${title}设置为:${value} ${unit}吗?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          this.hadleOperationConrol(id, value);
        })
        .catch(() => {
          // 用户取消操作，需要更新原来的频率
          this.getPolicyList();
        });
    },
    hadleOperationConrol(id, param) {
      let data = {
        id: id,
        param: param,
      };
      console.log("操作参数", data);
      operationConrol([data])
        .then((res) => {
          if (res.code == 200) {
            this.$modal.msgSuccess("指令下发成功!");
            // 开启 loading 效果
            this.loading = true;
            // 更新所有设备状态;
            setTimeout(() => {
              this.getPolicyList().finally(() => {
                // 关闭 loading 效果
                this.loading = false;
              });
            }, 6000);
          } else {
            // this.$modal.msgError("操作失败");
            console.log("应该更新状态的");
            // 更新所有设备状态;
            this.getPolicyList();
          }
        })
        .catch((error) => {
          console.log("请求发生错误，更新设备状态", error);
          // 更新所有设备状态;
          this.getPolicyList();
        });
    },
    // 启用状态
    handleStatus(item) {
      this.$confirm(
        `确定要切换"${item.name}"的状态为:${
          item.delayStatus ? "开启" : "禁用 吗?"
        }`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          // 这里调用请求函数
          console.log("请求后台", item.delayStatus);
          let param = null;
          if (item.delayStatus) {
            param = 1;
          } else {
            param = 0;
          }
          this.hadleOperationConrol(item.delayStatusId, param);
        })
        .catch(() => {
          // 用户取消操作，恢复开关状态
          item.delayStatus = !item.delayStatus;
          console.log("不请求后台");
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.app-container {
  position: relative;
  padding: 0.2rem;
  .delay-title {
    /* 基础样式 */
    display: inline-block;
    padding: 0.1rem;
    font-family: "Arial Rounded MT Bold", sans-serif;
    font-size: 0.18rem;
    font-weight: 700;
    color: #e6f3ff;
    text-shadow: 0 2px 4px rgba(0, 60, 120, 0.4);
    letter-spacing: 2px;
    position: relative;
    overflow: hidden;
    cursor: default;

    /* 双背景叠加 */
    background: linear-gradient(
        65deg,
        rgba(1, 11, 24, 0.8) 0%,
        rgba(36, 91, 146, 0.6) 50%,
        rgba(18, 53, 95, 0.5) 100%
      ),
      linear-gradient(-25deg, #0b274b 20%, #2b4d6b 80%);
    background-blend-mode: overlay;

    /* 动态边框 */
    border: 2px solid;
    border-image: linear-gradient(45deg, #026bbb, transparent) 1;

    /* 主流光动画 */
    &::before {
      content: "";
      position: absolute;
      top: -50%;
      left: -100%;
      width: 250%;
      height: 200%;
      background: linear-gradient(
        60deg,
        transparent 20%,
        rgba(255, 255, 255, 0.3) 50%,
        transparent 80%
      );
      animation: shine 2.5s infinite linear;
    }

    /* 副流光动画 */
    &::after {
      content: "";
      position: absolute;
      top: -30%;
      left: -50%;
      width: 200%;
      height: 160%;
      background: linear-gradient(
        -30deg,
        transparent 30%,
        rgba(255, 255, 255, 0.2) 50%,
        transparent 70%
      );
      animation: shineReverse 3s infinite linear;
      animation-delay: 0.8s;
    }
  }

  /* 主流光动画 */
  @keyframes shine {
    0% {
      transform: translateX(-20%) rotate(60deg);
    }
    100% {
      transform: translateX(120%) rotate(60deg);
    }
  }

  /* 反向副流光 */
  @keyframes shineReverse {
    0% {
      transform: translateX(20%) rotate(-30deg);
    }
    100% {
      transform: translateX(-120%) rotate(-30deg);
    }
  }
  .right-line {
    position: absolute;
    top: 0;
    left: 0;
    width: 1.7rem;
    height: 0.4rem;
  }
  .left-line {
    position: absolute;
    right: 0;
    bottom: 0;
    width: 0.5rem;
    height: 2.2rem;
  }
}
.device-container {
  display: flex;
  flex-direction: column;
  width: 100%;
  min-height: 700px;
  background-color: #142c4e;
  padding: 10px 10px 30px 10px;
  border-radius: 10px;
  .device-li {
    width: 100%;
    display: flex;
    flex-direction: row;
    align-items: center;
    padding: 12px 0;
    color: #abcdfc;
    border-bottom: 1px dashed #0349ac;
    .device-name {
      flex: 1;
      white-space: nowrap;
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: center;
      flex-wrap: nowrap;
      .slip {
        margin: 0 5px;
        color: #1282d8;
        font-weight: bold;
      }
    }
  }
  .device-li:nth-child(1) {
    color: #9ca3af;
  }
}
</style>
<style scoped>
.device-name >>> .el-input {
  width: 80px !important;
}
.device-name >>> .el-input__inner {
  background-color: #04193a;
  border: 1px solid #1262db;
  color: #3ef0fd;
  font-weight: 700;
  text-align: center;
  padding: 0 0.1rem !important;
}
</style>
