<template>
	<view class="page">
		<u-navbar :is-back="false" :border-bottom="false" :background="bgc" title-color='#2E4975' title-size='36'
			height='8'></u-navbar>
		<view class="title">
			<image src="https://api.ccttiot.com/smartmeter/img/static/uhRjXxrVaNwOCld2fYUl" mode=""></image>
		</view>
		<!-- 背景图 -->
		<!-- 没设备时展示 -->
		<image class="bjimg" v-if="bjflag" src="https://api.ccttiot.com/smartmeter/img/static/uz8MR6BuZW2qRANnYgLu"
			mode=""></image>
		<!-- 有设备时展示 -->
		<image class="bjimg" v-else src="https://api.ccttiot.com/smartmeter/img/static/uXBpJuaUs0XUNb8HTahh" mode="">
		</image>
		<view class="wusb" v-if="bjflag">
			<text>暂无设备，请先绑定设备</text>
			<view class="bang" @click="btnaddsb">
				绑定
			</view>
		</view>
		<view class="" v-else>
			<view class="selectbox">
				<view class="shebeiname" >
					<view class="" @click="btnksxz">
						{{user.deviceName == undefined ? '--' : user.deviceName}}
						<image style="width: 32rpx;height: 26rpx;margin-left: 14rpx;" v-if="!xuanzeflag" src="https://api.ccttiot.com/smartmeter/img/static/uwHOBxvbJjkhx1uDiQHI" mode=""></image>
						<image style="width: 32rpx;height: 26rpx;margin-left: 14rpx;" v-else class="rotated-image" src="https://api.ccttiot.com/smartmeter/img/static/uwHOBxvbJjkhx1uDiQHI" mode=""></image>
					</view> <text style="background-color: red;box-shadow: 0rpx 0rpx 10rpx 0rpx red, 0rpx 0rpx 30rpx 0rpx red" v-if="vardataflag == 1 || vardataflag == 2"></text> <text v-else></text> 
					<view class="lj" @click="btnlj" v-if="vardataflag == 1">
						点击连接
					</view>
					<view class="lj" @click="btnlj" v-if="vardataflag == 2">
						连接中
					</view>
					<view class="lj" style="color: #15C55D;border: 1px solid #15C55D;" @click="btnlj" v-if="vardataflag == 3">
						已连接
					</view>
				</view>
				<view class="selectshezhi" style="display: flex;">
					<image @click="btnsz" src="https://api.ccttiot.com/smartmeter/img/static/uvCJ8ro0MpfGZd53vypJ" mode=""></image>
				</view>
			</view>
			<!-- 设备信息 -->
			<view class="devicebox"> 
				<view class="devicetop">
					<view class="devicelt" @click="btnsz">
						<image :src="imgpic" mode="aspectFit"></image>
						<view class="xinghao">
							<view class="one">型号：{{user.model == undefined ? '--' : user.model}}</view>
								<view class="">MAC：{{user.mac == undefined ? '--' : user.mac}}</view>
						</view>
					</view>
					<view style="color: red;font-size: 26rpx;display: flex;align-items: center;" v-if=" ver != '' && ver.slice(3) != version" @click="btnsz">
						<text style="display: inline-block;width: 10rpx;height: 10rpx;border-radius: 50%;background-color: red;margin-right: 10rpx;"></text>可更新
					</view>
				</view>
				<view class="deviceweek" v-if="pre == 'WATER'" @click="btntime">
					<view class="weeklist">
						<view class="" v-if="!ver_data.p_set1 || ver_data.p_set1[3] == 0">
							<view class="kg" style="color: rgba(0, 0, 0, .3);" v-if="!ver_data.p_set1 || ver_data.p_set1[3] == 0">
								OFF
							</view>
							<view class="weekday" style="color: rgba(0,0,0,.3);">
								P1
							</view>
							<view class="time" style="color: rgba(0,0,0,.3);">
								{{ver_data.p_set1 && ver_data.p_set1[0] !== undefined ? ver_data.p_set1[0].toString().padStart(2, '0') + ':' + ver_data.p_set1[1].toString().padStart(2, '0') : '--:--'}}
							</view>
							<view class="interval" style="color: rgba(0,0,0,.3);" v-if="ver_data.p_set1 && ver_data.p_set1[4] > 1">
								 每{{ver_data.p_set1[4]}}天
							</view>
							<view style="color: rgba(0,0,0,.3);" class="interval" v-else>
								每天
							</view>
						</view>
						<view class="" v-else>
							<view class="kg" style="color: #48893B;">
								ON
							</view>
							<view class="weekday">
								P1
							</view>
							<view class="time">
								{{ver_data.p_set1 && ver_data.p_set1[0] !== undefined ? ver_data.p_set1[0].toString().padStart(2, '0') + ':' + ver_data.p_set1[1].toString().padStart(2, '0') : '--:--'}}
							</view>
							<view class="interval" v-if="ver_data.p_set1 && ver_data.p_set1[4] > 1">
								 每{{ver_data.p_set1[4]}}天
							</view>
							<view class="interval" v-else>
								每天
							</view>
						</view>
						<view class="img">
							<image v-if="shouldShowIcon(1)"
							    src="https://api.ccttiot.com/smartmeter/img/static/u9iZpd6bW6bUsUay4uvH" mode="">
							</image>
						</view>
					</view>
					<view class="weeklist">
						<view class="" v-if="!ver_data.p_set2 || ver_data.p_set2[3] == 0">
							<view class="kg" style="color: rgba(0, 0, 0, .3);" v-if="!ver_data.p_set2 || ver_data.p_set2[3] == 0">
								OFF
							</view>
							<view class="weekday" style="color: rgba(0,0,0,.3);">
								P2
							</view>
							<view class="time" style="color: rgba(0,0,0,.3);">
								{{ver_data.p_set2 && ver_data.p_set2[0] !== undefined ? ver_data.p_set2[0].toString().padStart(2, '0') + ':' + ver_data.p_set2[1].toString().padStart(2, '0') : '--:--'}}
							</view>
							<view class="interval" style="color: rgba(0,0,0,.3);" v-if="ver_data.p_set2 && ver_data.p_set2[4] > 1">
								每{{ver_data.p_set2[4]}}天
							</view>
							<view style="color: rgba(0,0,0,.3);" class="interval" v-else>
								每天
							</view>
						</view>
						<view class="" v-else>
							<view class="kg" style="color: #48893B;">
								ON
							</view>
							<view class="weekday">
								P2
							</view>
							<view class="time">
								{{ver_data.p_set2 && ver_data.p_set2[0] !== undefined ? ver_data.p_set2[0].toString().padStart(2, '0') + ':' + ver_data.p_set2[1].toString().padStart(2, '0') : '--:--'}}
							</view>
							<view class="interval" v-if="ver_data.p_set2 && ver_data.p_set2[4] > 1">
								每{{ver_data.p_set2[4]}}天
							</view>
							<view class="interval" v-else>
								每天
							</view>
						</view>
						<view class="img">
							<image v-if="shouldShowIcon(2)"
								src="https://api.ccttiot.com/smartmeter/img/static/u9iZpd6bW6bUsUay4uvH" mode="">
							</image>
						</view>
					</view>
					<view class="weeklist">
						<view class="" v-if="!ver_data.p_set3 || ver_data.p_set3[3] == 0">
							<view class="kg" style="color: rgba(0, 0, 0, .3);" v-if="!ver_data.p_set3 || ver_data.p_set3[3] == 0">
								OFF
							</view>
							<view class="weekday" style="color: rgba(0,0,0,.3);">
								P3
							</view>
							<view class="time" style="color: rgba(0,0,0,.3);">
								{{ver_data.p_set3 && ver_data.p_set3[0] !== undefined ? ver_data.p_set3[0].toString().padStart(2, '0') + ':' + ver_data.p_set3[1].toString().padStart(2, '0') : '--:--'}}
							</view>
							<view class="interval" style="color: rgba(0,0,0,.3);" v-if="ver_data.p_set3 && ver_data.p_set3[4] > 1">
								 每{{ver_data.p_set3[4]}}天
							</view>
							<view style="color: rgba(0,0,0,.3);" class="interval" v-else>
								每天
							</view>
						</view>
						<view class="" v-else>
							<view class="kg" style="color: #48893B;">
								ON
							</view>
							<view class="weekday">
								P3
							</view>
							<view class="time">
								{{ver_data.p_set3 && ver_data.p_set3[0] !== undefined ? ver_data.p_set3[0].toString().padStart(2, '0') + ':' + ver_data.p_set3[1].toString().padStart(2, '0') : '--:--'}}
							</view>
							<view class="interval" v-if="ver_data.p_set3 && ver_data.p_set3[4] > 1">
								 每{{ver_data.p_set3[4]}}天
							</view>
							<view class="interval" v-else>
								每天
							</view>
						</view>
						<view class="img">
							<image v-if="shouldShowIcon(3)"
								src="https://api.ccttiot.com/smartmeter/img/static/u9iZpd6bW6bUsUay4uvH" mode="">
							</image>
						</view>
					</view>
					<view class="weeklist">
						<view class="" v-if="!ver_data.p_set4 || ver_data.p_set4[3] == 0">
							<view class="kg" style="color: rgba(0, 0, 0, .3);" v-if="!ver_data.p_set4 || ver_data.p_set4[3] == 0">
								OFF
							</view>
							<view class="weekday" style="color: rgba(0,0,0,.3);">
								P4
							</view>
							<view class="time" style="color: rgba(0,0,0,.3);">
								{{ver_data.p_set4 && ver_data.p_set4[0] !== undefined ? ver_data.p_set4[0].toString().padStart(2, '0') + ':' + ver_data.p_set4[1].toString().padStart(2, '0') : '--:--'}}
							</view>
							<view class="interval" style="color: rgba(0,0,0,.3);" v-if="ver_data.p_set4 && ver_data.p_set4[4] > 1">
								每{{ver_data.p_set4[4]}}天
							</view>
							<view style="color: rgba(0,0,0,.3);" class="interval" v-else>
								每天
							</view>
						</view>
						<view class="" v-else>
							<view class="kg" style="color: #48893B;">
								ON
							</view>
							<view class="weekday">
								P4
							</view>
							<view class="time">
								{{ver_data.p_set4 && ver_data.p_set4[0] !== undefined ? ver_data.p_set4[0].toString().padStart(2, '0') + ':' + ver_data.p_set4[1].toString().padStart(2, '0') : '--:--'}}
							</view>
							<view class="interval" v-if="ver_data.p_set4 && ver_data.p_set4[4] > 1">
								每{{ver_data.p_set4[4]}}天
							</view>
							<view class="interval" v-else>
								每天
							</view>
						</view>
						<view class="img">
							<image v-if="shouldShowIcon(4)"
								src="https://api.ccttiot.com/smartmeter/img/static/u9iZpd6bW6bUsUay4uvH" mode="">
							</image>
						</view>
					</view>
					<view class="weeklist">
						<view class="" v-if="!ver_data.p_set5 || ver_data.p_set5[3] == 0">
							<view class="kg" style="color: rgba(0, 0, 0, .3);" v-if="!ver_data.p_set5 || ver_data.p_set5[3] == 0">
								OFF
							</view>
							<view class="weekday" style="color: rgba(0,0,0,.3);">
								P5
							</view>
							<view class="time" style="color: rgba(0,0,0,.3);">
								{{ver_data.p_set5 && ver_data.p_set5[0] !== undefined ? ver_data.p_set5[0].toString().padStart(2, '0') + ':' + ver_data.p_set5[1].toString().padStart(2, '0') : '--:--'}}
							</view>
							<view class="interval" style="color: rgba(0,0,0,.3);" v-if="ver_data.p_set5 && ver_data.p_set5[4] > 1">
								每{{ver_data.p_set5[4]}}天
							</view>
							<view style="color: rgba(0,0,0,.3);" class="interval" v-else>
								每天
							</view>
						</view>
						<view class="" v-else>
							<view class="kg" style="color: #48893B;">
								ON
							</view>
							<view class="weekday">
								P5
							</view>
							<view class="time">
								{{ver_data.p_set5 && ver_data.p_set5[0] !== undefined ? ver_data.p_set5[0].toString().padStart(2, '0') + ':' + ver_data.p_set5[1].toString().padStart(2, '0') : '--:--'}}
							</view>
							<view class="interval" v-if="ver_data.p_set5 && ver_data.p_set5[4] > 1">
								每{{ver_data.p_set5[4]}}天
							</view>
							<view class="interval" v-else>
								每天
							</view>
						</view>
						<view class="img">
							<image v-if="shouldShowIcon(5)"
								src="https://api.ccttiot.com/smartmeter/img/static/u9iZpd6bW6bUsUay4uvH" mode="">
							</image>
						</view>
					</view>
					<view class="weeklist">
						<view class="" v-if="!ver_data.p_set6 || ver_data.p_set6[3] == 0">
							<view class="kg" style="color: rgba(0, 0, 0, .3);" v-if="!ver_data.p_set6 || ver_data.p_set6[3] == 0">
								OFF
							</view>
							<view class="weekday" style="color: rgba(0,0,0,.3);">
								P6
							</view>
							<view class="time" style="color: rgba(0,0,0,.3);">
								{{ver_data.p_set6 && ver_data.p_set6[0] !== undefined ? ver_data.p_set6[0].toString().padStart(2, '0') + ':' + ver_data.p_set6[1].toString().padStart(2, '0') : '--:--'}}
							</view>
							<view class="interval" style="color: rgba(0,0,0,.3);" v-if="ver_data.p_set6 && ver_data.p_set6[4] > 1">
								每{{ver_data.p_set6[4]}}天
							</view>
							<view style="color: rgba(0,0,0,.3);" class="interval" v-else>
								每天
							</view>
						</view>
						<view class="" v-else>
							<view class="kg" style="color: #48893B;">
								ON
							</view>
							<view class="weekday">
								P6
							</view>
							<view class="time">
								{{ver_data.p_set6 && ver_data.p_set6[0] !== undefined ? ver_data.p_set6[0].toString().padStart(2, '0') + ':' + ver_data.p_set6[1].toString().padStart(2, '0') : '--:--'}}
							</view>
							<view class="interval" v-if="ver_data.p_set6 && ver_data.p_set6[4] > 1">
								每{{ver_data.p_set6[4]}}天
							</view>
							<view class="interval" v-else>
								每天
							</view>
						</view>
						<view class="img">
							<image v-if="shouldShowIcon(6)"
								src="https://api.ccttiot.com/smartmeter/img/static/u9iZpd6bW6bUsUay4uvH" mode="">
							</image>
						</view>
					</view>
				</view>
				<view class="" style="margin-top: 18rpx;display: flex;justify-content: space-between;" v-else>
					<view class="" style="font-size: 24rpx;color: #50565A;text-align: center;margin-top: 10rpx;">
						<view class="" style="display: flex;align-items: center;">
							<image style="width:32rpx;height:32rpx;margin-right: 8rpx;" src="https://api.ccttiot.com/smartmeter/img/static/uhyYG0TLfWi9XUhTQz7D" mode=""></image>
							启动时间
						</view>
						<view class="" style="margin-top:10rpx;font-size: 36rpx;font-weight: 600;">
							{{csbobj.hour == undefined ? '--' : csbobj.hour + ':'}}{{csbobj.minute == undefined ? '' : csbobj.minute}}
						</view>
					</view>
					<view class="" style="font-size: 24rpx;color: #50565A;margin-top: 10rpx;text-align: center;">
						<view class="" style="display: flex;align-items: center;">
							<image style="width:32rpx;height:32rpx;margin-right: 8rpx;font-size: 36rpx;font-weight: 600;" src="https://api.ccttiot.com/smartmeter/img/static/uuQaK98cmdQQnPWus27Z" mode=""></image>
							工作时长
						</view>
						<view class="" style="margin-top:10rpx;font-size: 36rpx;font-weight: 600;">
							{{csbobj.second == undefined ? '--' : csbobj.second + '秒'}}
						</view>
					</view>
					<view class="" style="font-size: 24rpx;color: #50565A;margin-top: 10rpx;text-align: center;">
						<view class="" style="display: flex;align-items: center;">
							<image style="width:32rpx;height:32rpx;margin-right: 8rpx;font-size: 36rpx;font-weight: 600;" src="https://api.ccttiot.com/smartmeter/img/static/uM6Yz4xVqFwzW6xlTRph" mode=""></image>
							间隔天数
						</view>
						<view class="" style="margin-top:10rpx;font-size: 36rpx;font-weight: 600;">
							{{csbobj.day == undefined ? '--' : csbobj.day + '天'}}
						</view>
					</view>
				</view>
			</view>
			<!-- 开关选择 -->
			<view class="dangqian">
				<view class="" style="display: flex;">
					<image src="https://lxnapi.ccttiot.com/smartmeter/img/static/ufHmxq7KI9PJhv8ey4ds" mode=""></image>
					<view class="cen" @click="btntb">
						<view class="shen">
							当前时间 <text>同步</text>
						</view>
						<view class="">
							点击可同步当前时间
						</view>
					</view>
				</view>
				<view class="rt" style="display: flex;align-items: center;" @click="btnsztime">
					{{devicetime == '' ? '--' : devicetime.slice(0,5)}} <u-icon name="arrow-right" color="#7FAD76" size="32"></u-icon>
				</view>
			</view>
			<view class="switchbox">
				<view class="switch_he" v-if="pre == 'WATER'">
					<image src="https://api.ccttiot.com/smartmeter/img/static/u7NwkNOoQYYsvHVMkDlu" mode=""></image>
					<view class="yushui">
						雨水感应
						<u-switch v-if="yschecked" v-model="one" @change="btnyushui" inactive-color="#eee"
							active-color="#eee" size="40"></u-switch>
						<u-switch v-else v-model="ones" @change="btnyushuis" active-color="#7FAD76"
							inactive-color="#7FAD76" size="40"></u-switch>
					</view>
				</view>
				<view class="switch_he" v-if="pre == 'WATER'">
					<image src="https://api.ccttiot.com/smartmeter/img/static/u7kd92ocUgDN052nhp4R" mode=""></image>
					<view class="yushui">
						儿童锁 <u-switch v-if="etchecked" v-model="two" @change="btnertong" inactive-color="#eee"
							active-color="#eee" size="40"></u-switch>
						<u-switch v-else v-model="twos" @change="btnertongs" active-color="#7FAD76"
							inactive-color="#7FAD76" size="40"></u-switch>
					</view>
				</view>
			</view>
			<view class="" style="display: flex;justify-content: space-between;">
				<!-- 定时 -->
				<view class="dingshi_he" @click="btntime">
					<view class="naoz">
						<image src="https://api.ccttiot.com/smartmeter/img/static/uJPgzMejk9gaogWnCO9M" mode=""></image> <text v-if="pre == 'WATER'">6组</text>
					</view>
					<view class="dstime">
						定时管理 <image src="https://api.ccttiot.com/smartmeter/img/static/uagx3wGa7RYvqKqoSymy" mode="">
						</image>
					</view>
				</view>
				<!-- 手动浇水 -->
				<view class="dingshi_he">
					<view class="naoz" style="font-weight: 400;font-size: 26rpx;align-items: center;">
						<image style="width: 170rpx;" src="https://api.ccttiot.com/smartmeter/img/static/uVYXvo4F6U6fJ5fP27BT" mode="aspectFill"></image>{{ sdminutes ? sdminutes + ':' : '' }}{{ sdseconds ? sdseconds : '' }}
					</view>
					<view class="dstime">
						手动浇水 <u-switch v-if="kgflag" v-model="jskeds" @change="btngb"  inactive-color="#eee" active-color="#eee" size="40"></u-switch>
							<u-switch v-else v-model="jsked" @change="btnkq" active-color="#7FAD76" inactive-color="#7FAD76" size="40"></u-switch>
					</view>
				</view>
			</view>
			<!-- 浇水日志 -->
			<view class="wateringlogbox" v-if="pre == 'WATER'" @click="btnjs">
				<view class="wateringlogtop">
					<image src="https://api.ccttiot.com/smartmeter/img/static/uGh3pRM7mMRSHdmvtzv3" mode=""></image>
					浇水日志
				</view>
				<view class="wateringlogbd">
					<view class="lt" >
						<view class="">距离下次：{{xctime}}</view>
						<view class="">下次浇水时长：{{xctimesc}}</view>
						<view class="">上次浇水：{{sctimejs}}</view>
					</view>
					<view class="rt">
						<image src="https://api.ccttiot.com/smartmeter/img/static/uagx3wGa7RYvqKqoSymy" mode=""></image>
					</view>
				</view>
			</view>
			<view class="" @click="btnbc" v-if="pre == 'WATER'" style="width: 100%;height: 80rpx;background-color: #7FAD76;color: #fff;text-align: center;font-size: 32rpx;line-height: 80rpx;margin-top: 30rpx;border-radius: 20rpx;">
				保存定时设置
			</view>
		</view>
		<!-- 切换设备 -->
		<view class="tabsb" v-if="xuanzeflag">
			<view class="selectbox">
				<view class="selectname" @click="btnksxz">
					切换设备 <image v-if="!xuanzeflag" src="https://api.ccttiot.com/smartmeter/img/static/uwHOBxvbJjkhx1uDiQHI" mode=""></image>
					        <image v-else class="rotated-image" src="https://api.ccttiot.com/smartmeter/img/static/uwHOBxvbJjkhx1uDiQHI" mode=""></image>
				</view>
			</view>
			<view class="sblist">
				<view class="sbist_val" v-for="(item,index) in devicelist" :key="index" @click="btnactive(item.deviceId,index)">
					<view class="lt">
						<view class="">{{item.deviceName}}</view>
						<view class="" style="margin-top: 14rpx;color: ccc;font-size: 20rpx;font-weight: 400;">MAC:{{item.mac}}</view>
					</view>
					<view class="rt">
						<image :src="item.modelPicture" mode="aspectFit"></image>
					</view>
				</view>
			</view>
			<view class="qdan" @click="btnaddsb">
				添加新设备
			</view>
		</view>
		<view class="mask" v-if="xuanzeflag" @click="xuanzeflag = !xuanzeflag"></view>
		<!-- 手动浇水 -->
		<view class="manualjs" v-if="sdjsflag">
			<view class="toptit">
				选择浇水时长
			</view>
			<view class="container" @click="btnshowjs">
				<view class="">{{minute}}分</view>
				<text>:</text>
				<view class="">{{second}}秒</view>
			</view>
			<view class="anniu">
				<view class="qx" @click="btnqx">
					取消
				</view>
				<view class="qd" @click="btnqd">
					确定
				</view>
			</view>
		</view>
		<view class="manualmask" v-if="sdjsflag"></view>
		<!-- 选择浇水时间-->
		<u-picker v-model="showjs" mode="time" :default-time="00" :params="params" @confirm="confirm"></u-picker>
        <!-- 设置当前时间 -->
		<u-picker v-model="timeflag" mode="time" :params="paramss" @confirm="confirmtime"></u-picker>
		<tab-bar :indexs='0'></tab-bar>
        
	</view>
</template>

<script>
	var xBlufi = require("@/components/blufi/xBlufi.js")
	export default {
		data() {
			return {
				timeflag:false,
				one: false,
				ones: true,
				two: false,
				twos: true,
				jsked:true,
				jskeds:false,
				yschecked: true,
				etchecked: true,
				kgflag: true,
				activeshu: 0,
				xuanzeflag: false,
				selectedMinute: '1',
				selectedSecond: '1',
				sdjsflag: false,
				showjs: false,
				params: {
					year: false,
					month: false,
					day: false,
					hour: false,
					minute: true,
					second: true
				},
				paramss: {
					year: false,
					month: false,
					day: false,
					hour: true,
					minute: true,
					second: false
				},
				minute: '--',
				second: '--',
				hasShownVersionAlert: false,
				devicesList: [],
				deviceId: '',
				name: '',
				mac: '',
				jstime: '',
				ver_data: {},
				vardataflag:1,
				showobj: {},
				jstimeobj:{},
				xctime: '--',
				sctimejs: '--',
				xctimesc: '--',
				xctimesj: '',
				sdminutes: '',
				sdseconds: '',
				datalist: '',
				devicelist:[],
				shebid:'',
				user:{},
				lastChar:'',
				timer:'',
				bjflag:true, 
				userobj:{},
				devicesarr:[],
				intervalId: null,
				imgflag:true,
				ver:'',
				pre:'',
				csbobj:{},
				disconnectTimer: null,
				devicetime:'',
				imgpic:'',
				xinp:'',
				version:'',
				
				searchStartTime: 0,      // 记录开始搜索的时间戳
				    searchTimeout: 10000,    // 10秒超时（单位：毫秒）
				    searchTimer: null,       // 搜索定时器
				    isSearching: false       // 是否正在搜索中
			}
		},
		// 分享到好友（会话）
		onShareAppMessage: function() {
			return {
				title: '绿小能',
				path: '/pages/index/index'
			}
		},

		// 分享到朋友圈  
		onShareTimeline: function() {
			return {
				title: '绿小能',
				query: '',
				path: '/pages/index/index'
			}
		},
		onLoad() {
			 wx.openBluetoothAdapter({
			     success: function (res) {
			       console.log('蓝牙适配器初始化成功'); 
			     },
			   fail: function (err) {
			      console.error('蓝牙适配器初始化失败，可能是因为没有权限', err);
			    uni.showToast({
			       	title: '蓝牙适配器初始化失败，可能是因为没有权限',
			       	icon: 'none',
			       	duration:2000
			    })
			   }
			 }) 	
			 this.vardataflag = 1
			 xBlufi.initXBlufi(1)
			 let that = this
			 xBlufi.listenDeviceMsgEvent(true, that.funListenDeviceMsgEvent)
			 xBlufi.notifyStartDiscoverBle({
			 	'isStart': true
			 })
			 // setTimeout(()=>{
				//  that.btnlj()
			 // },1500)
		},
		onShow() {
			// 请求个人信息
			this.getinfo() 
			this.getshuju() // 页面加载时启动定时器
			xBlufi.listenDeviceMsgEvent(true, this.funListenDeviceMsgEvent)
		},
		mounted() {
		   
		},
		onHide() {
		    // 页面隐藏时清除定时器
		   this.clearTimer()
		   this.clearDisconnectTimer()
		},
		onUnload() {
		    // 页面卸载时清除定时器
		   this.clearTimer()
		   this.clearDisconnectTimer()
		},
		methods: {
			// 点击保存设置
			btnbc(){
				this.handleUserAction()
				if(this.vardataflag != 3){
					uni.showToast({
						title: '设备未连接',
						icon: 'none',
						duration:2000
					})
				}else{
					uni.showToast({
						title: '保存成功',
						icon: 'success',
						duration:2000
					})
					xBlufi.notifySendCustomData({
						customData: '11sleep' + this.xinp
					})
				}
			},
			getbanbens(){
				this.$u.get(`/app/model/${this.user.modelId}`).then(res => {
					if (res.code == 200) {
						this.version = res.data.version.slice(1)
						console.log(this.version,'this.versionthis.versionthis.version');
					}
				})
			},
			// 点击进行设备录入
			btnluru(){
				this.datalist = ''
				this.mac = ''
				this.ver_data = {}
				uni.reLaunch({
					url:'/pages/myorder/index'
				})
			},
			// 点击选择时间
			btnshowjs() {
				this.showjs = true
			}, 
            // 补零函数
			formattedTime(minutes, seconds) {
				// 将数字转换为字符串并补零  
				const formattedMinutes = String(minutes).padStart(2, '0')
				const formattedSeconds = String(seconds).padStart(2, '0')
				// 返回格式化后的时间字符串  
				console.log(`${formattedMinutes}:${formattedSeconds}`,'111111111')
				return `${formattedMinutes}:${formattedSeconds}`
			},
			// 静默登录
			jmlogin() {
				let taht = this
				wx.login({
					success(res) {
						if (res.code) {
							let data = {
								jsCode: res.code,
							}
							taht.$u.post(`/loginByopenid?jsCode=${res.code}`, data).then(res => {
								if (res.code == 200) {
									taht.getinfo()
									uni.setStorageSync('token', res.token)
								}else{
									
								}
							})
						}
					}
				})
			},
			// 获取用户信息
			getinfo() {
				this.$u.get(`/appVerify/profile`).then((res) => {
					if (res.code == 200) {
						this.userobj = res.data
						// 根据用户id获取当前用户
						this.getlist()
					}else if(res.code == 401){
						this.jmlogin()
					}
				})
			},
			// 获取设备列表
			getlist(){
				this.$u.get(`/app/getDeviceInfoByUser?userId=${this.userobj.userId}`).then((res) => {
					if (res.code == 200) {
						if(res.data.length > 0 || res.data != ''){
							this.bjflag = false
							this.devicelist = res.data
							this.imgpic = res.data[0].modelPicture
							this.mac = res.data[0].mac
							this.pre = res.data[0].pre
							this.deviceId = res.data[0].mac.match(/.{2}/g).reverse().join(':')
							this.user = res.data[0]
							this.shebid = res.data[0].deviceId
							this.getbanbens()
							let that = this
						}else{
							this.bjflag = true
						}
					}
				})
			},
			// 点击连接蓝牙函数
			btnlj() {
				console.log("进入111蓝牙连接")
				if (this.vardataflag != 3) {
					this.vardataflag = 2
					let that = this
					if (that.deviceId != '') {
						let systemInfo = uni.getSystemInfoSync()
						if (systemInfo.platform == 'android') {
							console.log("进入这里是Android")
							xBlufi.notifyStartDiscoverBle({
								'isStart': false 
							})
							console.log("进入蓝牙连接", that.deviceId)
							console.log("进入that.name", that.name)
							xBlufi.notifyConnectBle({
								isStart: true,
								deviceId: that.deviceId,
								name: that.name
							})
						} else if (systemInfo.platform == 'ios') {
							console.log("进入这里是IOS")
							that.findDevice()
						}
					}
					setTimeout(()=>{
						if(this.vardataflag != 3){
							this.vardataflag = 1
						}
					},15000)
				} 
			},
			// ios递归函数匹配
			findDevice() {
			    // 使用 find 方法查找匹配的设备
			    const matchedDevice = this.devicesarr.find(device => {
			        console.log(device.name, this.mac, '111') 
			        console.log("IOSMAC", device)
			        return device.name.slice(-12) == this.mac.slice(-12)
			    })
			    if (matchedDevice) {
			        // 找到匹配的设备
			        xBlufi.notifyStartDiscoverBle({
			            'isStart': false
			        })
			        xBlufi.notifyConnectBle({
			            isStart: true,
			            deviceId: matchedDevice.deviceId,
			            name: matchedDevice.name
			        })
			        this.deviceId = matchedDevice.deviceId
			        this.name = matchedDevice.name
			        console.log(this.deviceId, '11221')
			    } else {
			        console.log("未找到匹配的设备，继续查找...")
			        setTimeout(this.findDevice.bind(this), 1000) // 使用 bind 保持 this 上下文
			    }
			},
			
			// 雨水感应开启
			btnyushui() {
				this.handleUserAction()
				this.one = false
				this.ones = true
				if(this.vardataflag != 3){
					uni.showToast({
						title: '设备未连接',
						icon: 'none',
						duration:2000
					})
				}else{
					uni.showLoading({
						title: '开启中...'
					})
					this.yschecked = false
					xBlufi.notifySendCustomData({
						customData: '11yudi'
					})
					uni.hideLoading()
				}
			},
			// 点击同步时间
			btntb(){
				this.handleUserAction()
				if(this.vardataflag != 3){
					uni.showToast({
						title: '设备未连接',
						icon: 'none',
						duration:2000
					})
				}else{
					this.devicetime = this.getCurrentTime();
					console.log(this.devicetime);
					// if(this.pre == 'WATER'){ //单阀
						uni.showLoading({
							title: '设置中...'
						})
						xBlufi.notifySendCustomData({
							customData: '11date' + this.devicetime + ';' 
						}) 
						uni.hideLoading() 
						uni.showToast({
							title: '同步成功',
							icon: 'success',
							duration:2000
						})
					// }else{ //抽水泵
					// 	uni.showLoading({ 
					// 		title: '设置中...'
					// 	})
					// 	xBlufi.notifySendCustomData({
					// 		customData: '11hour' + this.devicetime + '@',
					// 	})
					// 	uni.hideLoading()
					// }
				} 
			},
			// 点击显示设置时间
			btnsztime(){
				this.handleUserAction()
				if(this.vardataflag != 3){
					uni.showToast({
						title: '设备未连接',
						icon: 'none',
						duration:2000
					})
				}else{
					this.timeflag = true
				}
			},
			getCurrentTime() {
			  const now = new Date();
			  const padZero = num => num.toString().padStart(2, '0');
			  const hours = padZero(now.getHours());   // 时 (00-23)
			  const minutes = padZero(now.getMinutes()); // 分 (00-59)
			  const seconds = padZero(now.getSeconds()); // 秒 (00-59)
			  return `${hours}:${minutes}:${seconds}`;
			},
			// 点击设置当前时间
			confirmtime(e){
				// if(this.pre == 'WATER'){ //单阀
					uni.showLoading({
						title: '设置中...'
					})
					console.log(e.hour,e.minute);
					this.devicetime = e.hour + ':' + e.minute
					xBlufi.notifySendCustomData({
						customData: '11date' + e.hour + ':' + e.minute + ':' + '00' + ';'
					})
					uni.hideLoading()
				// }else{ //抽水泵
				// 	uni.showLoading({
				// 		title: '设置中...'
				// 	})
				// 	console.log(e.hour,e.minute);
				// 	xBlufi.notifySendCustomData({
				// 		customData: '11hour' + e.hour + '@' + e.minute + '@',
				// 	})
				// 	uni.hideLoading()
				// }
			},
			// 雨水感应关闭
			btnyushuis() {
				this.handleUserAction()
				this.one = false
				this.ones = true
				if(this.vardataflag != 3){
					uni.showToast({
						title: '设备未连接',
						icon: 'none',
						duration:2000
					})
				}else{
					uni.showLoading({
						title: '关闭中...'
					})
					this.yschecked = true
					xBlufi.notifySendCustomData({
						customData: '11unyudi'
					})
					uni.hideLoading()
				}
			},
			// 点击儿童锁开启
			btnertong() {
				this.handleUserAction()
				this.two = false
				this.twos = true
				if(this.vardataflag != 3){
					uni.showToast({
						title: '设备未连接',
						icon: 'none',
						duration:2000
					})
				}else{
					uni.showLoading({
						title: '开启中...'
					})
					this.etchecked = false
					xBlufi.notifySendCustomData({
						customData: '11lock'
					})
					uni.hideLoading()
				}
			},
			// 点击儿童锁关闭
			btnertongs() {
				this.handleUserAction()
				this.two = false
				this.twos = true
				if(this.vardataflag != 3){
					uni.showToast({
						title: '设备未连接',
						icon: 'none',
						duration:2000
					})
			    }else{
					uni.showLoading({
						title: '关闭中...'
					})
					this.etchecked = true
					xBlufi.notifySendCustomData({
						customData: '11unlock'
					})
					uni.hideLoading()
				}
			},

			// 点击添加设备 
			btnaddsb() {
				this.$u.get(`/appVerify/profile`).then((res) => {
					if (res.code == 200) {
						this.vardataflag = 1
						this.ver_data = {}
						this.datalist = ''
						uni.navigateTo({
							url: '/page_user/lanya'
						})
					}else if(res.code == 401){
						this.jmlogin()
					}
				})
			},

			// 点击选择浇水时间
			confirm(e) {
				this.handleUserAction()
				this.minute = e.minute
				this.second = e.second
				this.jstime = Number(e.second) + Number(e.minute * 60)
			},

			// 点击跳转到定时页面
			btntime() {
				this.handleUserAction()
				if(this.vardataflag != 3){
					uni.showToast({
						title: '蓝牙未连接',
						icon: 'none',
						duration: 2000
					})
				}else{
					uni.navigateTo({
						url: '/page_user/dingshi?list=' + JSON.stringify(this.ver_data) + '&pre=' + this.pre
					})
				}
			},
			
			// 点击取消手动浇水
			btnqx() {
				this.handleUserAction()
				this.sdjsflag = false
				this.sdminutes = ''
				this.sdseconds = ''
				this.kgflag = true
				this.jsked = true
				this.jskeds = false
			},
			// 确定选择时间
			btnqd() {
				this.handleUserAction()
				if (this.minute == '--' || this.second == '--') {
					uni.showToast({
						title: '请选择浇水时长',
						icon: 'none',
						duration: 3000
					})
				} else {
					uni.showLoading({
						title: '开启中...'
					})
					xBlufi.notifySendCustomData({
						customData: "11time@" + this.jstime + '@'
					})
					uni.hideLoading()
					this.startTimer(this.jstime)
					this.sdjsflag = false
				}
			},

			// 手动浇水定时器
			startTimer(totalSeconds) {  
			    let remainingSeconds = totalSeconds
			    const sdminutes = ''
			    const sdseconds = ''
			    this.timer = setInterval(() => {  
			        // 计算分钟和秒  
			        const minutes = Math.floor(remainingSeconds / 60).toString()
			        const secs = (remainingSeconds % 60).toString()
			        // 格式化秒和分钟，确保是两位数  
			        this.sdseconds = secs.padStart(2, '0')
			        this.sdminutes = (minutes > 0 ? minutes : '').padStart(2, '0') // 如果分钟为0，则不显示分钟  
			        // 更新剩余秒数  
			        remainingSeconds--
			        // 如果剩余秒数为0，则停止定时器  
			        if (remainingSeconds <= 0) {  
			            clearInterval(this.timer)
			            this.btnkq()
			            this.sdminutes = '' 
			            this.sdseconds = '' 
			        }  
			    }, 1000)
			},
			
			// 关闭手动浇水
			btnkq() {
				this.handleUserAction()
				console.log('关闭')
				if(this.vardataflag != 3){
					uni.showToast({
						title: '设备未连接',
						icon: 'none',
						duration:2000
					})
				}else{
					uni.showLoading({
						title: '关闭中...'
					})
					xBlufi.notifySendCustomData({
						customData: "11close"
					})
					clearInterval(this.timer)
					this.sdminutes = ''
					this.sdseconds = ''
					this.kgflag = true
					this.jsked = true
					this.jskeds = false
					uni.hideLoading()
				}
			},
			// 开启手动浇水
			btngb() {
				this.handleUserAction()
				console.log('开启')
				if(this.vardataflag != 3){
					uni.showToast({
						title: '设备未连接',
						icon: 'none',
						duration:2000
					})
					this.jsked = true
					this.jskeds = false
				}else{
					this.sdjsflag = true
					this.kgflag = false
				}
			},

			// 跳转到设置
			btnsz() {
				xBlufi.listenDeviceMsgEvent(false, this.funListenDeviceMsgEvent)
				if(this.csbobj.day){
					this.xctime = '111'
				}
				uni.navigateTo({
					url: '/page_user/upload?deviceid=' + this.shebid + '&ver=' + this.ver + '&xctime=' + this.xctime + '&xipin=' + this.xinp + '&img=' + this.imgpic
				})
			},
			// 选择设备
			btnactive(deviceId,index) {
				this.shebid = deviceId
                this.btnxuanze()
			},
			// 选择确定设备  shebid
			btnxuanze() {
				this.$u.put(`/app/toggleDevice?userId=${this.userobj.userId}&deviceId=${this.shebid}`).then(res => {
					if(res.code == 200){
						wx.closeBLEConnection({
							deviceId:  this.mac,
						})
						xBlufi.notifyConnectBle({
						    isStart: false,
						    deviceId: this.deviceId,
						    name: this.name
						})
						uni.showToast({
							title: res.msg,
							icon: 'success',
							duration: 2000
						})
						this.datalist = ''
						this.mac = ''
						this.ver_data = {}
						this.name = ''
						this.deviceId = ''
						this.xuanzeflag = false
						this.vardataflag = 1
						this.sdseconds = ''
						this.sdminutes = ''
						this.kgflag = true
						this.jsked = true
						this.jskeds = false
						this.getshebxq()
					}else{
						uni.showToast({
							title: res.msg,
							icon: 'none',
							duration: 2000
						})
					}
				})
			},
			// 获取设备信息
			getshebxq(){
				this.$u.get(`/app/getDeviceInfo/${this.shebid}`).then(res => {
					if(res.code == 200){
						this.mac = res.data.mac
						this.pre = res.data.pre
						this.imgpic = res.data.modelPicture
						this.deviceId = res.data.mac.match(/.{2}/g).reverse().join(':')
						this.user = res.data
						this.getbanbens()
						// this.btnlj()
					}
				})
			},
			
			// 点击切换设备
			btnksxz() {
				if (this.xuanzeflag == true) {
					this.xuanzeflag = false
				} else {
					this.xuanzeflag = true
				}
			},
			//跳转到浇水日志页
			btnjs() {
				uni.showToast({
					title: '此功能暂未开通',
					icon: 'none',
					duration:2000
				})
				// uni.navigateTo({
				// 	url: '/page_user/jiaoshui'
				// })
			},
			// 获取附近蓝牙设备列表
			funListenDeviceMsgEvent: function(options) {
				switch (options.type) {
					case xBlufi.XBLUFI_TYPE.TYPE_STATUS_CONNECTED:
						if (!options.result) {
							this.vardataflag = 1
							this.clearDisconnectTimer()
						}
						break;
					case xBlufi.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS:
						if (options.result) {
							this.devicesarr = options.data
						}
						break;
					case xBlufi.XBLUFI_TYPE.TYPE_CONNECTED:
						console.log("连接回调：" + JSON.stringify(options))
						xBlufi.notifyInitBleEsp32({
							deviceId: this.deviceId
						})
						if (options.result == true){
							console.log('服务发现成功:', options);
							this.datalist = '1'
							setTimeout(()=>{
								this.vardataflag = 3
								this.initDisconnectTimer()
								xBlufi.notifySendCustomData({
									customData: "11get"
								})
							},3000)
						}else{
							console.log('服务发现失败:', options.data);
							this.vardataflag = 1
							this.clearDisconnectTimer() 
						}
						break
					case xBlufi.XBLUFI_TYPE.TYPE_INIT_ESP32_RESULT:
						// if (options.result == true){
						// 	console.log('服务发现成功:', options);
						// 	this.datalist = '1'
						// 	this.vardataflag = 3
						// 	this.initDisconnectTimer()
						// 	// 连接成功后立即发送一次获取数据命令
						// 	console.log("连接成功后发送获取数据命令")
						// 	xBlufi.notifySendCustomData({
						// 		customData: "11get"
						// 	})
						// }else{
						// 	console.log('服务发现失败:', options.data);
						// 	this.vardataflag = 1
						// 	this.clearDisconnectTimer() 
						// }
						break
					case xBlufi.XBLUFI_TYPE.TYPE_RECIEVE_CUSTON_DATA:
						console.log("收到设备数据：", options.data)
						if (options.data.indexOf("prom:") !== -1) {
							// console.log('固件升级中')
							var indexOld = options.data.substring(options.data.indexOf('prom:'))
							// console.log("indexOld", indexOld);
							var load_num = indexOld.substring(
								indexOld.indexOf("prom:") + 5,
								indexOld.indexOf("@")
							)
							this.progress = Number(load_num);
							// console.log("load_num", load_num);
							console.log("升级进度：", this.progress)
							if (this.progress === 6000) {
								// console.log('固件成功')
								this.progress = 100
								uni.showToast({
									title: '固件升级成功',
									icon: 'success',
									duration: 2000
								})
								setTimeout(()=>{
									this.shengjiflag = false
									uni.reLaunch({
										url:'/pages/index/index'
									})
								},2000)
							}
							if (this.progress === 9000) {
								// console.log('固件升级失败')
								this.progress = 99
								uni.showToast({
									title: '固件升级失败',
									icon: 'none',
									duration: 2000
								})
								setTimeout(()=>{
									this.shengjiflag = false
									uni.reLaunch({
										url:'/pages/index/index'
									})
								},1000)
							}
						} else {
							this.datalist = options.data.slice(0, -1) + ";"
							this.vardataflag = 3
							if(this.pre == 'WATER'){
								this.getchuli()
							}else{
								this.getcsbshuju()
							}
						}
						break
					case xBlufi.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS_START:
						if (!options.result) {
							this.vardataflag = 1
							console.log('蓝牙初始化失败')
							return
						}
						break
				}
			},
			// 每隔一时间发送一次获取数据
			getshuju() {
				const that = this
				that.intervalId = setInterval(() => {
					if (that.vardataflag == 3) {
						// console.log("发送获取数据命令")
						xBlufi.notifySendCustomData({
							customData: "11get"
						})
					}
				}, 5000) 
			},
			// 清除定时器
		     clearTimer() {
		         if (this.intervalId) {
		             clearInterval(this.intervalId);
		             this.intervalId = null; // 重置定时器 ID
		             console.log("定时器已清除");
		         }
		     },
            // 处理抽水泵接收数据
			getcsbshuju(){
				const input = this.datalist
				const inputString = this.datalist;
				const hasAtSymbol = inputString.includes('@');
				let processedString;
				let currentDay = 0;
				if (hasAtSymbol) {
				    const [ver, restOfString] = inputString.split('@');
				    this.ver = ver || '';
				    processedString = restOfString || '';
				    // 解析当前天数
				    const showMatch = processedString.match(/show:([^;]+)/);
				    if (showMatch) {
				        const showValues = showMatch[1].split(',');
				        currentDay = parseInt(showValues[showValues.length - 1]) || 0;
				    }
				} else {
				    processedString = inputString;
				    this.ver = '';
				}
				const version = this.ver;
				const parts = input.replace(";", "").split(":")
				// 获取时间部分并分割
				const timeParts = parts[1].split(",")
				// 解析为对象
				this.csbobj = {
				    hour: parseInt(timeParts[0]) < 10 ? '0' + parseInt(timeParts[0]) : parseInt(timeParts[0]), // 小时
				    minute: parseInt(timeParts[1])  < 10 ? '0' + parseInt(timeParts[1]) : parseInt(timeParts[1]), // 分钟
				    second: parseInt(timeParts[2]), // 秒
				    day: parseInt(timeParts[3]) // 天数
				}
				this.devicetime = parseInt(timeParts[4]) + ':' + parseInt(timeParts[5])
				this.ver_data = this.csbobj
                // console.log(this.csbobj);
			},
			// 处理从设备接收数据
			getchuli() {
			    const inputString = this.datalist;
			    // console.log('接收到的数据:', inputString);
			    // 检查是否有 @ 分隔符
			    const hasAtSymbol = inputString.includes('@');
			    let processedString;
			    let currentDay = 0;
			    if (hasAtSymbol) {
			        const [ver, restOfString] = inputString.split('@');
			        this.ver = ver || '';
			        processedString = restOfString || '';
			        // 解析当前天数
			        const showMatch = processedString.match(/show:([^;]+)/);
			        if (showMatch) {
			            const showValues = showMatch[1].split(',');
			            currentDay = parseInt(showValues[showValues.length - 1]) || 0;
			        }
			    } else {
			        processedString = inputString;
			        this.ver = '';
			    }
			    // console.log('处理后的字符串:', processedString);
				// console.log(this.ver,'this.verthis.verthis.ver');
			    const version = this.ver;
			    // 使用正则表达式提取数字部分
			    const versionNumber = version.match(/\d+/); // 匹配连续的数字
			    // if (versionNumber) {
			    //     const num = parseInt(versionNumber[0], 10); // 转换为整数
			    //     if (num < 9 && !this.hasShownVersionAlert) {
			    //         this.hasShownVersionAlert = true; // 设置标记为已显示
			    //         uni.showModal({
			    //             title: "提示",
			    //             content: `您当前设备版本过低，可能无法正常使用，请点击右上角设置前去升级`,
			    //             showCancel: false, // 不显示取消按钮
			    //             confirmText: "确定", // 按钮文字
			    //             success: (res) => {
			    //                 if (res.confirm) {
			    //                     console.log("用户点击了确定");
			    //                     this.hasShownVersionAlert = false; // 重置标记，允许下次判断
			    //                 }
			    //             }
			    //         })
			    //     } else {
			    //         console.log(`版本号 ${num} 不小于 9`);
			    //     }
			    // } else {
			    //     console.log("没有找到版本号数字");
			    // }
			    const pairs = processedString.split(';').filter(Boolean);
			    // console.log('分割后的数据对:', pairs);
			    const showObject = {};
			    const pSetObjects = {};
			    // 初始化所有p_set为默认值
			    for (let i = 1; i <= 6; i++) {
			        pSetObjects[`p_set${i}`] = [0, 0, 0, 0, 0];
			    }
			    // 解析字符串
			    pairs.forEach(pair => {
			        const [key, value] = pair.split(':');
			        if (key === 'show') {
			            showObject.showArray = value.split(',').map(Number);
			        } else if (key.startsWith('p_set')) {
			            const values = value.split(',').map(Number);
			            // 确保数组长度为5
			            while (values.length < 5) {
			                values.push(0);
			            }
			            pSetObjects[key] = values;
			        }
			    })
			    this.ver_data = pSetObjects;
			    this.jstimeobj = pSetObjects;
			    this.showobj = showObject;
			    // 设置开关状态
			    this.yschecked = this.showobj.showArray[1] !== 1;
			    this.etchecked = this.showobj.showArray[0] !== 1;
			    // 计算浇水时间
			    const calculateTimeDifference = (date1, date2) => {
			        const diffMs = Math.abs(date1 - date2);
			        const diffMinutes = Math.floor(diffMs / (1000 * 60));
			        const diffHours = Math.floor(diffMinutes / 60);
			        const remainingMinutes = diffMinutes % 60;
			        return { hours: diffHours, minutes: remainingMinutes };
			    };
			    const formatTime = (seconds) => {
			        const minutes = Math.floor(seconds / 60);
			        const remainingSeconds = seconds % 60;
			        return `${minutes}分${remainingSeconds}秒`;
			    };
			    const getTimeFromArray = (timeArray) => {
			        if (!timeArray || timeArray.length < 2) return null;
			        const [hour, minute] = timeArray;
			        const date = new Date();
			        date.setHours(hour, minute, 0, 0);
			        return date;
			    };
			    let nextTime = null;
			    let nextTimeDiff = null;
			    let nextWaterDuration = null;
			    let prevTime = null;
			    for (const key in this.ver_data) {
			        if (this.ver_data.hasOwnProperty(key) && this.ver_data[key][3] === 1) {
			            const timeArray = this.ver_data[key];
			            const timeDate = getTimeFromArray(timeArray);
			            if (!timeDate) continue;
			            const diff = calculateTimeDifference(timeDate, new Date());
			            const interval = timeArray[4] || 0;
			            // 检查是否应该在这一天浇水
			            const shouldWaterToday = interval === 0 || (currentDay % interval === 0);
			            if (timeDate > new Date() && shouldWaterToday) {
			                if (!nextTime || (diff.hours * 60 + diff.minutes < (nextTimeDiff?.hours || 0) * 60 + (nextTimeDiff?.minutes || 0))) {
			                    nextTimeDiff = diff;
			                    nextTime = timeDate;
			                    nextWaterDuration = formatTime(timeArray[2]);
			                }
			            } else if (!prevTime || timeDate > prevTime) {
			                prevTime = timeDate;
			            }
			        }
			    }
			    // 输出结果
			    this.xctime = nextTime ? `${nextTimeDiff.hours}时${nextTimeDiff.minutes}分` : '无距离下次浇水时间';
			    this.xctimesc = nextWaterDuration || '未知';
			    this.sctimejs = prevTime ? prevTime.toTimeString().slice(0, 5) : '无上次浇水时间';
			    this.xctimesj = nextTime ? nextTime.toTimeString().slice(0, 5) : '无下次浇水时间';
			    console.log('解析后的数据:', {
			        ver_data: this.ver_data,
			        showobj: this.showobj,
			        nextTime: this.xctimesj,
			        nextTimeDiff: this.xctime,
			        prevTime: this.sctimejs
			    });
				this.xinp = this.showobj.showArray[this.showobj.showArray.length - 1]
				// if(this.showobj.showArray[6] != '' && this.showobj.showArray[7] != ''){
					// console.log('111111111111111111111111111111111111111111111111111111111111111');
				  // 显式转为字符串
				  const yiStr = String(this.showobj.showArray[6])
				  const erStr = String(this.showobj.showArray[7])
				  // console.log('22222222222222222222222222222222222222222222222222222',yiStr,erStr);
				  // 判断字符串长度是否为1（而不是<10）
				  let yi = yiStr.length === 1 ? '0' + yiStr : yiStr
				  let er = erStr.length === 1 ? '0' + erStr : erStr
				  // console.log('33333333333333333333333333333333333333333333333333',yi,er);
				  this.devicetime = yi + ':' + er
				  // console.log(this.devicetime,'this.devicetimethis.devicetimethis.devicetimethis.devicetimethis.devicetimethis.devicetimethis.devicetimethis.devicetime');
				// }
			},
			// 初始化断开蓝牙定时器
			initDisconnectTimer() {
				this.clearDisconnectTimer()
				this.disconnectTimer = setTimeout(() => {
					if(this.vardataflag === 3) {
						this.disconnectBluetooth()
					}
				}, 600000)
			},
			// 重置断开蓝牙定时器
			resetDisconnectTimer() {
				this.initDisconnectTimer()
			},
			// 清除断开蓝牙定时器
			clearDisconnectTimer() {
				if(this.disconnectTimer) {
					clearTimeout(this.disconnectTimer)
					this.disconnectTimer = null
				}
			},
			// 断开蓝牙连接
			disconnectBluetooth() {
				if(this.deviceId) {
					wx.closeBLEConnection({
						deviceId: this.deviceId,
						success: () => {
							console.log('蓝牙连接已断开')
							this.vardataflag = 1
							this.datalist = ''
							uni.showToast({
								title: '蓝牙已断开连接',
								icon: 'none',
								duration: 2000
							})
						}
					})
					xBlufi.notifyConnectBle({
						isStart: false,
						deviceId: this.deviceId,
						name: this.name
					})
				}
			},
			// 监听用户操作的方法
			handleUserAction() {
				if(this.vardataflag === 3) {
					this.resetDisconnectTimer()
				}
			},
			// 获取时间显示
			getTimeDisplay(setKey) {
				const set = this.ver_data[setKey];
				if (set && set[0] !== undefined) {
					return `${set[0].toString().padStart(2, '0')}:${set[1].toString().padStart(2, '0')}`;
				}
				return '--:--';
			},
			// 判断是否是当前时间
			isCurrentTime(setKey) {
				const set = this.ver_data[setKey];
				return set && set[0] == this.xctimesj.slice(0,2) && set[1] == this.xctimesj.slice(-2);
			},
			// 计算时间差值（分钟）
			getTimeDifference(hour, minute) {
				if (!this.devicetime) return Infinity;
				const [currentHour, currentMinute] = this.devicetime.split(':').map(Number);
				const currentTotalMinutes = currentHour * 60 + currentMinute;
				const targetTotalMinutes = hour * 60 + minute;
				
				// 计算时间差
				let diff = targetTotalMinutes - currentTotalMinutes;
				// 如果时间已过，加上24小时
				if (diff <= 0) {
					diff += 1440;
				}
				return diff;
			},
			
			// 判断是否显示图标
			shouldShowIcon(pSetIndex) {
				const pSet = this.ver_data[`p_set${pSetIndex}`];
				// 如果定时未开启，不显示图标
				if (!pSet || pSet[3] !== 1) return false;
				
				const currentDiff = this.getTimeDifference(pSet[0], pSet[1]);
				
				// 检查是否是第一个最小时间差的定时设置
				for (let i = 1; i <= 6; i++) {
					const checkSet = this.ver_data[`p_set${i}`];
					if (checkSet && checkSet[3] === 1) {
						const checkDiff = this.getTimeDifference(checkSet[0], checkSet[1]);
						// 如果找到更小的时间差，或者相同时间差但索引更小，则不显示
						if (checkDiff < currentDiff || (checkDiff === currentDiff && i < pSetIndex)) {
							return false;
						}
					}
				}
				return true;
			},
		}
	}
</script>

<style lang="scss">
	.dangqian{
		width: 670rpx;
		height: 160rpx;
		background: #FFFFFF;
		box-shadow: 0rpx 0rpx 38rpx 0rpx rgba(128,128,128,0.3);
		filter: blur(0px);
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 0 26rpx;
		box-sizing: border-box;
		margin-top: 24rpx;
		border-radius: 20rpx;
		image{
			width: 78rpx;
			height: 78rpx;
		}
		.cen{
			margin-left: 30rpx;
			.shen{
				font-weight: 600;
				font-size: 28rpx;
				color: #3D3D3D;
				margin-bottom: 8rpx;
				display: flex;
				text{
					width: 80rpx;
					height: 40rpx;
					background-color: #7FAD76;
					color: #fff;
					text-align: center;
					line-height: 40rpx;
					border-radius: 10rpx;
					margin-left: 20rpx;
				}
			}
			view{
				font-size: 24rpx;
				color: #808080;
			}
		}
		.rt{
			font-weight: 600;
			font-size: 48rpx;
			color: #50565A;
		}
	}
	.rotated-image {
	    transform: rotate(180deg); /* 旋转 180 度 */
	    transition: transform 1s ease;
	}
	.container {
		display: flex;
		align-items: center;
		justify-content: center;
		margin-top: 22rpx;
		view {
			width: 242rpx;
			height: 208rpx;
			background: #F0F0F0;
			border-radius: 24rpx 24rpx 24rpx 24rpx;
			text-align: center;
			line-height: 208rpx;
			font-weight: 600;
			font-size: 44rpx;
			color: #3D3D3D;
		}
		text {
			font-size: 80rpx;
			margin-left: 46rpx;
			margin-right: 46rpx;
		}
	}
	.anniu {
		display: flex;
		justify-content: space-between;
		margin-top: 58rpx;
		.qx {
			width: 278rpx;
			height: 80rpx;
			border-radius: 10rpx 10rpx 10rpx 10rpx;
			border: 2rpx solid #7FAD76;
			font-size: 36rpx;
			color: #7FAD76;
			font-weight: 600;
			line-height: 80rpx;
			text-align: center;
		}
		.qd {
			width: 278rpx;
			height: 80rpx;
			background: #7FAD76;
			border-radius: 10rpx 10rpx 10rpx 10rpx;
			font-size: 36rpx;
			color: #fff;
			font-weight: 600;
			line-height: 80rpx;
			text-align: center;
		}
	}
	.selected-time {
		margin-top: 20px;
		font-size: 20px;
	}
	#activebor {
		border: 1px solid #48893B;
	}
	@keyframes fadeInDown {
		from {
			opacity: 0;
			transform: translateY(-20px);
			/* 初始位置稍微在上方 */
		}
		to {
			opacity: 1;
			transform: translateY(0);
			/* 最终位置 */
		}
	}
	.mask{
		width: 100%;
		height: 100vh;
		background: #3D3D3D;
		opacity: 0.2;
		position: fixed;
		top: 0;
		left: 0;
		z-index: 1;
	}
	.manualmask {
		width: 100%;
		height: 100vh;
		background: #3D3D3D;
		opacity: 0.2;
		position: fixed;
		top: 0;
		left: 0;
		z-index: 99;
	}
	.manualjs {
		width: 678rpx;
		max-height: 610rpx;
		background: #fff;
		border-radius: 24rpx 24rpx 24rpx 24rpx;
		position: fixed;
		top: 538rpx;
		left: 50%;
		transform: translateX(-50%);
		z-index: 100;
		padding: 42rpx 44rpx;
		box-sizing: border-box;
		.toptit {
			font-size: 36rpx;
			color: #3D3D3D;
			font-weight: 600;
			display: flex;
			justify-content: space-between;
			align-items: center;
		}
	}
	.page {
		padding: 0 40rpx;
		padding-bottom: 300rpx;
		box-sizing: border-box;
		.tabsb {
			width: 750rpx;
			max-height: 90vh;
			background: #FFFFFF;
			position: fixed;
			top: 0;
			left: 0;
			padding: 0 40rpx;
			padding-bottom: 60rpx !important;
			box-sizing: border-box;
			border-radius: 0rpx 0rpx 50rpx 50rpx;
			z-index: 2;
			padding-top: 110rpx;
			box-sizing: border-box;
			animation: fadeInDown .5s ease-out forwards;
			.qdan {
				width: 100%;
				height: 102rpx;
				font-size: 48rpx;
				color: #FFFFFF;
				font-weight: 500;
				line-height: 102rpx;
				text-align: center;
				background-color: #48893B;
				border-radius: 20rpx;
				margin-top: 40rpx;
			}
			.sblist {
				width: 100%;
				max-height: 68vh;
				overflow: scroll;
				margin-top: 50rpx;
				.sbist_val {
					display: flex;
					justify-content: space-between;
					align-items: center;
					padding: 20rpx 30rpx;
					margin-bottom: 28rpx;
					box-sizing: border-box;
					background: #F7F7F7;
					border-radius: 20rpx 20rpx 20rpx 20rpx;
					border: 1px solid transparent;
					.lt {
						font-size: 36rpx;
						color: #3D3D3D;
						font-weight: 600;
					}
					.rt {
						image {
							width: 124rpx;
							height: 124rpx;
						}
					}
				}
			}
		}
		.sbmask {
			width: 100%;
			height: 100vh;
			background-color: rgb(238, 238, 238);
			position: fixed;
			top: 400rpx;
			left: 0;
			opacity: .5;
		}
		.wusb {
			margin-top: 514rpx;
			text-align: center;
			text {
				font-size: 28rpx;
				color: #737B80;
			}
			view {
				width: 212rpx;
				height: 76rpx;
				background: #48893B;
				border-radius: 38rpx 38rpx 38rpx 38rpx;
				border-radius: 50rpx;
				font-size: 28rpx;
				color: #FFFFFF;
				text-align: center;
				line-height: 76rpx;
				margin: auto;
				margin-top: 50rpx;
			}
		}
		.wateringlogbox {
			width: 100%;
			height: 244rpx;
			background: #FFFFFF;
			box-shadow: 0rpx 0rpx 38rpx 0rpx rgba(128, 128, 128, 0.3);
			filter: blur(0px);
			border-radius: 20rpx;
			margin-top: 20rpx;
			padding: 30rpx;
			box-sizing: border-box;
			.wateringlogbd {
				display: flex;
				justify-content: space-between;
				.lt {
					view {
						font-size: 28rpx;
						color: #50565A;
						margin-top: 10rpx;
					}
				}
				.rt {
					image {
						width: 114rpx;
						height: 114rpx;
					}
				}
			}
			.wateringlogtop {
				display: flex;
				align-items: center;
				font-size: 32rpx;
				color: #3D3D3D;
				font-weight: 600;
				image {
					width: 40rpx;
					height: 40rpx;
					margin-right: 14rpx;
				}
			}
		}
		.dingshi_he {
			margin-top: 24rpx;
			width: 304rpx;
			height: 194rpx;
			background: #FFFFFF;
			box-shadow: 0rpx 0rpx 38rpx 0rpx rgba(128, 128, 128, 0.3);
			filter: blur(0px);
			border-radius: 20rpx;
			padding: 26rpx;
			box-sizing: border-box;
			.naoz {
				font-size: 40rpx;
				color: #3D3D3D;
				font-weight: 600;
				display: flex;
				justify-content: space-between;
				image {
					width: 78rpx;
					height: 78rpx;
				}
			}
			.dstime {
				margin-top: 14rpx;
				display: flex;
				align-items: center;
				width: 100%;
				justify-content: space-between;
				image {
					width: 52rpx;
					height: 52rpx;
				}
			}
		}
		.switchbox {
			margin-top: 24rpx;
			display: flex;
			justify-content: space-between;
			.switch_he {
				width: 304rpx;
				height: 194rpx;
				background: #FFFFFF;
				box-shadow: 0rpx 0rpx 38rpx 0rpx rgba(128, 128, 128, 0.3);
				filter: blur(0px);
				border-radius: 20rpx;
				padding: 26rpx;
				box-sizing: border-box;
				.yushui {
					width: 100%;
					font-size: 28rpx;
					color: #3D3D3D;
					display: flex;
					align-items: center;
					justify-content: space-between;
					margin-top: 20rpx;
				}
				image {
					width: 78rpx;
					height: 78rpx;
				}
			}
		}
		.devicebox {
			width: 100%;
			max-height: 400rpx;
			background: #FFFFFF;
			box-shadow: 0rpx 0rpx 38rpx 0rpx rgba(128, 128, 128, 0.3);
			filter: blur(0px);
			margin-top: 22rpx;
			border-radius: 20rpx;
			padding: 30rpx;
			box-sizing: border-box;
			.deviceweek {
				display: flex;
				justify-content: space-between;
				margin-top: 34rpx;
				.weeklist {
					text-align: center;
					.kg {
						font-size: 24rpx;
						color: #999999;
						font-weight: 600;
					}
					.weekday {
						font-size: 36rpx;
						color: #3D3D3D;
						font-weight: 600;
						margin-top: 4rpx;
					}
					.time {
						font-size: 28rpx;
						color: #3D3D3D;
						margin-top: 4rpx;
					}
					.interval {
						font-size: 24rpx;
						color: #3D3D3D;
						font-weight: 600;
						margin-top: 4rpx;
					}
					.img {
						text-align: center;
						image {
							width: 12rpx;
							height: 12rpx;
						}
					}
				}
			}
			.devicetop {
				display: flex;
				justify-content: space-between;
				align-items: center;
				.devicert {
					text-align: right;
					.shoudong {
						display: flex;
						image {
							width: 64rpx;
							height: 32rpx;
							margin-right: 8rpx;
						}
						font-size: 24rpx;
						color: #3D3D3D;
					}
					.shengyu {
						font-size: 24rpx;
						color: #3D3D3D;
						margin-top: 6rpx;
					}
				}
				.devicelt {
					display: flex;
					.xinghao {
						font-size: 24rpx;
						color: #3D3D3D;
						.one {
							font-size: 28rpx !important;
							color: #3D3D3D;
							font-weight: 600 !important;
							margin-top: 6rpx;
						}
					}
					image {
						width: 74rpx;
						height: 80rpx;
						margin-right: 32rpx;
					}
				}
			}
		}
		.selectbox {
			width: 100%;
			margin-top: 22rpx;
			display: flex;
			justify-content: space-between;
			align-items: center;
			.shebeiname {
				font-size: 36rpx;
				color: #333;
				font-weight: 600;
				display: flex;
				align-items: center;
				.lj{
					color: red;
					margin-left: 10rpx;
					font-weight: 400;
					font-size: 28rpx;
					border: 1px solid red;
					padding: 4rpx;
					box-sizing: border-box;
					border-radius: 10rpx;
				}
				text {
					display: inline-block;
					width: 14rpx;
					height: 14rpx;
					background: #15C55D;
					border-radius: 50%;
					box-shadow: 0rpx 0rpx 10rpx 0rpx rgba(0, 255, 102, 0.9), 0rpx 0rpx 30rpx 0rpx rgba(69, 255, 143, 0.9);
					margin-left: 22rpx;
				}
			}
			.shebeiadd {
				image {
					width: 214rpx;
					height: 64rpx;
				}
			}
			.selectname {
				font-size: 48rpx;
				color: #3D3D3D;
				font-weight: 600;
				z-index: 2;
				image {
					width: 32rpx;
					height: 26rpx;
					margin-left: 14rpx;
				}
			}
			.selectnames {
				font-size: 28rpx;
				color: #3D3D3D;
                border: 1px solid;
				padding:0 20rpx;
				box-sizing: border-box;
				border-radius: 10rpx;
				background-color: #7FAD76;
				color: #fff;
				height: 60rpx;
				line-height: 60rpx;
				image {
					width: 32rpx;
					height: 26rpx;
					margin-left: 14rpx;
				}
			}
			.selectshezhi {
				image {
					width: 60rpx;
					height: 66rpx;
				}
			}
		}
		.bjimg {
			width: 100%;
			height: 100vh;
			position: fixed;
			top: 0;
			left: 0;
			z-index: -1;
		}
		.title {
			box-sizing: border-box;
			image {
				width: 260rpx;
				height: 60rpx;
			}
		}
	}
</style>