<template>
  <div class="seal_test_container">
    <div class="left_container">
      <div class="title_wrap">
        <img class="icon" :src="SealPng" alt="" />
        <div class="title">实时压力表</div>
      </div>
      <div class="echarts_box" id="seal_echarts"></div>
      <div class="oper_box">
        <div class="air_box">
          <p class="box"></p>
          <p class="tit">测试前气压</p>
          <p class="num">
            {{
              sealStore.oldAirPressure != null
                ? sealStore.oldAirPressure
                : '--'
            }}KPa
          </p>
        </div>
        <img
          class="air_img"
          v-if="!sealStore.isStartTest"
          @click="newStartTest(1)"
          :src="StartTest"
          alt=""
        />
        <img
          class="air_img"
          @click="newStartTest(2)"
          v-if="sealStore.isStartTest"
          :src="StopTest"
          alt=""
        />
        <input
          type="number"
          placeholder="第一次"
          v-model="sleepVal1"
          style="width: 100px; height: 100px"
        />
        <input
          type="number"
          placeholder="第二次"
          v-model="sleepVal2"
          style="width: 100px; height: 100px"
        />
      </div>
    </div>
    <div class="right_container">
      <div class="header">
        <div class="left">
          <img :src="TestIcon" class="icon" alt="" />
          <p class="title">密封测试</p>
        </div>
        <p class="en">SEAL</p>
      </div>
      <div class="oper_box">
        <div class="emp_box">
          <div class="title">测试时间</div>
          <div class="num">
            {{ resultTime ? resultTime : '未开始' }}
          </div>
        </div>
        <div class="emp_box">
          <div class="title">气压差值</div>
          <div class="num">
            {{
              sealStore.differenceValue != null
                ? `${sealStore.differenceValue}KPa`
                : '未开始'
            }}
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import * as echarts from 'echarts'
import { ref, onMounted, onBeforeUnmount, watch } from 'vue'
import SealPng from '@/assets/img/seal/seal.png'
import TestIcon from '@/assets/img/seal/test.png'
import StartTest from '@/assets/img/seal/starttest.png'
import StopTest from '@/assets/img/seal/stoptest.png'
import {
  someAirSwitchJSON,
  airCompressor_setStateJSON,
  airCompressorGetPressureDirectIntervalJSON,
  airCompressor_channelCtrlJSON,
  AirInletProportionalValve_setStateJSON,
  AirOutletProportionalValve_setStateJSON,
  airCompressorGetPressureDirectJSON,
  airCompressorSetValve1JSON,
  airCompressorSetValve2JSON,
  airCompressorChannelSelectJSON,
  AirOutletProportionalValve_getStateJSON,
  airInletProportionalValve_getStateJSON,
} from '@/mock/command'
import { useSealStore, useTestStore, useWebSocketStore } from '@/store'
import { storeToRefs } from 'pinia'

const sealStore = useSealStore()
const testStore = useTestStore()
const websocketStore = useWebSocketStore()

const { airInletProportionalInitVal, airOutletProportionalInitVal } =
  storeToRefs(sealStore)

const sealCharts = ref(null)
const sealOptions = ref({
  series: [
    {
      type: 'gauge',
      min: 0,
      max: 800,
      progress: {
        show: true,
        width: 18,
        itemStyle: {
          color: '#3442aa',
        },
      },
      pointer: {
        itemStyle: {
          color: '#3442aa',
        },
      },
      axisLine: {
        lineStyle: {
          width: 18,
        },
      },
      axisTick: {
        show: false,
      },
      splitLine: {
        length: 15,
        lineStyle: {
          width: 2,
          color: '#999',
        },
      },
      axisLabel: {
        distance: 25,
        color: '#999',
        fontSize: 20,
      },
      anchor: {
        show: true,
        showAbove: true,
        size: 25,
        itemStyle: {
          borderWidth: 10,
          borderColor: '#3442aa',
        },
      },
      title: {
        show: false,
      },
      detail: {
        valueAnimation: true,
        fontSize: 40,
        color: '#3442aa',
        formatter: '{value} KPa',
        offsetCenter: [0, '70%'],
      },
      data: [
        {
          value: sealStore.currentAirPressure,
        },
      ],
    },
  ],
})

const n_sec = ref(0) // 秒
const n_min = ref(0) // 分
const n_hour = ref(0) // 时

const resultTime = ref('')
const timerStart = ref(null)

const timerReal = () => {
  var str_sec = n_sec.value
  var str_min = n_min.value
  var str_hour = n_hour.value
  if (n_sec.value < 10) {
    str_sec = '0' + n_sec.value
  }
  if (n_min.value < 10) {
    str_min = '0' + n_min.value
  }
  if (n_hour.value < 10) {
    str_hour = '0' + n_hour.value
  }
  resultTime.value = str_hour + ':' + str_min + ':' + str_sec
  n_sec.value = n_sec.value + 1
  if (n_sec.value > 59) {
    n_sec.value = 0
    n_min.value = n_min.value + 1
  }
  if (n_min.value > 59) {
    n_min.value = 0
    n_hour.value = n_hour.value + 1
  }
}

watch(
  () => sealStore.isStartTest,
  (newValue, oldValue) => {
    if (!newValue) {
      stopTimer()
    }
  },
)

const stopTimer = () => {
  // 改变测试前oldAirPressure为null
  sealStore.updateOldAirPressure(null)
  // 结束测试时将时间重置null
  clearInterval(timerStart.value)
  timerStart.value = null
  resultTime.value = null
  n_sec.value = 0
  n_min.value = 0
  n_hour.value = 0
  sealStore.updateIsStartTest(false)
}

const timerFunc = () => {
  timerReal()
  timerStart.value = setInterval(() => {
    timerReal()
  }, 1000)
}

const wait = async ms => {
  await new Promise(resolve => setTimeout(resolve, ms))
}

const sleepVal1 = ref(1)
const sleepVal2 = ref(5)

const newStartTest = async flag => {
  if (flag == 1) {
    // 开始测试
    // 启动计时器
    timerFunc()
    sealStore.updateIsStartTest(true)
    // 空压机选通阀切换到通道2（空气）
    websocketStore.sendCommandMsg(airCompressorChannelSelectJSON([2]))
    // 空压机电子阀1打开 空压机电子阀2打开
    websocketStore.sendCommandMsg(airCompressorSetValve1JSON([1]))
    websocketStore.sendCommandMsg(airCompressorSetValve2JSON([1]))
    // 风机入口比例阀闭合 风机出口比例阀闭合
    websocketStore.sendCommandMsg(AirInletProportionalValve_setStateJSON([0]))
    websocketStore.sendCommandMsg(AirOutletProportionalValve_setStateJSON([0]))
    // 空压机打开
    websocketStore.sendCommandMsg(airCompressor_setStateJSON([1]))
    // 等待1s
    await wait(sleepVal1.value * 1000)
    // 空压机关闭
    websocketStore.sendCommandMsg(airCompressor_setStateJSON([0]))
    // 空压机电子阀1关闭 空压机电子阀2关闭
    websocketStore.sendCommandMsg(airCompressorSetValve1JSON([0]))
    websocketStore.sendCommandMsg(airCompressorSetValve2JSON([0]))
    // 空压机选通阀切换到通道1 （入气口）
    websocketStore.sendCommandMsg(airCompressorChannelSelectJSON([1]))
    // 等待5s
    await wait(sleepVal2.value * 1000)
    // 记录当前压力数值作为初始压力值
    websocketStore.sendCommandMsg(airCompressorGetPressureDirectJSON)
  }
  if (flag == 2) {
    // 停止测试
    /**
     *  空压机电子阀1打开
     *  空压机电子阀2打开
     *  空压机选通阀切换到通道1
     *  风机入口比例阀恢复
     *  风机出口比例阀恢复
     */
    websocketStore.sendCommandMsg(airCompressorSetValve1JSON([1]))
    websocketStore.sendCommandMsg(airCompressorSetValve2JSON([1]))
    websocketStore.sendCommandMsg(airCompressorChannelSelectJSON([1]))
    // 数值为刚开始记录的数值
    websocketStore.sendCommandMsg(
      AirInletProportionalValve_setStateJSON([
        airInletProportionalInitVal.value[0],
      ]),
    )
    websocketStore.sendCommandMsg(
      AirOutletProportionalValve_setStateJSON([
        airOutletProportionalInitVal.value[0],
      ]),
    )
    // 停止计时器
    stopTimer()
  }
}

const timer = ref(null)
const timerData = ref(null)
onBeforeUnmount(() => {
  clearInterval(timerData.value)
  clearInterval(timer.value)
  clearInterval(timerStart.value)
})
onMounted(() => {
  // 需要记录当前的风机入口出口比例阀数值
  sealCharts.value = echarts.init(document.getElementById('seal_echarts'))
  sealCharts.value.setOption(sealOptions.value)
  timer.value = setInterval(() => {
    sealCharts.value.setOption({
      series: [
        {
          type: 'gauge',
          min: 0,
          max: 800,
          progress: {
            show: true,
            width: 18,
            itemStyle: {
              color: '#3442aa',
            },
          },
          pointer: {
            itemStyle: {
              color: '#3442aa',
            },
          },
          axisLine: {
            lineStyle: {
              width: 18,
            },
          },
          axisTick: {
            show: false,
          },
          splitLine: {
            length: 15,
            lineStyle: {
              width: 2,
              color: '#999',
            },
          },
          axisLabel: {
            distance: 25,
            color: '#999',
            fontSize: 20,
          },
          anchor: {
            show: true,
            showAbove: true,
            size: 25,
            itemStyle: {
              borderWidth: 10,
              borderColor: '#3442aa',
            },
          },
          title: {
            show: false,
          },
          detail: {
            valueAnimation: true,
            fontSize: 40,
            color: '#3442aa',
            formatter: '{value} KPa',
            offsetCenter: [0, '70%'],
          },
          data: [
            {
              value: sealStore.currentAirPressure,
            },
          ],
        },
      ],
    })
  }, 1000)
  websocketStore.sendCommandMsg(airInletProportionalValve_getStateJSON)
  websocketStore.sendCommandMsg(AirOutletProportionalValve_getStateJSON)
  timerData.value = setInterval(() => {
    websocketStore.sendCommandMsg(airCompressorGetPressureDirectIntervalJSON)
  }, 100)
})
</script>

<style lang="scss" scoped>
.seal_test_container {
  margin-bottom: 19px;
  height: 580px;
  box-sizing: border-box;
  border-radius: 16px;
  display: flex;
  align-items: center;
  .left_container {
    margin-right: 30px;
    width: 766px;
    height: 580px;
    box-sizing: border-box;
    border-radius: 16px;
    background: #ffffff;
    position: relative;
    .title_wrap {
      position: absolute;
      left: 28px;
      top: 28px;
      width: 141px;
      height: 31px;
      box-sizing: border-box;
      display: flex;
      align-items: center;
      .title {
        font-family: 思源黑体;
        font-size: 20px;
        font-weight: bold;
        line-height: normal;
        letter-spacing: 0.02em;
        font-feature-settings: 'kern' on;
        color: #000000;
        margin-left: 9px;
      }
      .icon {
        width: 30px;
        height: 30px;
      }
    }
    .oper_box {
      position: absolute;
      left: 28px;
      bottom: 28px;
      width: 710px;
      height: 110px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      .air_img {
        width: 341px;
        height: 110px;
      }
      .air_box {
        width: 341px;
        height: 110px;
        border-radius: 16px;
        background: #f6f6f6;
        display: flex;
        align-items: center;
        justify-content: center;
        .box {
          width: 16px;
          height: 16px;
          background: #4359b9;
          margin-right: 6px;
        }
        .tit {
          font-family: 思源黑体;
          font-size: 20px;
          font-weight: normal;
          line-height: normal;
          letter-spacing: 0.06em;
          font-feature-settings: 'kern' on;
          color: #3d3d3d;
          margin-right: 8px;
        }
        .num {
          font-family: Source Han Sans;
          font-size: 30px;
          font-weight: bold;
          line-height: normal;
          letter-spacing: 0.06em;
          font-feature-settings: 'kern' on;
          color: #4359b9;
        }
      }
    }
    .echarts_box {
      height: 580px;
      position: absolute;
      left: 0;
      top: -36px;
      width: 100%;
    }
  }
  .right_container {
    height: 580px;
    box-sizing: border-box;
    border-radius: 16px;
    background: #ffffff;
    flex: 1;
    padding: 32px 42px;
    .header {
      display: flex;
      align-items: center;
      justify-content: space-between;
      box-sizing: border-box;
      width: 340px;
      height: 45px;
      border-radius: 245px;
      background: #06518b;
      padding-left: 17px;
      padding-right: 24px;
      margin-bottom: 20px;
      .left {
        display: flex;
        align-items: center;
        .icon {
          width: 16px;
          height: 16px;
        }
        .title {
          font-family: 思源黑体;
          font-size: 14px;
          font-weight: normal;
          line-height: normal;
          letter-spacing: 0.1em;
          margin-left: 9px;
          color: #ffffff;
        }
      }
      .en {
        font-family: 思源黑体;
        font-size: 12px;
        font-weight: normal;
        line-height: normal;
        letter-spacing: 0.1em;
        color: #ffffff;
      }
    }
    .oper_box {
      width: 340px;
      height: 455px;
      border-radius: 16px;
      background: #f6f6f6;
      box-sizing: border-box;
      padding: 20px;
      .emp_box {
        width: 300px;
        height: 198px;
        border-radius: 12px;
        background: #fff;
        margin-bottom: 20px;
        box-sizing: border-box;
        padding-top: 16px;
        padding-left: 27px;
        padding-right: 27px;
        padding-bottom: 20px;
        display: flex;
        flex-direction: column;
        .title {
          font-family: Source Han Sans;
          font-size: 16px;
          font-weight: 500;
          line-height: normal;
          letter-spacing: 0.06em;
          font-feature-settings: 'kern' on;
          color: #06518b;
        }
        .num {
          flex: 1;
          display: flex;
          align-items: center;
          justify-content: center;
          font-family: 思源黑体;
          font-size: 30px;
          font-weight: bold;
          line-height: normal;
          letter-spacing: 0.1em;
          color: #000000;
          border-radius: 12px;
          background: #fafafa;
          box-sizing: border-box;
        }
      }
      .test_png {
        width: 300px;
        height: 50px;
      }
    }
  }
}
input[type='number']::-webkit-inner-spin-button,
input[type='number']::-webkit-outer-spin-button,
input[type='datetime']::-webkit-inner-spin-button,
input[type='datetime']::-webkit-outer-spin-button {
  /* 设置箭头按钮的宽度和高度 */
  width: 50px;
  height: 100px;
}
</style>
