<template>
  <view class="container">
    <!-- 头部区域 -->
    <BluetoothHeader
        @ble-data-received="handleBleDataReceived"
    />

    <!-- 主要内容区域 -->
    <view class="main-content">
      <!-- 日期时间显示 -->
      <view class="datetime-box">
        <text class="datetime-text">{{ currentDateTime }}</text>
      </view>

      <view class="status-indicators">
        <!-- 状态指示器 -->
        <view class="indicator-row">
          <view class="indicator-item" v-for="(item, index) in indicators1" :key="index">
            <view class="status-indicator" :class="{ 'active': item.value }"></view>
            <text class="indicator-text">{{ item.label }}</text>
          </view>
        </view>
        <view class="indicator-row">
          <view class="indicator-item" v-for="(item, index) in indicators2" :key="index">
            <view class="status-indicator" :class="{ 'active': item.value }"></view>
            <text class="indicator-text">{{ item.label }}</text>
          </view>
        </view>
      </view>

      <!-- 传感器读数和控制 -->
      <view class="sensor-controls">
        <view class="control-item" v-for="(item, index) in sensorControls" :key="index">
          <view class="control-label">{{ item.label }}</view>
          <view class="control-value">
            <u--input
                border="none"
                v-model="item.value"
            ></u--input>
          </view>
          <view class="control-buttons">
            <u-button
                v-for="(btn, btnIndex) in item.buttons"
                :key="btnIndex"
                :plain="true" :hairline="true"
                :class="getButtonClass(btn)"
                size="mini"
                @click="handleButtonClick(btn.text,btn.action)"
            >
              {{ btn.text }}
            </u-button>
          </view>
        </view>
        <!-- 单电机控制器按键组 -->
        <view class="motor-control-section">
          <view class="section-title">单电机控制</view>
          <view class="motor-control-buttons">
            <!-- 第一行 -->
            <view class="button-row">
              <u-button
                  :plain="true" :hairline="true"
                  class="motor-control-btn"
                  type="primary"
                  size="medium"
                  @click="handleMotorControl('stop')"
              >
                停止
              </u-button>
              <u-button
                  :plain="true" :hairline="true"
                  class="motor-control-btn"
                  type="primary"
                  size="medium"
                  @click="handleMotorControl('motor1East')"
              >
                电机1向东
              </u-button>
              <u-button
                  :plain="true" :hairline="true"
                  class="motor-control-btn"
                  type="primary"
                  size="medium"
                  @click="handleMotorControl('motor1West')"
              >
                电机1向西
              </u-button>
            </view>

            <!-- 第二行 -->
            <view class="button-row">
              <u-button
                  :plain="true" :hairline="true"
                  class="motor-control-btn"
                  type="primary"
                  size="medium"
                  @click="handleMotorControl('motor2East')"
              >
                电机2向东
              </u-button>
              <u-button
                  :plain="true" :hairline="true"
                  class="motor-control-btn"
                  type="primary"
                  size="medium"
                  @click="handleMotorControl('motor2West')"
              >
                电机2向西
              </u-button>
              <view class="empty-button-space"></view> <!-- 空白占位 -->
            </view>
          </view>
        </view>
      </view>
      <DeviceStatusInfo/>
    </view>
    <u-modal :show="confirmShow" title="提示" :content='confirmContent' :showCancelButton=true  @cancel="cancel"  @confirm="confirm" ></u-modal>
  </view>
</template>

<script>
import BluetoothHeader from '@/pages/components/header.vue';
import DeviceStatusInfo from '@/pages/components/DeviceStatusInfo.vue';
import {writeRegister,heartbeat,getAgreement} from '@/utils/modbus.js';
export default {
  components: {
    BluetoothHeader,
    DeviceStatusInfo
  },
  data() {
    return {
      agreementTypeName: '',
      communicationLink_set: false,
      communicationTimer_set: null,
      selectAction: '',
      currentDateTime: '0000-00-00 00:00:00',
      currentTab: 0,
      rxCount: 0,
      txCount: 0,
      confirmShow: false,
      confirmContent: '是否确定执行该操作？',
      workMode: '', // 添加工作模式变量
      indicators1: [
        {name: 'tilt', label: '倾角', value: false},
        {name: 'limit', label: '限位', value: false},
        {name: 'overcurrent', label: '过流', value: false}
      ],
      indicators2: [
        {name: 'rtc', label: 'RTC', value: false},
        {name: 'wind', label: '大风', value: false},
        {name: 'undervoltage', label: '欠压', value: false}
      ],
      sensorControls: [
        {
          name: 'sunAltitude',
          label: '太阳高度角',
          value: '',
          buttons: [
            {text: '自动', action: 'auto', type: 'primary'}
          ]
        },
        {
          name: 'sunAzimuth',
          label: '太阳方位角',
          value: '',
          buttons: [
            {text: '手动', action: 'manual', type: 'primary'},
            {text: '标定', action: 'calibrate', type: 'primary'}
          ]
        },
        {
          name: 'targetAngle',
          label: '目标角度',
          value: '',
          buttons: [
            {text: '向东', action: 'east', type: 'primary'},
            {text: '放平', action: 'level', type: 'primary'}
          ]
        },
        {
          name: 'angle1',
          label: '角度1',
          value: '',
          buttons: [
            {text: '向西', action: 'west', type: 'primary'},
            {text: '雪', action: 'snow', type: 'primary'}
          ]
        },
        {
          name: 'angle2',
          label: '角度2',
          value: '',
          buttons: [
            {text: '雨', action: 'rain', type: 'primary'},
            {text: '风', action: 'wind', type: 'primary'}
          ]
        },
        {
          name: 'motor1Current',
          label: '电机1电流(A)',
          value: '',
          buttons: []
        },
        {
          name: 'motor2Current',
          label: '电机2电流(A)',
          value: '',
          buttons: []
        },
        {
          name: 'temperature',
          label: '温度(°)',
          value: '',
          buttons: []
        },
        {
          name: 'voltage',
          label: '电压(V)',
          value: '',
          buttons: [
            {text: '校正时间', action: 'calibrateTime', type: 'primary', number: 1}
          ]
        }
      ]
    }
  },

  onShow() {
    this.agreementTypeName = getAgreement();
  },
  methods: {
    // 处理电机控制按钮点击
    handleMotorControl(action) {
      // 检查是否处于手动模式
      if (this.workMode !== '手动') {
        uni.showToast({
          title: '请先切换到手动模式',
          icon: 'none',
          duration: 2000
        });
        return;
      }

      this.motorControlAction = action;

      // 设置确认对话框内容
      let actionText = '';
      switch(action) {
        case 'stop':
          actionText = '停止';
          break;
        case 'motor1East':
          actionText = '电机1向东';
          break;
        case 'motor1West':
          actionText = '电机1向西';
          break;
        case 'motor2East':
          actionText = '电机2向东';
          break;
        case 'motor2West':
          actionText = '电机2向西';
          break;
      }

      this.confirmContent = `是否确定执行${actionText}操作？`;
      this.confirmShow = true;
    },
    // 处理从子组件传递过来的蓝牙数据
    handleBleDataReceived(data) {
      console.log('在父组件中接收到蓝牙数据:', data);
      this.updateSensorData(data);
    },
    cancel(){
      this.confirmShow = false
      this.motorControlAction = ''; // 重置电机控制动作
    },
    confirm() {
      if (this.motorControlAction === ''){
        switch (this.selectAction) {
          case 'auto': // 自动
            writeRegister("READ_AUTO",null);
            break
          case 'manual': // 手动
            writeRegister("READ_MANUAL",null)
            break
          case 'calibrate':  // 标定
            // writeRegister("WRITE_REGISTER",null)
            break
          case 'east': // 向东
            writeRegister("READ_DOWN",null)
            break
          case 'level': // 放平
            writeRegister("FLATTEN",null)
            break
          case 'west': // 向西
            writeRegister("READ_UP",null)
            break
          case 'snow': // 雪
            writeRegister("SNOW",null)
            break
          case 'rain': // 雨
            writeRegister("RAIN",null)
            break
          case 'wind': // 风
            writeRegister("WIND",null)
            break
          case 'calibrateTime':  // 校正时间
            writeRegister("READ_TIME",this.getCurrentTimeValues())
            break
          case 'cancel': //取消
            writeRegister("READ_CANCEL",null)
        }
      }
      // 添加电机控制处理
      switch(this.motorControlAction) {
        case 'stop':
          writeRegister("READ_MOTOR_STOP", null);
          break;
        case 'motor1East':
          writeRegister("READ_MOTOR1_EAST", null);
          break;
        case 'motor1West':
          writeRegister("READ_MOTOR1_WEST", null);
          break;
        case 'motor2East':
          writeRegister("READ_MOTOR2_EAST", null);
          break;
        case 'motor2West':
          writeRegister("READ_MOTOR2_WEST", null);
          break;
      }
      // 重置电机控制动作
      this.motorControlAction = '';
      this.confirmShow = false;
      uni.showToast({
        title: '操作执行成功！',
        icon: 'success',
        duration: 2000
      });
    },
    handleButtonClick(text,action) {
      console.log(action)
      this.selectAction = action;
      this.confirmContent = `是否确定执行`+text+`相关的操作？`;
      this.confirmShow = true;
    },
    // 获取按钮的class
    getButtonClass(btn) {
      // 建立action与工作模式的映射关系
      const actionToModeMap = {
        'auto': '自动',
        'manual': '手动',
        'level': '放平',
        'snow': '雪',
        'rain': '雨',
        'wind': '风',
        'east':'向东',
        'west':'向西',
      };

      let classes = ['btn-broder'];

      // 添加宽度类
      if (btn.number == 1) {
        classes.push('one-btn');
      }

      // 如果是工作模式按钮且与当前工作模式匹配，则添加绿色背景类
      if (actionToModeMap[btn.action] && this.workMode === actionToModeMap[btn.action]) {
        classes.push('active-work-mode');
      }

      return classes;
    },
    updateSensorData(data) {
      // 根据蓝牙数据更新传感器值
      this.sensorControls.forEach(control => {
        switch (control.name) {
          case 'sunAltitude': // 太阳高度角
            if (data.qEleAngle_53 !== undefined) {
              control.value = data.qEleAngle_53
            }
            break
          case 'sunAzimuth': // 太阳方位角
            if (data.qAzimuth_54 !== undefined) {
              control.value = data.qAzimuth_54
            }
            break
          case 'targetAngle': // 目标角度
            if (data.qTargetAngle_42 !== undefined) {
              control.value = data.qTargetAngle_42
            }
            break
          case 'angle1': // 角度1
            if (data.qRealAngle_43 !== undefined) {
              control.value = data.qRealAngle_43
            }
            break
          case 'angle2': // 角度2
            if (data.qRealAngle_31 !== undefined) {
              control.value = data.qRealAngle_31
            }
            break
          case 'motor1Current': // 电机1电流
            if (data.MotorCurrent_30 !== undefined) {
              control.value = data.MotorCurrent_30
            }
            break
          case 'motor2Current': // 电机2电流
            if (data.MotorCurrent_35 !== undefined) {
              control.value = data.MotorCurrent_35
            }
            break
          case 'temperature': // 温度
            if (data.Temperature_33 !== undefined) {
              control.value = data.Temperature_33
            }
            break
          case 'voltage': // 电压
            if (data.Battery_32 !== undefined) {
              control.value = data.Battery_32
            }
            break
        }
      })

      console.log('WorkModle_41:',data.WorkModle_41);
      // 根据C++中的工作模式解析逻辑更新workMode
      if (data.WorkModle_41 !== undefined) {
        const workModeBits = data.WorkModle_41.toString();
        switch (workModeBits) {
          case "100000": // 自动
            this.workMode = '自动'
            break
          case "10000": // 手动
            this.workMode = '手动'
            break
          case "1000000": // 放平
            this.workMode = '放平'
            break
          case "1000000000": // 雨
            this.workMode = '雨'
            break
          case "100000000": // 雪
            this.workMode = '雪'
            break
          case "10000000000": // 风
            this.workMode = '风'
            break
          case "10000000": // 指定
            this.workMode = '指定'
            break
          case "11000": // 向东
            this.workMode = '向东'
            break
          case "10100": // 向西
            this.workMode = '向西'
            break
          default:
            this.workMode = '未知模式'
            break
        }
      }

      if (data.Message_40 !== undefined) {
        // 根据二进制字符串更新指示器状态
        const messageBits = data.Message_40.toString()
        console.log('messageBits:',messageBits)
        // 清除所有状态
        this.indicators1.forEach(item => item.value = false)
        this.indicators2.forEach(item => item.value = false)

        // 根据实际协议确定位的含义
        if(messageBits === "100") {
          this.indicators1[0].value = true // 倾角
        } else if(messageBits === "10") {
          this.indicators1[2].value = true // 过流
        } else if(messageBits === "1") {
          this.indicators1[1].value = true // 限位
        } else if(messageBits === "110") {
          this.indicators1[2].value = true // 过流
          this.indicators1[1].value = true // 限位
        } else if(messageBits === "101") {
          this.indicators1[0].value = true // 倾角
          this.indicators1[2].value = true // 过流
        } else if(messageBits === "11") {
          this.indicators1[1].value = true // 限位
          this.indicators1[2].value = true // 过流
        } else if(messageBits === "111") {
          this.indicators1[0].value = true // 倾角
          this.indicators1[1].value = true // 限位
          this.indicators1[2].value = true // 过流
        }
      }

      // 更新时间显示
      if (data.nowtime !== undefined) {
        this.currentDateTime = data.nowtime
      }

      // 设置6秒后将 communicationLink_set 设置为 false 的定时器
      this.communicationTimer_set = setTimeout(() => {
        this.communicationLink_set = false
        this.communicationTimer_set = null
      }, 5000)
    },
    getCurrentTimeValues(){
      const now = new Date();
      // 获取各个时间组件
      const year = now.getFullYear();        // 年份 (例如: 2024)
      const month = now.getMonth() + 1;      // 月份 (0-11, 需要+1变为1-12)
      const day = now.getDate();             // 日期 (1-31)
      const hours = now.getHours();          // 小时 (0-23)
      const minutes = now.getMinutes();      // 分钟 (0-59)
      const seconds = now.getSeconds();      // 秒 (0-59)

      // 返回时间值数组，每个值都是16位整数
      return [
        year,      // 年
        month,     // 月
        day,       // 日
        hours,     // 时
        minutes,   // 分
        seconds    // 秒
      ];
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  background-color: #f5f5f5;
  height: calc(100vh - 120px);
  display: flex;
  flex-direction: column;
}


.main-content {
  flex: 1;
  padding: 20rpx;
  height: 100%;
}

.work-mode-display {
  background-color: #fff;
  padding: 20rpx;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  text-align: center;

  .work-mode-text {
    font-size: 28rpx;
    font-weight: bold;
    color: #333;
  }
}

.datetime-box {
  background-color: #fff;
  padding: 30rpx;
  border-radius: 16rpx;
  margin-bottom: 20rpx;
  text-align: center;

  .datetime-text {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
  }
}

.status-indicators {
  background-color: #fff;
  padding: 20rpx;
  border-radius: 16rpx;
  margin-bottom: 20rpx;

  .indicator-row {
    display: flex;
    justify-content: space-around;
    align-items: center;
    margin-bottom: 20rpx;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .indicator-item {
    display: flex;
    align-items: center;
    justify-content: center;
    flex: 1;
    text-align: center;
    gap: 10rpx;
  }

  .indicator-text {
    font-size: 24rpx;
    color: #666;
  }
}

.sensor-controls {
  background-color: #fff;
  border-radius: 16rpx;
  overflow: auto;
  height: calc(100% - 390rpx);

  .control-item {
    display: flex;
    align-items: center;
    padding: 20rpx;
    border-bottom: 1rpx solid #f0f0f0;

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

  .control-label {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: #fff;
    padding: 10rpx 20rpx;
    border-radius: 8rpx;
    font-size: 24rpx;
    width: 240rpx;
    text-align: center;
    margin-right: 20rpx;
  }

  .control-value {
    background-color: #f8f9fa;
    padding: 10rpx 20rpx;
    border-radius: 8rpx;
    font-size: 28rpx;
    font-weight: bold;
    color: #333;
    width: 140rpx;
    height: 60rpx;
    text-align: center;
    margin-right: 20rpx;
  }

  .control-buttons {
    display: flex;
    gap: 20rpx;
  }

  .u-button--mini {
    width: 120rpx;
  }
}

.one-btn {
  width: 240rpx !important;
}

.btn-broder {
  border: 1rpx solid #dadbde;
}

// 活跃的工作模式按钮样式
.active-work-mode {
  background-color: #00ff00 !important; // 绿色背景
  color: #000 !important;
  border-color: #00ff00 !important;
}

.status-indicator {
  width: 20rpx;
  height: 20rpx;
  border-radius: 50%;
  background-color: #ccc;
  margin-right: 10rpx;

  &.active {
    background-color: red;
  }
}
.typeSelect{
  font-size: 16px;
  color: #fff;
  font-weight: 600;
  display: flex;
}

.text-lable{
  color: #fff;
  font-size: 12px;
}

.motor-control-section {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 20rpx;
  margin-top: 20rpx;
}

.section-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  text-align: center;
}

.motor-control-buttons {
  .button-row {
    display: flex;
    justify-content: space-between;
    margin-bottom: 20rpx;

    &:last-child {
      margin-bottom: 0;
    }
  }

  .motor-control-btn {
    flex: 1;
    margin: 0 10rpx;

    &:first-child {
      margin-left: 0;
    }

    &:last-child {
      margin-right: 0;
    }
  }

  .empty-button-space {
    flex: 1;
    margin: 0 10rpx;
  }
}
</style>
