<template>
  <div class="main-content">
    <!-- 左侧数据区 -->
    <div class="left">
      <div class="item-class" v-for="item in leftList" :key="item.name">
        <i class="icon" :class="item.icon"></i>
        <span class="item-name" :style="{ color: item.color }">{{
          item.name
        }}</span>
        <span class="item-value">{{ item.value }}</span>
      </div>
      <div class="left-botton">
        <span class="item-name">主控<br />位置</span>
        <span class="item-value">
          <count-to
            :start-val="0"
            :end-val="Number(zgposition)"
            :duration="860"
            :decimals="2"
            separator=","
          />
        </span>
      </div>
    </div>

    <!-- 中央电梯模拟区 -->
    <div class="center">
      <div class="center-box">
        <div class="dianti-target" :style="targetStyle">{{ displayTrend }}</div>
        <div class="dianti-number">
          <p
            v-for="(item, index) in elevatorTimes"
            :key="'diantiNmuber' + index"
          >
            <span>{{ item.name }}</span
            >：<span>{{ item.value }}</span>
          </p>
        </div>
        <div class="dianti-peizhong" :style="counterweightStyle"></div>
        <div
          class="dianti-box"
          :class="{ active: isMoving }"
          :style="elevatorStyle"
        ></div>
        <div class="dianti-louceng" style="top: 290px; left: 526px">
          <div
            class="louceng-item"
            v-for="(floor, index) in floors"
            :key="index"
          >
            {{ floor }}
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧状态区 -->
    <div class="right">
      <div
        class="right-item-class"
        v-for="(item, index) in rightList"
        :key="'right-' + index"
      >
        <div class="left-item-box">{{ item.name }}</div>
        <div class="right-item-box">
          <div
            class="right-item-box-item"
            v-for="(value, subIndex) in [
              item.value1,
              item.value2,
              item.value3,
              item.value4,
            ]"
            :key="'value-' + index + '-' + subIndex"
            :class="{ active: value.status == 1 }"
          >
            {{ value.name }}
          </div>
        </div>
      </div>
      <div class="right-item-botton">
        <div class="title">提升机巡检记录</div>
        <div class="right-item-body">
          <div class="table-header">
            <span v-for="(header, index) in tableHeaders" :key="index">{{
              header
            }}</span>
          </div>
          <div
            class="table-content"
            v-for="(item, index) in tableList"
            :key="'table-' + index"
          >
            <span>{{ item.user_name }}</span>
            <span>{{ item.device_name }}</span>
            <span :class="item.device_state == 0 ? '' : 'red'">{{
              item.device_state == 0 ? "正常" : "异常"
            }}</span>

            <span>{{ parseTime(item.polling_data, "{y}-{m}-{d}") }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import CountTo from "vue-count-to";
import {
  getElevatorData,
  getElevatorTimes,
  getRecentFive,
} from "@/api/tyler/jst";
// 修改位置配置常量（添加中间点容差）
const POSITIONS = [
  {
    name: "去井口",
    value: 0,
    depth: 0,
    glposy: 76,
    pzposy: 673,
    range: [-205, 0],
  },
  {
    name: "去一中",
    value: 1,
    depth: 410,
    glposy: 253,
    pzposy: 578,
    range: [-430, -206],
  },
  {
    name: "去二中",
    value: 2,
    depth: 450,
    glposy: 338,
    pzposy: 491,
    range: [-470, -431],
  },
  {
    name: "去三中",
    value: 3,
    depth: 490,
    glposy: 422,
    pzposy: 415,
    range: [-510, -471],
  },
  {
    name: "去四中",
    value: 4,
    depth: 530,
    glposy: 506,
    pzposy: 325,
    range: [-550, -511],
  },
  {
    name: "去五中",
    value: 5,
    depth: 570,
    glposy: 596,
    pzposy: 156,
    range: [-999, -551],
  },
];
export default {
  components: { CountTo },
  data() {
    return {
      // 数据列表
      leftList: [],
      rightList: [],
      tableList: [],
      // 电梯状态
      zgposition: 0,
      zgtrend: "待命",
      isMoving: false,

      // 动画控制
      animationId: null,
      timer: null,
      source: null, // 新增取消令牌源
      // 位置信息
      currentPos: null,
      targetPos: null,

      // 静态配置
      floors: ["一中", "二中", "三中", "四中", "五中"],
      tableHeaders: ["检查人", "检查设备", "是否正常", "日期"],
      elevatorTimes: [],
    };
  },
  computed: {
    // 电梯状态显示
    displayTrend() {
      return this.zgtrend.includes("待命")
        ? `${this.zgtrend}`
        : `前往：${this.zgtrend}`;
    },
    // 电梯目标样式
    targetStyle() {
      return {
        top: "300px",
        left: "170px",
        backgroundColor: this.zgtrend.includes("待命") ? "#999" : "#fecb00",
      };
    },
    // 电梯位置样式
    elevatorStyle() {
      return this.calculatePosition("glposy");
    },
    // 配重位置样式
    counterweightStyle() {
      return this.calculatePosition("pzposy");
    },
  },
  watch: {},
  created() {
    this.startAutoUpdate(); // 在created中启动定时器
  },
  beforeDestroy() {
    this.clearAnimation();
    if (this.timer) {
      clearInterval(this.timer);
      this.timer = null; // 新增清理引用
    }
  },
  mounted() {
    this.initPositions();
    this.startAutoUpdate();
    // 获取巡检记录
    this.getInspectionRecords();
  },
  methods: {
    // 初始化位置数据
    initPositions() {
      this.currentPos = POSITIONS[0];
      this.targetPos = POSITIONS[0];
    },

    // 计算当前位置
    calculatePosition(type) {
      if (!POSITIONS.length) return { top: "450px", left: "428px" };

      const currentDepth = Number(this.zgposition) || 0;

      // 添加安全判断
      const position =
        (this.zgtrend === "待命"
          ? this.findNearestPosition(currentDepth)
          : this.calculateMovingPosition(type, currentDepth)) || POSITIONS[0];

      return {
        top: `${position[type] || POSITIONS[0][type]}px`, // 添加默认值
        left: type === "glposy" ? "428px" : "365px",
      };
    },

    // 加强查找方法的安全性
    findNearestPosition(depth) {
      console.log(depth, "当前深度");

      // 处理负数区间匹配
      const rangeMatch = POSITIONS.find(
        (p) => depth >= p.range[0] && depth <= p.range[1]
      );
      console.log("负数区间匹配结果:", rangeMatch?.name);

      if (rangeMatch) return rangeMatch;
      console.log("区间匹配结果:", rangeMatch?.name);
      // 无区间匹配时找最近深度（使用原始深度值）
      return POSITIONS.reduce(
        (prev, curr) =>
          Math.abs(curr.depth - Math.abs(depth)) <
          Math.abs(prev.depth - Math.abs(depth))
            ? curr
            : prev,
        POSITIONS[0]
      );
    },

    // 查找最近楼层
    // 统一后的查找方法
    findNearestPosition(depth) {
      console.log("当前深度:", depth);
      // 优先匹配区间范围
      const rangeMatch = POSITIONS.find(
        (p) => depth >= p.range[0] && depth <= p.range[1]
      );
      console.log("区间匹配结果:", rangeMatch?.name);

      if (rangeMatch) return rangeMatch;

      // 无区间匹配时找最近深度
      return POSITIONS.reduce(
        (prev, curr) =>
          Math.abs(curr.depth - depth) < Math.abs(prev.depth - depth)
            ? curr
            : prev,
        POSITIONS[0]
      );
    },

    // 计算移动中的位置
    calculateMovingPosition(type, currentDepth) {
      const nearest = this.findNearestPosition(currentDepth);
      // 添加位置强制更新
      this.currentPos = nearest;
      this.targetPos = this.targetPos;
      const progress = Math.min(
        1,
        Math.abs(currentDepth - nearest.depth) /
          Math.abs(this.targetPos.depth - nearest.depth)
      );

      return {
        ...nearest,
        [type]:
          nearest[type] + (this.targetPos[type] - nearest[type]) * progress,
      };
    },

    // 启动自动更新
    startAutoUpdate() {
      this.clearAnimation();
      this.getdata();

      this.timer = setInterval(this.getdata, 2000);
    },

    // 获取数据
    async getdata() {
      let obj = {
        Shift: "当班次数",
        Today: "当日次数",
        Month: "当月次数",
      };
      try {
        const res = await getElevatorData();
        if (res.code === 200) {
          this.processData(res.rows[0]);
          this.updateElevatorStatus(res.rows[0]);
          this.moveElevator();
        }
        //获取提升机次数
        const res2 = await getElevatorTimes();
        if (res2.code === 200) {
          this.elevatorTimes = res2.data.map((e) => {
            return {
              name: obj[e.name],
              value: e.value,
            };
          });
        }
      } catch (error) {
        console.error("数据获取失败:", error);
      }
    },

    // 处理数据更新
    processData(data) {
      // 左侧数据列表
      this.leftList = [
        {
          icon: "icon1",
          name: "主控速度",
          value: `${Number(data.mainSpeed).toFixed(2)}m/s`,
          color: "#00FEEF",
        },
        {
          icon: "icon1",
          name: "编码器速度",
          value: `${Number(data.coderSpeed).toFixed(2)}m/s`,
          color: "#00FEEF",
        },
        {
          icon: "icon1",
          name: "给定速度",
          value: `${Number(data.givenSpeed).toFixed(2)}m/s`,
          color: "#00FEEF",
        },
        {
          icon: "icon1",
          name: "从编码器速度",
          value: `${Number(data.givenSpeed).toFixed(2)}m/s`,
          color: "#00FEEF",
        },
        {
          icon: "icon2",
          name: "主罐位置",
          value: `${Number(data.position).toFixed(2)}m`,
          color: "#26DEFF",
        },
        {
          icon: "icon2",
          name: "位置偏差",
          value: `${Number(data.locationDeviation).toFixed(2)}m`,
          color: "#26DEFF",
        },
        {
          icon: "icon3",
          name: "电枢电流",
          value: `${Number(data.motorCurrent).toFixed(2)}A`,
          color: "#FECB00",
        },
        {
          icon: "icon3",
          name: "磁场电流",
          value: `${Number(data.runningPressure).toFixed(2)}A`,
          color: "#FECB00",
        },
        {
          icon: "icon1",
          name: "运行油压",
          value: `${Number(data.controlPosition).toFixed(2)}MPa`,
          color: "#3AFF7B",
        },
      ];

      // 右侧数据列表
      this.rightList = [
        {
          name: "硬件条件",
          value1: { name: "运行准备", status: data.runPrepare },

          value2: { name: "主风机启", status: data.mainFan },
          value3: { name: "变流器启", status: data.transformer },
          value4: {
            name: "液压站启",
            status: data.hydraulicStation,
          },
        },
        {
          name: "安全保护",
          value1: {
            name: "硬件安全",
            status: data.hardwareSecurity,
          },
          value2: {
            name: "软件安全",
            status: data.hardwareSecurity,
          },
          value3: { name: "操作台安全", status: data.consoleSafety },
          value4: { name: "轻故障", status: data.minorMalfunction },
        },
        {
          name: "信号方向",
          value1: { name: "井口信号", status: data.wellheadSignal },
          value2: { name: "信号继电器", status: data.signalRelay },
          value3: { name: "选择正向", status: data.chooseForward },
          value4: { name: "选择反向", status: data.chooseReverse },
        },
        {
          name: "闸回路",
          value1: { name: "手动闸", status: data.manualGate },
          value2: { name: "工作闸", status: data.workGate },
          value3: { name: "全敞闸", status: data.openGate },
          value4: { name: "一级制动", status: data.firstBraking },
        },
        {
          name: "开车回路",
          value1: { name: "选低速", status: data.lowSpeed },
          value2: { name: "使能输出", status: data.enableOutput },
          value3: { name: "装置解封", status: data.deviceUnsealed },
          value4: { name: "系统减速", status: data.systemSlowdown },
        },
      ];

      this.zgposition = (Number(data.position) || 0).toFixed(2);
    },

    // 更新电梯状态
    updateElevatorStatus(data) {
      if (!data.currentAction) {
        const currentDepth = Number(data.position) || 0;
        const nearest = this.findNearestPosition(currentDepth);

        // 强制更新当前位置
        this.currentPos = nearest; // 新增
        this.targetPos = nearest; // 新增

        this.zgtrend = `待命(${nearest.name})`;
        this.isMoving = false;
      } else {
        this.targetPos =
          POSITIONS.find((item) => item.value == data.currentAction) ||
          POSITIONS[0];
        this.zgtrend = this.targetPos.name;
        this.isMoving = true;
      }
    },

    // 电梯移动动画
    moveElevator() {
      if (!this.isMoving) return;
      this.clearAnimation();

      const startTime = Date.now();
      const startPosition = Number(this.zgposition);
      const targetDepth = this.targetPos.depth;
      const distance = targetDepth - startPosition;
      const duration = Math.abs(distance) * 10; // 根据距离计算动画时长

      const animate = () => {
        const progress = Math.min(1, (Date.now() - startTime) / duration);

        // 实时更新电梯位置
        this.zgposition = (startPosition + distance * progress).toFixed(2);

        // 到达目标位置后更新状态
        if (progress < 1) {
          this.animationId = requestAnimationFrame(animate);
        } else {
          this.isMoving = false;
          this.zgtrend = `待命(${this.targetPos.name})`;
          this.currentPos = this.targetPos;
        }
      };

      animate();
    },

    // 清除动画
    clearAnimation() {
      if (this.animationId) {
        cancelAnimationFrame(this.animationId);
        this.animationId = null;
      }
    },
    // 提升机巡检记录
    async getInspectionRecords() {
      try {
        const response = await getRecentFive();
        console.log("response:", response);
        if (response.code === 200) {
          this.tableList = response.data;
        } else {
          console.error("获取巡检记录失败:", response.message);
        }
      } catch (error) {
        console.error("获取巡检记录时发生错误:", error);
      }
    },
  },
};
</script>

<style scoped lang="scss">
.main-content {
  font-family: "fangsong";
  background: url("~@/assets/images/screen/tfxt/bg.png") no-repeat center;
  padding-top: 100px;
  display: flex; // 新增弹性布局
  justify-content: space-between; // 左右两侧贴边
  .left {
    padding-left: 91px;
    padding-top: 70px;
    .item-class {
      width: 390px;
      height: 60px;
      border-radius: 10px;
      background: url("~@/assets/images/screen/tsj/bg5.png") no-repeat center;
      background-size: 100%;
      margin-bottom: 20px;
      .icon {
        width: 50px;
        height: 50px;
        display: inline-block;
        margin-left: 15px;
        vertical-align: middle; // 新增垂直对齐
        &.icon1 {
          background: url("~@/assets/images/screen/tsj/icon1.png") no-repeat
            center;
          background-size: 100% 100%;
        }
        &.icon2 {
          background: url("~@/assets/images/screen/tsj/icon2.png") no-repeat
            center;
          background-size: 100% 100%;
        }
        &.icon3 {
          background: url("~@/assets/images/screen/tsj/icon3.png") no-repeat
            center;
          background-size: 100% 100%;
        }
      }
      .item-name {
        margin-left: 15px;
        font-weight: 600;
        font-size: 20px;
        color: #00feef;
        display: inline-block; // 改为行内块
        vertical-align: middle; // 新增垂直对齐
        width: 170px;
        text-align: left;
        height: 60px;
        line-height: 60px;
        // float: left;
      }
      .item-value {
        display: inline-block; // 改为行内块
        vertical-align: middle; // 新增垂直对齐
        height: 60px;
        width: 110px;
        font-weight: 600;
        font-size: 26px;
        color: #ffffff;
        margin-right: 15px;
        height: 60px;
        line-height: 60px; // 新增行高保持垂直居中
        text-align: right;
        // float: left;
      }
    }
    .left-botton {
      width: 390px;
      height: 112px;
      border-radius: 10px;
      background: url("~@/assets/images/screen/tsj/bg6.png") no-repeat center;
      background-size: 100% 100%;
      display: flex; // 新增弹性布局
      align-items: center; // 新增垂直居中
      .item-name {
        font-weight: 600;
        font-size: 26px;
        color: #00feef;
        display: inline-block; // 改为行内块
        vertical-align: middle; // 新增垂直对齐
        width: 116px;
        height: 72px;
        text-align: center;
        margin-left: 20px;
        border-right: 1px solid #00feef;
        margin: 0 auto 0 20px; // 修改外边距
      }
      .item-value {
        font-weight: 600;
        font-size: 26px;
        color: #ffffff;
        display: inline-block;
        vertical-align: middle; // 新增垂直对齐
        flex: 1; // 新增填充剩余空间
        text-align: center;
      }
    }
  }
  .center {
    width: 826px;
    height: 902px;
    margin: 0 50px;
    padding-top: 70px;
    .center-box {
      width: 100%;
      height: 100%;
      background: url("~@/assets/images/screen/tsj/bg1.png") no-repeat center;
      background-size: 100% 100%;
      position: relative;
      .dianti-target {
        width: 60px;
        height: 250px;
        background: #fecb00;
        font-size: 30px;
        font-weight: 600;
        color: #000000;
        writing-mode: vertical-rl;
        text-align: center;
        line-height: 60px;
        letter-spacing: 10px;
        position: absolute;
      }
      .dianti-number {
        position: absolute;
        top: 600px;
        left: 110px;
        font-size: 24px;
        color: #f0ff01;
        line-height: 24px;
      }
      .dianti-peizhong {
        width: 18px;
        height: 90px;
        background: url("~@/assets/images/screen/tsj/bg4.png") no-repeat center;
        background-size: 100% 100%;
        position: absolute;
        transition: transform 0.5s cubic-bezier(0.4, 0, 0.2, 1);
      }
      .dianti-box {
        width: 46px;
        height: 78px;
        background: url("~@/assets/images/screen/tsj/bg3.png") no-repeat center;
        background-size: 100% 100%;
        position: absolute;
        transition: transform 0.5s cubic-bezier(0.4, 0, 0.2, 1);
        &.active {
          &::before {
            content: "";
            width: 16px;
            height: 26px;
            position: absolute;
            top: 0;
            left: 0;
            background: url("~@/assets/images/screen/tsj/icon5.png") no-repeat
              center;
            background-size: 100% 100%;
          }
        }
      }
      .dianti-box,
      .dianti-peizhong {
        transition: all 0.5s cubic-bezier(0.4, 0, 0.2, 1);
        will-change: transform;
      }

      .status-normal {
        color: #00ff0d;
      }

      .dianti-louceng {
        position: absolute;
        .louceng-item {
          width: 160px;
          height: 40px;
          background: #00aadb;
          font-weight: 400;
          font-size: 24px;
          color: #ffffff;
          text-align: center;
          line-height: 40px;
          margin-bottom: 45px;
        }
      }
    }
  }
  .right {
    width: 400px;
    padding-top: 70px;
    margin-right: 50px;
    .right-item-class {
      width: 100%;
      height: 118px;
      background: url("~@/assets/images/screen/tsj/bg6.png") no-repeat center;
      background-size: 100% 100%;
      display: flex; // 新增弹性布局
      align-items: center; // 垂直居中
      padding: 0 10px; // 添加左右内边距
      margin-bottom: 18px;
      .left-item-box {
        width: 98px;
        height: 98px;
        border-radius: 10px;
        border: 2px solid #02dbf2;
        font-weight: 400;
        font-size: 24px;
        color: #fecb00;
        line-height: 36px;
        padding: 10px 22px; // 移除原有padding
        margin-right: 10px;
      }
      .right-item-box {
        flex: 1; // 填充剩余空间
        display: grid; // 使用网格布局
        grid-template-columns: repeat(2, 1fr); // 两列布局
        gap: 10px; // 项间距
        justify-content: space-between;
        .right-item-box-item {
          width: 130px;
          height: 44px;
          border-radius: 8px;
          text-align: center;
          border: 2px solid #02dbf2;
          font-weight: 400;
          font-size: 20px;
          color: #ffffff;
          margin: 0; // 移除原有宽度限制
          line-height: 40px; // 垂直居中
          &.active {
            background: url("~@/assets/images/screen/tsj/button.png") no-repeat
              center;
            background-size: 100% 100%;
            line-height: 40px; // 垂直居中
            color: black;
          }
        }
      }
    }
    .right-item-botton {
      width: 100%;
      height: 190px;
      background: url("~@/assets/images/screen/tsj/bg7.png") no-repeat center;
      background-size: 100% 100%;
      overflow: hidden;
      .title {
        height: 45px;
        border-bottom: 1px solid #02f2ea;
        margin: 0 10px;
        font-weight: 400;
        font-size: 22px;
        color: #fecb00;
        line-height: 45px;
      }
      .right-item-body {
        width: 100%;
        margin-top: 8px;
        .table-header {
          display: grid;
          grid-template-columns: 1fr 2fr 2fr 2fr;
          color: #02f2ea;
          margin: 0px 10px;
          span {
            text-align: center;
            font-size: 16px;
            font-weight: 500;
          }
        }
        .table-content {
          display: grid;
          grid-template-columns: 1fr 2fr 2fr 2fr;
          color: #ffffff; // 内容文字颜色
          font-size: 16px;
          margin: 0px 10px;
          span {
            text-align: center;
            line-height: 30px; // 行高保持垂直居中
            &:nth-child(3) {
              // 第三列特殊样式
              color: #00ff0d; // 正常状态绿色
            }
            &.red {
              color: red;
            }
          }

          // 鼠标悬停效果
          &:hover {
            background: rgba(2, 242, 234, 0.1);
          }
        }
      }
    }
  }
}
</style>
