<template>
  <view class="container">


    <!-- 头部区域 -->
    <view class="header">
      <u-row>
        <u-col span="2">
          <view class="status-btn" :class="{ active_btn: communicationLink_2 }">Link</view>
        </u-col>
        <u-col span="2">
          <view class="status-btn" :class="{ active_btn: bleConnected }">blue</view>
        </u-col>
        <u-col span="6" textAlign="left">
          <text class="title">长沙亿旭智能</text>
        </u-col>
        <u-col span="2">

        </u-col>
      </u-row>
    </view>


    <!-- 主要内容区域 -->
    <scroll-view class="content" scroll-y>
      <view class="param-section">
        <!-- 电机方向 -->
        <view class="param-row">
          <view class="btn-class">
            <u-button type="primary" size="mini" class="param-label">电机方向</u-button>
          </view>
          <view class="input-class" >
            <u-input
                @focus="editStatus = true"
                @blur="handleBlurWithDelay"
                v-model="params.motorDirection"
                disabledColor="#ffffff"
                placeholder="请选择方向"
                readonly
            ></u-input>
          </view>
          <view class="checkbox-class">
            <u-checkbox-group
                placement="column">
              <u-checkbox v-model="params.wDir" @change="handleDirectionChange"  class="checkbox" label="W_Dir">W_Dir</u-checkbox>
            </u-checkbox-group>
          </view>

          <u-button :plain="true" :hairline="true"  size="mini" class="action-btn" @click="writeDirection" :disabled="params.wDir">方向设置</u-button>
        </view>

        <!-- 通讯时间 -->
        <view class="param-row">
          <view class="btn-class">
            <u-button type="primary" size="mini" class="param-label">通讯时间</u-button>
          </view>
          <view class="input-class">
            <u-input
                @focus="editStatus = true"
                @blur="handleBlurWithDelay"
                v-model="params.communicationTime"
                disabledColor="#ffffff"
                placeholder=""

            ></u-input>
          </view>
          <view class="checkbox-class">
            <u-checkbox-group v-model="checkboxValue_timedSend"
                placement="column">
              <u-checkbox  name="timedSend"   v-model="params.timedSend" class="checkbox" label="定时发送" @change="handleCommunicationTimeChange">定时发送</u-checkbox>
            </u-checkbox-group>
          </view>
        </view>

        <!-- 夜返角度 -->
        <view class="param-row">
          <view class="btn-class">
            <u-button type="primary" size="mini" class="param-label">夜返角度°</u-button>
          </view>
          <view class="input-class">
            <u-input
                @focus="editStatus = true"
                @blur="handleBlurWithDelay"
                v-model="params.nightReturnAngle"
                placeholder="请输入角度"
                type="text"
                class="param-input"
            ></u-input>
          </view>
          <view class="checkbox-class">
            <u-checkbox-group

                placement="column">
              <u-checkbox v-model="params.wBackA" class="checkbox" label="W_BackA"  @change="handleNightReturnAngleChange">W_BackA</u-checkbox>
            </u-checkbox-group>
          </view>
          <u-button :plain="true" :hairline="true"  size="mini" class="action-btn" :disabled="params.wBackA"
                    @click="writeNightReturnAngle">夜返角写入
          </u-button>
        </view>

        <!-- 放平角度 -->
        <view class="param-row">
          <view class="btn-class">
            <u-button type="primary" size="mini" class="param-label">放平角度°</u-button>
          </view>
          <view class="input-class">
            <u-input
                @focus="editStatus = true"
                @blur="handleBlurWithDelay"
                v-model="params.flatAngle"
                placeholder="请输入角度"
                type="text"
                class="param-input"
            ></u-input>
          </view>
          <view class="checkbox-class">
            <u-checkbox-group

                placement="column">
              <u-checkbox v-model="params.wFlat" class="checkbox" label="W_Flat" @change="handleFlatAngleChange">W_Flat</u-checkbox>
            </u-checkbox-group>
          </view>
          <u-button :plain="true" :hairline="true"  size="mini" class="action-btn" :disabled="params.wFlat" @click="writeFlatAngle">
            放平角度写入
          </u-button>
        </view>

        <!-- 指定角度 -->
        <view class="param-row">
          <view class="btn-class">
            <u-button type="primary" size="mini" class="param-label">指定角度°</u-button>
          </view>
          <view class="input-class">
            <u-input
                @focus="editStatus = true"
                @blur="handleBlurWithDelay"
                v-model="params.specifiedAngle"
                placeholder="请输入角度"
                type="text"
                class="param-input"
            ></u-input>
          </view>
          <view class="checkbox-class">
            <u-checkbox-group

                placement="column">
              <u-checkbox v-model="params.wSetA" class="checkbox" label="W_SetA" @change="handleSpecifiedAngleChange">W_SetA</u-checkbox>
            </u-checkbox-group>
          </view>
          <u-button :plain="true" :hairline="true"  size="mini" class="action-btn" :disabled="params.wSetA" @click="writeSpecifiedAngle">
            指定角度写入
          </u-button>
        </view>

        <!-- 雪天角度 -->
        <view class="param-row">
          <view class="btn-class">
            <u-button type="primary" size="mini" class="param-label">雪天角度°</u-button>
          </view>
          <view class="input-class">
            <u-input
                @focus="editStatus = true"
                @blur="handleBlurWithDelay"
                v-model="params.snowAngle"
                placeholder="请输入角度"
                type="text"
                class="param-input"
            ></u-input>
          </view>
          <view class="checkbox-class">
            <u-checkbox-group

                placement="column">
              <u-checkbox v-model="params.wSno" class="checkbox" label="W_Sno" @change="handleSnowAngleChange">W_Sno</u-checkbox>
            </u-checkbox-group>
          </view>
          <u-button :plain="true" :hairline="true"  size="mini" class="action-btn" :disabled="params.wSno" @click="writeSnowAngle">
            雪天角度写入
          </u-button>
        </view>

        <!-- 大风角度 -->
        <view class="param-row">
          <view class="btn-class">
            <u-button type="primary" size="mini" class="param-label">大风角度°</u-button>
          </view>
          <view class="input-class">
            <u-input
                @focus="editStatus = true"
                @blur="handleBlurWithDelay"
                v-model="params.windAngle"
                placeholder="请输入角度"
                type="text"
                class="param-input"
            ></u-input>
          </view>
          <view class="checkbox-class">
            <u-checkbox-group
                placement="column">
              <u-checkbox v-model="params.wWin" class="checkbox" label="W_Win" @change="handleWindAngleChange">W_Win</u-checkbox>
            </u-checkbox-group>
          </view>
          <u-button :plain="true" :hairline="true"  size="mini" class="action-btn" :disabled="params.wWin" @click="writeWindAngle">
            大风角度写入
          </u-button>
        </view>

        <!-- 过流值 -->
        <view class="param-row">
          <view class="btn-class">
            <u-button type="primary" size="mini" class="param-label">过流值(A)</u-button>
          </view>
          <view class="input-class">
            <u-input
                @focus="editStatus = true"
                @blur="handleBlurWithDelay"
                v-model="params.overcurrentValue"
                placeholder="请输入过流值"
                type="text"
                class="param-input"
            ></u-input>
          </view>
          <view class="checkbox-class">
            <u-checkbox-group
                placement="column">
              <u-checkbox v-model="params.wCurr" class="checkbox" label="W_Curr" @change="handleOvercurrentValueChange">W_Curr</u-checkbox>
            </u-checkbox-group>
          </view>
          <u-button :plain="true" :hairline="true"  size="mini" class="action-btn" :disabled="params.wCurr"
                    @click="writeOvercurrentProtection">过流保护写入
          </u-button>
        </view>

        <!-- 跟踪精度 -->
        <view class="param-row">
          <view class="btn-class">
            <u-button type="primary" size="mini" class="param-label">跟踪精度</u-button>
          </view>
          <view class="input-class">
            <u-input
                @focus="editStatus = true"
                @blur="handleBlurWithDelay"
                v-model="params.trackingAccuracy"
                placeholder="请输入精度"
                type="text"
                class="param-input"
            ></u-input>
          </view>
          <view class="checkbox-class">
            <u-checkbox-group

                placement="column">
              <u-checkbox v-model="params.wAccu" class="checkbox" label="W_Accu" @change="handleAccuracyChange">W_Accu</u-checkbox>
            </u-checkbox-group>
          </view>
          <u-button :plain="true" :hairline="true"  size="mini" class="action-btn" :disabled="params.wAccu" @click="writeAccuracy">
            精度写入
          </u-button>
        </view>
      </view>
    </scroll-view>
    <u-action-sheet
        :show="showMotorDirection"
        :actions="directionOptions"
        title="请选择电机方向"
        @close="showMotorDirection = false"
        @select="motorDirectionSelect"
    >
    </u-action-sheet>

  </view>
</template>

<script>
import {writeRegister,setTime,stopHeartbeat,setTimeStatus} from '@/utils/modbus.js';
export default {
  data() {
    return {
      checkboxValue_timedSend: ['timedSend'],
      editStatus: false,
      showMotorDirection: false,
      checkboxValue1: [],
      activeTab: 'settings2',
      params: {
        motorDirection: '正转',
        communicationTime: '0.5',
        nightReturnAngle: '-30',
        flatAngle: '-1',
        specifiedAngle: '20',
        snowAngle: '30',
        windAngle: '10',
        overcurrentValue: '5',
        trackingAccuracy: '1',
        wDir:true,
        timedSend: true,
        wBackA: true,
        wFlat: true,
        wSetA: true,
        wSno: true,
        wWin: true,
        wCurr: true,
        wAccu: true
      },
      directionOptions: [
        {name: '正转', value: '正转'},
        {name: '反转', value: '反转'}
      ],
      communicationLink_2: false,
      communicationTimer_2: null, // 添加这一行用于保存定时器 ID
    }
  },
  computed: {
    bleConnected() {
      return this.$store.getters['ble/connected']
    },
    bleData() {
      return this.$store.getters['ble/data']
    }
  },
  watch: {
    bleData: {
      handler(newData, oldData) {
        if (newData) {
          console.log('接收到蓝牙数据:', newData)
          // 清除之前的定时器
          if (this.communicationTimer_2) {
            clearTimeout(this.communicationTimer_2)
            this.communicationTimer_2 = null
          }
          // 设置通信链接状态为 true
          this.communicationLink_2 = true
          if (!this.editStatus){
             this.updateSensorData(newData)
          }

        }
      },
      deep: true, // 深度监听，确保嵌套对象变化时也能触发
      immediate: true // 立即执行一次
    }
  },
  methods: {
    handleBlurWithDelay() {
      setTimeout(() => {
        this.editStatus = false;
      }, 1000);
    },
    handleNightReturnAngleChange(value){
      this.params.wBackA = !value;
    },
    handleFlatAngleChange(value){
      this.params.wFlat = !value;
    },
    handleSpecifiedAngleChange(value){
      this.params.wSetA = !value;
    },
    handleSnowAngleChange(value){
      this.params.wSno = !value;
    },
    handleWindAngleChange(value){
      this.params.wWin = !value;
    },
    handleOvercurrentValueChange(value){
      this.params.wCurr = !value;
    },
    handleAccuracyChange(value){
      this.params.wAccu = !value;
    },
    handleCommunicationTimeChange(value){
      this.params.wTim = !value;
      if (value){
        let number = parseFloat(this.params.communicationTime || "0");
        const intValue1 = Math.round(number * 1000);
        setTime(intValue1);
      }else{
        stopHeartbeat();
      }
      setTimeStatus(value);
    },
    handleDirectionChange(value){
       this.params.wDir = !value;
    },
    motorDirectionSelect(e){
      this.params.motorDirection = e.name
      uni.showModal({
        title: '确认写入',
        content: `确定执行电机方向设置？`,
        success: (res) => {
          if (res.confirm) {
            if (e.name === '正转'){
              writeRegister('READ_DIRECTION', null)
            }else {
              writeRegister('READ_REVERSE', null)
            }
            uni.showToast({
              title: '操作执行成功！',
              icon: 'success',
              duration: 2000
            });
          }
        }
      });


    },
    writeDirection() {
      this.showMotorDirection = true;
    },
    writeNightReturnAngle() {
      if (this.params.wBackA) return
      uni.showModal({
        title: '确认写入',
        content: `是否确定执行此操作？`,
        success: (res) => {
           if (res.confirm) {
             writeRegister('READ_RETURN', this.params.nightReturnAngle);
             uni.showToast({
               title: '操作执行成功！',
               icon: 'success',
               duration: 2000
             });
           }
        }
      });


    },
    writeFlatAngle() {
      if (this.params.wFlat) return
      uni.showModal({
        title: '确认写入',
        content: `是否确定执行此操作？`,
        success: (res) => {
           if (res.confirm) {
             writeRegister('READ_FLAT', this.params.flatAngle);
             uni.showToast({
               title: '操作执行成功！',
               icon: 'success',
               duration: 2000
             });
           }
        }
      });


    },
    writeSpecifiedAngle() {
      if (this.params.wSetA) return
      uni.showModal({
        title: '确认写入',
        content: `是否确定执行此操作？`,
        success: (res) => {
           if (res.confirm) {
             writeRegister('READ_SPECIFY', this.params.specifiedAngle);
             uni.showToast({
               title: '操作执行成功！',
               icon: 'success',
               duration: 2000
             });
           }
        }
      });


    },
    writeSnowAngle() {
      if (this.params.wSno) return
      uni.showModal({
        title: '确认写入',
        content: `是否确定执行此操作？`,
        success: (res) => {
           if (res.confirm) {
             writeRegister('READ_SNOW', this.params.snowAngle);
             uni.showToast({
               title: '操作执行成功！',
               icon: 'success',
               duration: 2000
             });
           }
        }
      });


    },
    writeWindAngle() {
      if (this.params.wWin) return
      uni.showModal({
        title: '确认写入',
        content: `是否确定执行此操作？`,
        success: (res) => {
           if (res.confirm) {
             writeRegister('READ_WIND', this.params.windAngle);
             uni.showToast({
               title: '操作执行成功！',
               icon: 'success',
               duration: 2000
             });
           }
        }
      });

    },
    writeOvercurrentProtection() {
      if (this.params.wCurr) return
      uni.showModal({
        title: '确认写入',
        content: `是否确定执行此操作？`,
        success: (res) => {
           if (res.confirm) {
             writeRegister('READ_OVERCURRENT', this.params.overcurrentValue);
             uni.showToast({
               title: '操作执行成功！',
               icon: 'success',
               duration: 2000
             });
           }
        }
      });


    },
    writeAccuracy() {
      if (this.params.wAccu) return
      uni.showModal({
        title: '确认写入',
        content: `是否确定执行此操作？`,
        success: (res) => {
           if (res.confirm) {
             writeRegister('READ_ACCURACY', this.params.trackingAccuracy);
             uni.showToast({
               title: '操作执行成功！',
               icon: 'success',
               duration: 2000
             });
           }
        }
      });

    },
    updateSensorData(data) {
      // 根据蓝牙数据更新参数值
      if (data.MotDrection_37 !== undefined && this.params.wDir) {
        // 电机方向: 0表示正转，1表示反转
        this.params.motorDirection = data.MotDrection_37 === '1' ? '反转' : '正转'
      }

      if (data.qNightAngle_66 !== undefined && this.params.wBackA) {
        this.params.nightReturnAngle = data.qNightAngle_66
      }

      if (data.qFlatAngle_67 !== undefined && this.params.wFlat) {
        this.params.flatAngle = data.qFlatAngle_67
      }

      if (data.qSpecifiedAngle_69 !== undefined && this.params.wSetA) {
        this.params.specifiedAngle = data.qSpecifiedAngle_69
      }

      if (data.qSnowAngle_68 !== undefined && this.params.wSno) {
        this.params.snowAngle = data.qSnowAngle_68
      }

      if (data.qWindAngle_70 !== undefined && this.params.wWin ) {
        this.params.windAngle = data.qWindAngle_70
      }

      if (data.OverProtection_38 !== undefined && this.params.wCurr) {
        this.params.overcurrentValue = data.OverProtection_38
      }

      if (data.TrackingAccuracy_39 !== undefined && this.params.wAccu) {
        this.params.trackingAccuracy = data.TrackingAccuracy_39
      }

      // 设置6秒后将 communicationLink_2 设置为 false 的定时器
      this.communicationTimer_2 = setTimeout(() => {
        this.communicationLink_2 = false
        this.communicationTimer_2 = null
      }, 5000)

    }
  }
}
</script>

<style lang="scss" >
@import '@/static/scss/custom-theme.scss';

.container {
  height: calc(100% - 140px);
  display: flex;
  flex-direction: column;
  background-color: $custom-bg-tertiary;
}

.status-bar {
  height: $custom-status-height;
  background-color: $custom-bg-primary;
  @include flex-between;
  padding: 0 $custom-spacing-md;
  font-size: 14px;

  .status-left {
    color: $custom-text-primary;
  }

  .status-right {
    @include flex-start;
    gap: $custom-spacing-xs;

    .data-rate {
      color: $custom-text-secondary;
      font-size: 12px;
    }

    .wifi-icon, .hd-text, .network, .battery {
      font-size: 12px;
    }
  }
}

.header {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20rpx;

  .link-btn {
    background-color: #ff4757;
    border: none;
    width: 60px;
    margin-left: 0px;
  }

  .title {
    color: #fff;
    font-size: 36rpx;
    font-weight: bold;
  }

  .status-btn {
    background-color: #ff4757;
    border: none;
    margin-left: 0px;
    padding: 0px;
    width: 40px;
    text-align: center;
    color: white;
    border-radius: 4px;
    height: 20px;
    line-height: 20px;
  }
  .active_btn {
    background-color: yellowgreen !important;
  }

}

.content {
  flex: 1;
  padding: $custom-spacing-md;
}

.param-section {
  @include card-style;
}

.param-row {
  @include flex-start;
  margin-bottom: $custom-spacing-md;
  gap: 2px;

  .param-label {
    width: 70px;
    @include button-style('primary');
  }

  .param-input {
    flex: 1;
    width: 60px;
    @include input-style;
  }

  .radio-group {
    @include flex-start;
    gap: $custom-spacing-md;
  }

  .checkbox {
    margin-left: $custom-spacing-sm;
  }

  .action-btn {
    width: 90px;
    background-color: $custom-bg-secondary;
    color: $custom-text-secondary;
    border: 1px solid $custom-border-secondary;
    height: 30px;
    line-height: 30px;
    margin-right: 0px;
    font-size: 12px;
  }
}

.bottom-nav {
  height: $custom-nav-height;
  background-color: $custom-nav-bg;
  display: flex;
  border-top: 1px solid $custom-border-primary;

  .nav-item {
    flex: 1;
    @include flex-center;
    font-size: 14px;
    color: $custom-text-secondary;
    background-color: $custom-bg-secondary;
    border-right: 1px solid $custom-border-primary;
    transition: $custom-transition;

    &:last-child {
      border-right: none;
    }

    &.active {
      background-color: $custom-nav-active-bg;
      color: $custom-text-primary;
      font-weight: bold;
    }

    &:hover {
      background-color: darken($custom-bg-secondary, 5%);
    }
  }
}

.footer-status {
  height: $custom-footer-height;
  @include gradient-bg;
  @include flex-between;
  padding: 0 $custom-spacing-md;

  .bt-status {
    color: #007aff;
    font-size: 14px;
    font-weight: bold;
  }

  .rx-tx-status {
    color: $custom-text-primary;
    font-size: 12px;
  }
}


// 响应式设计
@include responsive(md) {
  .param-row {
    .param-input {
      min-width: 150px;
    }
  }
}

@include responsive(lg) {
  .param-row {
    .param-input {
      min-width: 200px;
    }
  }
}

::v-deep .param-section .u-button--mini{
  width: 80px !important;
  height: 36px !important;
  font-size: 10px !important;
}

::v-deep .param-section .u-input{
  width: 60px !important;
}

::v-deep .content text{
    font-size: 12px !important;
}

</style>