<template>
  <div class="app-container policy-flex" v-loading="loading">
    <div
      class="policy"
      :class="{ 'radio-style': hasRadioInput(item.values) }"
      v-for="(item, index) in policyList"
      :key="index"
    >
      <div class="policy-title">{{ item.name }}</div>
      <div
        class="policy-li"
        v-for="(children, index) in item.values"
        :key="index + 1"
      >
        <template v-if="children.inputType === 'text'">
          <div>{{ children.pointName }}:</div>
          <div class="right-data">
            <el-input
              v-if="children.inputType === 'text'"
              v-model="children.curValue"
              placeholder="请输入"
              size="mini"
              @keyup.enter.native="handleEnter(children, $event)"
              @input="handleInput(children)"
              @blur="handleBlur()"
            ></el-input>
            <div class="unit">{{ children.unit }}</div>
          </div>
        </template>
        <template v-if="children.inputType === 'select'">
          <div>{{ children.pointName }}:</div>
          <div class="right-data">
            <el-select
              v-model="children.curValue"
              placeholder="请选择"
              size="mini"
              ref="selectRef"
              @change="selectThink(children)"
              @visible-change="
                (visible) => handleVisibleChange(visible, children)
              "
            >
              <el-option
                v-for="option in getOptions(children.min, children.max)"
                :key="option"
                :label="option.toString()"
                :value="option"
              >
              </el-option>
            </el-select>
            <div class="unit">{{ children.unit }}</div>
          </div>
        </template>
        <template v-if="children.inputType === 'radio'">
          <div class="right-data">
            <el-radio-group
              v-model="children.curValue"
              @change="handleRadioChange(children, item)"
            >
              <el-radio border :label="children.pointName">{{
                children.pointName
              }}</el-radio>
            </el-radio-group>
          </div>
        </template>
      </div>
      <div v-if="item.name === '自动模式选择'" class="tips-text">
        注:请停机状态下选择
      </div>
    </div>
  </div>
</template>

<script>
import { policyListData } from "@/api/centerairC/strategy";
import { operationConrol } from "@/api/hotWater/waterControl";
export default {
  name: "deviceStrategy",
  data() {
    return {
      loading: false,
      policyList: [],
      policyDetails: [],
      value: "",
      // 用于存储选择前的值
      oldValue: null,
    };
  },
  mounted() {
    this.getPolicyList();
  },
  methods: {
    // select数组
    getOptions(min, max) {
      const options = [];
      for (let i = min; i <= max; i++) {
        options.push(i);
      }
      return options;
    },
    // 如果有radio,则需要改变policy类名的样式了
    hasRadioInput(values) {
      return values.some((child) => child.inputType === "radio");
    },
    // 请求列表
    getPolicyList() {
      return new Promise((resolve, reject) => {
        let data = {
          systemType: "0",
          funPolicyType: "1",
        };
        policyListData(data)
          .then((res) => {
            console.log("策略返回res", res);
            if (res.code == 200) {
              this.policyList = res.rows;
              this.initRadioSelection();
            } else {
              this.policyList = [];
            }
            // 成功时解析 Promise
            resolve(res);
          })
          .catch((error) => {
            // 失败时拒绝 Promise
            reject(error);
          });
      });
    },
    // 处理select下拉框显示或隐藏事件
    handleVisibleChange(visible, children) {
      if (visible) {
        // 当下拉框打开时保存原值
        this.$set(children, "_oldValue", children.curValue);
      }
    },
    // 处理select的选中值
    selectThink(children) {
      const oldValue = children._oldValue;
      this.$confirm(
        `确定要修改"${children.pointName}"的数据为:${children.curValue}吗?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          this.hadleOperationConrol(children.cpmId, children.curValue);
        })
        .catch(() => {
          // 用户取消操作，恢复原来的值
          children.curValue = oldValue;
        });
    },
    // 当select下拉框显示或隐藏时触发
    handleSelectVisibleChange(val, visible) {
      if (visible) {
        // 下拉框显示时，保存当前的值
        this.oldValue = val;
        console.log("显示的旧值", this.oldValue);
      }
      return val;
    },
    // 处理初始页面时候radio的默认选中值
    initRadioSelection() {
      this.policyList.forEach((item) => {
        item.values.forEach((children) => {
          if (children.inputType === "radio") {
            if (Number(children.curValue) == 0) {
              // console.log("当前项是0", children.curValue);
              children.curValue = null; // 设置为 null 确保 radio 不选中
            } else {
              console.log("当前项是1", children.curValue);
              const selectedOption = item.values.find(
                (option) => option.curValue === 1
              );
              // 选中当前的pointName
              if (selectedOption) {
                children.curValue = selectedOption.pointName;
              }
            }
          }
        });
      });
    },
    // 处理输入事件，过滤非数字字符
    handleInput(children) {
      console.log("校验");
      // 实时校验并过滤非数字和非小数点字符
      children.curValue = String(children.curValue).replace(/[^\d.]/g, "");
      // 确保只有一个小数点
      const parts = children.curValue.split(".");
      if (parts.length > 2) {
        // 如果有多个小数点，只保留第一个小数点及之前的部分和第一个小数点之后的部分
        children.curValue = parts[0] + "." + parts[1];
      }
      // 确保小数点后最多两位
      if (parts.length === 2) {
        children.curValue = parts[0] + "." + parts[1].slice(0, 2);
      }
    },
    // 失去焦点
    handleBlur() {
      // this.currentFocusIndex = "";
    },
    handleEnter(children, event) {
      console.log("请求后端", children);
      // 失去焦点
      event.target.blur();
      this.$confirm(
        `确定要修改"${children.pointName}"的数据为:${children.curValue} ${children.unit}吗?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          this.hadleOperationConrol(children.cpmId, children.curValue);
        })
        .catch(() => {
          // 用户取消操作，需要更新原来的频率
          // this.getOperationList();
        });
    },
    handleRadioChange(children, item) {
      if (children.curValue === "定时模式") {
        // 请求设备定时开关的列表数据,保证定时设置有开启状态
        let data = {
          systemType: "0",
          funPolicyType: "3",
        };
        policyListData(data)
          .then((res) => {
            console.log("策略返回res", res);
            if (res.code == 200) {
              let timeList = res.rows;
              // 定义一个函数来检查 timeList 中是否存在符合条件的对象
              function checkTimeList() {
                for (let i = 0; i < timeList.length; i++) {
                  let values = timeList[i].values;
                  for (let j = 0; j < values.length; j++) {
                    if (
                      values[j].pointName === "启动标志" &&
                      values[j].curValue === 1
                    ) {
                      return true;
                    }
                  }
                }
                return false;
              }
              // 调用函数并获取结果
              let result = checkTimeList();
              console.log("是否有开启的标志", result);
              if (result) {
                // 有开启标志的话就可以开启定时模式
                this.$confirm(
                  `确定要修改"${item.name}"的数据为:${children.curValue} ${children.unit}吗?`,
                  "提示",
                  {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                  }
                )
                  .then(() => {
                    console.log("children.curValue", children.curValue);
                    if (children.curValue) {
                      this.hadleOperationConrol(children.cpmId, "2");
                    }
                  })
                  .catch(() => {
                    // 用户取消操作，需要更新原来的数据
                    children.curValue = "0";
                  });
              } else {
                this.$confirm(
                  `当前设备定时开关都为停用状态,是否去开启?`,
                  "提示",
                  {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                  }
                )
                  .then(() => {
                    // 没有开启标志的话就跳转到设备定时开关去开启
                    this.$router.push("/centerairC/strategy/timeSwitch");
                  })
                  .catch(() => {
                    // 用户取消操作，需要更新原来的数据
                    children.curValue = "0";
                  });
              }
            }
          })
          .catch((error) => {});
      } else {
        this.$confirm(
          `确定要修改"${item.name}"的数据为:${children.curValue} ${children.unit}吗?`,
          "提示",
          {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          }
        )
          .then(() => {
            console.log("children.curValue", children.curValue);
            if (children.curValue) {
              this.hadleOperationConrol(children.cpmId, "1");
            }
          })
          .catch(() => {
            // 用户取消操作，需要更新原来的数据
            children.curValue = "0";
          });
      }
    },
    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;
              });
            }, 5000);
          } else {
            // this.$modal.msgError("操作失败");
            console.log("应该更新状态的");
            // 更新所有设备状态;
            this.getPolicyList();
          }
        })
        .catch((error) => {
          console.log("请求发生错误，更新设备状态", error);
          // 更新所有设备状态;
          this.getPolicyList();
        });
    },
  },
};
</script>

<style lang="scss" scoped>
.policy-flex {
  margin-top: 15px;
  width: 100%;
  display: flex;
  flex-direction: row;
  flex-wrap: wrap;
  .policy {
    display: flex;
    flex-direction: column;
    position: relative;
    width: calc(33.33% - 40px);
    margin: 0 20px;
    min-height: 350px;
    background-image: url(../../../assets/images/strategy-border.png);
    background-size: 100% 100%;
    border-bottom: 1px solid #1587cc;
    border-left: 1px solid #1587cc;
    margin-bottom: 25px;
    padding: 70px 60px 20px 40px;
    .policy-title {
      font-size: 0.18rem;
      font-weight: bold;
      position: absolute;
      top: 18px;
      left: 25px;
      margin-bottom: 20px;
    }
    .policy-li {
      display: flex;
      flex-direction: row;
      align-items: center;
      justify-content: space-between;
      z-index: 0;
      font-size: 0.16rem;
      color: #94b8ce;
      margin-bottom: 10px;
      .right-data {
        display: flex;
        flex-direction: row;
        align-items: center;
        justify-content: flex-start;
        flex-wrap: wrap;
        // max-width: 2.5rem;
        .unit {
          width: 25px;
          white-space: nowrap;
        }
      }
      .el-input {
        width: 80px !important;
        margin: 0 15px 0 5px;
      }
      .el-select {
        width: 80px !important;
        margin: 0 15px 0 5px;
      }
      .tips-text {
        font-size: 14px;
      }
    }
  }
  .radio-style {
    display: flex;
    flex-direction: row !important;
    align-items: flex-start !important;
    flex-wrap: wrap;
    align-content: flex-start; /* 调整多行元素的对齐方式 */
    .policy-li {
      margin: 10px;
      width: calc(50% - 20px) !important;
    }
  }
}
@media (min-width: 1560px) and (max-width: 1670px) {
  .policy {
    padding: 70px 0.3rem 20px 40px !important;
  }
}
@media (min-width: 1400px) and (max-width: 1560px) {
  .policy {
    padding: 70px 0.3rem 20px 40px !important;
    width: calc(33.33% - 20px) !important;
    margin: 0 10px 25px 10px !important;
  }
  .policy-li {
    font-size: 14px !important;
  }
}
@media (min-width: 1340px) and (max-width: 1400px) {
  .policy {
    padding: 70px 0.3rem 20px 40px !important;
    width: calc(33.33% - 20px) !important;
    margin: 0 10px 25px 10px !important;
  }
  .policy-li {
    font-size: 14px !important;
  }
  .radio-style {
    padding: 70px 0.3rem 20px 20px !important;
    .policy-li {
      width: calc(50% - 20px) !important;
    }
  }
}
@media (min-width: 1025px) and (max-width: 1340px) {
  .policy {
    width: calc(49% - 20px) !important;
    margin: 0 10px 25px 10px !important;
    padding: 70px 30px 15px 40px !important;
  }
  .policy-title {
    font-size: 16px !important;
  }
  .policy-li {
    font-size: 14px !important;
  }
}
@media (max-width: 1240px) {
  .policy {
    width: calc(80% - 20px) !important;
    margin: 0 10px 25px 10px !important;
    padding: 70px 60px 15px 40px !important;
  }
  .policy-title {
    font-size: 16px !important;
    left: 40px !important;
  }
  .policy-li {
    font-size: 14px !important;
  }
}
// 媒体查询，适配大于2000px分辨率的大屏样式
@media (min-width: 2000px) {
  .policy-flex {
    margin-top: 0.15rem !important;
  }
  .policy-flex .policy {
    min-height: 3.5rem !important;
    margin-bottom: 0.2rem !important;
    padding: 0.7rem 0.6rem 0.2rem 0.4rem !important;
  }
  .policy-flex .policy .policy-title {
    font-size: 0.18rem;
    top: 0.18rem !important;
    left: 0.25rem !important;
    margin-bottom: 0.2rem !important;
  }
  .policy-flex .policy .policy-li {
    margin-bottom: 0.1rem !important;
  }
  .policy-flex .policy .policy-li .el-input {
    width: 0.8rem !important;
    margin: 0 0.15rem 0 0.05rem !important;
  }
  .policy-flex .policy .policy-li .right-data .unit {
    width: 0.25rem !important;
  }
  .policy-flex .policy .policy-li .el-select {
    width: 0.8rem !important;
    margin: 0 0.15rem 0 0.05rem !important;
  }
  .tips-text {
    font-size: 0.14rem !important;
  }
  .policy-li .el-radio {
    margin-bottom: 0.05rem !important;
}
}
</style>
<style scoped>
.policy-li >>> .el-input__inner {
  background-color: #04193a;
  border: 1px solid #1262db;
  color: #3ef0fd;
  font-weight: 700;
  text-align: center;
  padding: 0 0.1rem !important;
}
.policy-li >>> .el-radio {
  margin-bottom: 5px;
}
.policy-li >>> .el-radio__label {
  color: #3ef0fd;
}
.policy-li >>> .el-radio__inner {
  border: 1px solid #042063;
  /* background-color: transparent !important; */
}
.policy-li >>> .el-radio.is-bordered {
  border: 1px solid #2c6afa;
}
</style>
