<template>
	<view class="container">

    <!-- 头部区域 -->
    <BluetoothHeader
        @ble-data-received="handleBleDataReceived"
    />
	
	
		<view class="main-content">
			<!-- 接收窗口 -->
			<view class="receive-section">
				<text class="section-title">接收窗口</text>
				<view class="receive-window">
					<scroll-view scroll-y="true" class="receive-textarea">
            <view
                v-for="(log, index) in sortedWriteLogs"
                :key="index"
                class="log-item"
            >
              <view class="log-time">{{log.time}}{{log.data}}</view>
            </view>
					</scroll-view>
				</view>
			</view>


			<!-- 输入控制区域 -->
			<view class="input-section">

        <u-row customStyle="margin-bottom: 10px" gutter="10">
          <u-col span="8">
            <u-input
                v-model="inputValue"
                placeholder="输入指令"
                class="command-input"
            ></u-input>
          </u-col>
          <u-col span="4">
            <u-checkbox-group
                placement="column">
              <u-checkbox v-model="cmdChecked" label="cmd" @change="changeCmd"></u-checkbox>
            </u-checkbox-group>
          </u-col>
        </u-row>
        <!-- 操作按钮 -->
        <u-row justify="end" customStyle="margin-bottom: 10px">
          <u-col span="4">
            <u-button type="info" size="mini" class="write-btn"  @click="sendMsg">指令发送</u-button>
          </u-col>
        </u-row>


        <u-row customStyle="margin-bottom: 10px" gutter="10">
          <u-col span="6">
            <u-button text="清空发送" @click="removeLogsByType('rx')"></u-button>
          </u-col>
          <u-col span="6">
            <u-button text="清空接受" @click="removeLogsByType('tx')"></u-button>
          </u-col>
        </u-row>

			</view>
		</view>
    <DeviceStatusInfo/>
	</view>
</template>

<script>
  import ecBLEApp from '@/utils/ecBLE/ecBLEApp.js';
  import {getAgreement} from '@/utils/modbus.js';
  import BluetoothHeader from '@/pages/components/header.vue';
  import DeviceStatusInfo from '@/pages/components/DeviceStatusInfo.vue';

  export default {
    components: {BluetoothHeader,DeviceStatusInfo},
		data() {
			return {
        agreementTypeName:'',
        communicationLink: false,
        communicationTimer_3: null, // 添加这一行用于保存定时器 ID
        writeLogs: [],
        showSex: false,
        checkboxValue1: [],
				inputValue: '',
				cmdChecked: false,
				carriageReturnChecked: false,
				wtypeValue: '',
				wtypeChecked: false,
				componentType: '单面',
				activeTab: 'receive',
				componentList: [
					{ name: '单面'},
					{ name: '双面'},
					{ name: '多面'}
				]
			}
		},
    onShow() {
      // 从全局变量加载日志
      this.writeLogs = ecBLEApp.getGlobalWriteLogs()
      // 添加监听器以实时更新
      ecBLEApp.addLogListener(this.onLogUpdate);
      this.agreementTypeName = getAgreement();
    },

    onHide() {
      // 移除监听器
      ecBLEApp.removeLogListener(this.onLogUpdate)
    },
    computed: {
      // 修改排序计算属性
      sortedWriteLogs() {
        return this.writeLogs.slice().sort((a, b) => {
          return new Date(b.time) - new Date(a.time); // 倒序排列
        });
      }
    },

		methods: {
      // 处理从子组件传递过来的蓝牙数据
      handleBleDataReceived(data) {
        console.log('在父组件中接收到蓝牙数据:', data);
        this.updateSensorData(data);
      },
      updateSensorData(data) {

      },
      sendMsg(){
        uni.showModal({
          title: '提示',
          content: `是否确定发送消息`+this.inputValue+`?`,
          success: (res) => {
            if (res.confirm) {
              ecBLEApp.writeBLECharacteristicValueTwo(this.inputValue,!this.cmdChecked);
            }
          }
        });
      },
      changeCmd(e) {
        this.cmdChecked = e
      },
      changeWtype(e){
        this.wtypeChecked = e
      },
      // 日志更新回调
      onLogUpdate(logs) {
        // this.writeLogs = [...logs] // 创建新数组以触发响应式更新
        this.writeLogs.splice(0, this.writeLogs.length, ...logs)
      },
      loadLogs() {
        // 从全局变量获取日志
        const newLogs = ecBLEApp.getGlobalWriteLogs()
        // 使用数组变更方法保持响应式
        this.writeLogs.splice(0, this.writeLogs.length, ...newLogs)
      },
      selectValue(e) {
        this.componentType = e.name
      },
			switchTab(tab) {
				this.activeTab = tab;
			},
			sendCommand() {
				// 发送指令逻辑
				console.log('发送指令:', this.inputValue);
			},
			writeType() {
				// 类型写入逻辑
				console.log('写入类型:', this.wtypeValue);
			},
			clearSend() {
				this.inputValue = '';
			},
			clearReceive() {
				// 清空接收窗口
				console.log('清空接收窗口');
			},
      removeLogsByType(type) {
        uni.showModal({
          title: '确认删除',
          content: `确定要删除所有类型为 '${type}' 的日志吗？`,
          success: (res) => {
            if (res.confirm) {
              const result = ecBLEApp.removeWriteDataByType(type)
              if (result.success) {
                uni.showToast({
                  title: `已删除${result.deletedCount}条日志`,
                  icon: 'success'
                })
                // 重新加载日志
                this.loadLogs();
                console.log('删除日志结果:', result)
                console.log(this.writeLogs)
              } else {
                uni.showToast({
                  title: '删除失败',
                  icon: 'none'
                })
              }
            }
          }
        })
      },
		}
	}
</script>

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

.container {
	height: calc(100vh - 120px);
	display: flex;
	flex-direction: column;
	background-color: #f5f5f5;
}


.status-bar {
	height: 60rpx;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 0 20rpx;
	color: white;
	font-size: 24rpx;
}

.status-left {
	display: flex;
	align-items: center;
	gap: 20rpx;
}

.status-center {
	flex: 1;
	text-align: center;
}

.app-title {
	font-size: 32rpx;
	font-weight: bold;
}

.status-right {
	display: flex;
	align-items: center;
	gap: 10rpx;
}

.network-info {
	font-size: 20rpx;
}

.signal {
	font-size: 20rpx;
}

.signal-bars {
	display: flex;
	gap: 2rpx;
}

.bar {
	width: 4rpx;
	height: 12rpx;
	background-color: white;
	border-radius: 1rpx;
}

.battery {
	font-size: 20rpx;
}

.main-content {
	flex: 1;
	padding: 20rpx;
	background-color: #f5f5f5;
  height: calc(100% - 140rpx);
}

.receive-section {
	margin-bottom: 30rpx;
}

.section-title {
	font-size: 28rpx;
	font-weight: bold;
	color: #333;
	margin-bottom: 10rpx;
	display: block;
}

.receive-window {
	background-color: white;
	border-radius: 10rpx;
	border: 2rpx solid #e0e0e0;
	height: 40vh;
  overflow: auto;
}

.receive-textarea {
	height: 100%;
	padding: 20rpx;
}

.placeholder-text {
	color: #999;
	font-size: 24rpx;
}

.input-section {
	background-color: white;
	border-radius: 10rpx;
	padding: 20rpx;
}

.input-row {
	display: flex;
	align-items: center;
	margin-bottom: 20rpx;
	gap: 20rpx;
}

.input-group {
	display: flex;
	align-items: center;
	flex: 1;
	gap: 10rpx;
}

.command-input, .wtype-input {
	flex: 1;
}

.scroll-btn {
	width: 60rpx;
	height: 60rpx;
}

.checkbox-group {
	display: flex;
	align-items: center;
}

.send-btn {
	width: 120rpx;
}

.component-section {
	margin-bottom: 20rpx;
}

.component-select {
	width: 100%;
}

.wtype-section {
	margin-bottom: 20rpx;
}

.write-btn {
  padding: 2px;
  color: #a7a7a7;
  margin: 5px;
  height: 30px;
}

.action-buttons {
	display: flex;
	gap: 20rpx;
	margin-bottom: 20rpx;
}

.clear-btn {
	flex: 1;
}

.device-info {
	display: flex;
	align-items: center;
	gap: 10rpx;
  margin-bottom: 10px;
}

.info-label {
	font-size: 28rpx;
	color: #333;
}

.info-value {
	font-size: 28rpx;
	color: #666;
}

::v-deep .input-section .u-button--mini{
  width: 100px !important;
  height: 30px !important;
}
.typeSelect{
  font-size: 16px;
  color: #fff;
  font-weight: 600;
  display: flex;
}
</style>
