<template>
	<view class="container">
		<uni-forms ref="form" :rules="rules" err-show-type="toast" :model="formData">
			<!-- 久坐提醒 -->
			<template v-if="title == '久坐提醒'">
				<uni-forms-item label="">
					<view class="forms-item border-line">
						<text class="label">久坐提醒</text>
						<mySwitch :activeValue="1" :inactiveValue="0" :value="formData.sedentaryOpen"
							@change="onChange($event,'sedentaryOpen')" />
					</view>
				</uni-forms-item>
				<view v-if="formData.sedentaryOpen == 1">
					<uni-forms-item label="" name="start_hour">
						<picker mode="multiSelector" :range="arrDate" :value="timeVal"
							@change="bindPickerChange($event,'timeVal')">
							<view class="forms-item border-line">
								<text class="label">时间段设置</text>
								<view class="box-itemr">
									<view v-if="formData.start_hour">{{formData.start_hour}} - {{formData.end_hour}}</view>
									<text v-else>请选择</text>
									<image class="arrow_black" src="@/static/images/pages_watch/icons/my_right_arrow_right_icon.png"
										mode="aspectFill"></image>
								</view>
							</view>
						</picker>
					</uni-forms-item>
					<uni-forms-item label="">
						<view class="forms-item border-line" @click="openPop">
							<text class="label">重复</text>
							<view class="box-itemr">
								<text>{{formData.repeatWeek.length == 0 ? '永不': repeatWeekText}}</text>
								<image class="arrow_black" src="@/static/images/pages_watch/icons/my_right_arrow_right_icon.png"
									mode="aspectFill"></image>
							</view>
						</view>
					</uni-forms-item>
				</view>
			</template>
			<!-- 心率指导 -->
			<template v-if="title == '心率指导'">
				<uni-forms-item label="">
					<view class="forms-item border-line">
						<text class="label">心率指导</text>
						<mySwitch :value="formData.hralarmOpen" @change="onChange($event,'hralarmOpen')" />
					</view>
				</uni-forms-item>
				<template v-if="formData.hralarmOpen">
					<uni-forms-item label="" name="hralarmHigh">
						<view class="forms-item border-line">
							<text class="label">不在区间内提醒</text>
							<view class="box-itemr">
								<view v-if="formData.hralarmHigh">{{formData.hralarmLow}} - {{formData.hralarmHigh}}</view>
								<text v-else>请选择</text>
								<image class="arrow_black" src="@/static/images/pages_watch/icons/my_right_arrow_right_icon.png"
									mode="aspectFill"></image>
							</view>
						</view>
					</uni-forms-item>
					<view class="hrRangetag">
						<view :class="hrActive === index ? 'hractive' : ''" v-for="(item,index) in hrRangetag" :key="index"
							@tap="handlehrRangetag(item,index)">
							{{item.name}}
						</view>
					</view>
					<picker-view v-if="visible" :indicator-style="indicatorStyle" :value="hrRangeValue"
						@change="hrRangeChange" class="picker-view">
						<picker-view-column>
							<view class="item" v-for="(item,index) in hrRange[0]" :key="index">{{item}}</view>
						</picker-view-column>
						<picker-view-column>
							<view class="item" v-for="(item,index) in hrRange[1]" :key="index">{{item}}</view>
						</picker-view-column>
					</picker-view>
				</template>
			</template>
			<!-- 血氧预警 -->
			<template v-if="title == '血氧预警'">
				<uni-forms-item label="">
					<view class="forms-item border-line">
						<text class="label">血氧预警</text>
						<mySwitch :value="formData.spo2alarmOpen" @change="onChange($event,'spo2alarmOpen')" />
					</view>
				</uni-forms-item>
				<uni-forms-item label="" name="spo2alarmLow" v-if="formData.spo2alarmOpen">
					<picker @change="bindPickerChange($event,'boRangeValue')" :value="boRangeValue" :range="boRange">
						<view class="forms-item border-line">
							<text class="label">血氧预警设置</text>
							<view class="box-itemr">
								<text>{{formData.spo2alarmLow ? formData.spo2alarmLow : '请选择'}}</text>
								<image class="arrow_black" src="@/static/images/pages_watch/icons/my_right_arrow_right_icon.png"
									mode="aspectFill"></image>
							</view>
						</view>
					</picker>
				</uni-forms-item>
			</template>
			<!-- 省电设置 -->
			<template v-if="title == '省电设置'">
				<view class="forms-item-title">勾选下方功能，点击一键省电进行优化</view>
				<label class="forms-item border-line" v-for="(item,index) in option" @tap="handleOption(item,index)">
					<view class="label">
						<view>{{item.name}}</view>
						<view class="label-tips">{{item.desc}}</view>
					</view>
					<view style="display: inline-block;">
						<view class="choose-radio" v-if="!item.checked"></view>
						<image class="choose-image" v-if="item.checked" src="@/static/images/pages_watch/icons/radio_choose_icon.png">
						</image>
					</view>
				</label>
				<view class="forms-item-title">已优化项</view>
				<label class="forms-item border-line" v-for="(item,index) in optionChoose" @click="handlePower(item,index)">
					<view class="label">
						<view>{{item.name}}</view>
						<view class="label-tips">{{item.desc}}</view>
					</view>
					<uni-icons type="checkmarkempty" size="20" :color="color"></uni-icons>
				</label>
			</template>
			<!-- 日期与时间 -->
			<template v-if="title == '日期与时间'">
				<view class="forms-item-title">时间格式</view>
				<radio-group @change="radioChange($event,'Itime')">
					<uni-forms-item label="" name="Itime">
						<label class="forms-item border-line">
							<text class="label">12小时制</text>
							<radio value="1" :checked="formData.Itime == 1" :color="color" :activeBorderColor="color"
								style="transform: scale(0.8);" />
						</label>
						<label class="forms-item">
							<text class="label">24小时制</text>
							<radio value="0" :checked="formData.Itime == 0" :color="color" :activeBorderColor="color"
								style="transform: scale(0.8);" />
						</label>
					</uni-forms-item>
				</radio-group>
				<view class="forms-item-title">日期格式</view>
				<radio-group @change="radioChange($event,'IDate')">
					<uni-forms-item label="" name="IDate">
						<label class="forms-item border-line">
							<text class="label">月-日</text>
							<radio value="0" :checked="formData.IDate == 0" :color="color" :activeBorderColor="color"
								style="transform: scale(0.8);" />
						</label>
						<label class="forms-item">
							<text class="label">日-月</text>
							<radio value="1" :checked="formData.IDate == 1" :color="color" :activeBorderColor="color"
								style="transform: scale(0.8);" />
						</label>
					</uni-forms-item>
				</radio-group>
			</template>
			<!-- 翻腕亮屏 -->
			<template v-if="title == '翻腕亮屏'">
				<uni-forms-item label="">
					<view class="forms-item border-line">
						<text class="label">翻腕亮屏</text>
						<mySwitch :value="formData.lcdgestureOpen" @change="onChange($event,'lcdgestureOpen')" />
					</view>
				</uni-forms-item>
				<uni-forms-item label="" name="lcdgestureStart" v-if="formData.lcdgestureOpen">
					<picker mode="multiSelector" :range="arrDate" :value="palmingVal"
						@change="bindPickerChange($event,'palmingVal')">
						<view class="forms-item border-line">
							<text class="label">时间段设置</text>
							<view class="box-itemr">
								<text v-if="formData.lcdgestureStart">{{formData.lcdgestureStart}} - {{formData.lcdgestureEnd}}</text>
								<text v-else>请选择</text>
								<image class="arrow_black" src="@/static/images/pages_watch/icons/my_right_arrow_right_icon.png"
									mode="aspectFill"></image>
							</view>
						</view>
					</picker>
				</uni-forms-item>
			</template>
			<!-- 单位设置 -->
			<template v-if="title == '单位设置'">
				<view class="forms-item-title">度量单位</view>
				<radio-group @change="radioChange($event,'measure')">
					<uni-forms-item label="">
						<label class="forms-item border-line">
							<text class="label">英制</text>
							<radio value="1" :checked="formData.measure == 1" :color="color" :activeBorderColor="color"
								style="transform: scale(0.8);" />
						</label>
						<label class="forms-item">
							<text class="label">公制</text>
							<radio value="0" :checked="formData.measure == 0" :color="color" :activeBorderColor="color"
								style="transform: scale(0.8);" />
						</label>
					</uni-forms-item>
				</radio-group>
				<view class="forms-item-title">温度单位</view>
				<radio-group @change="radioChange($event,'temperature')">
					<uni-forms-item label="">
						<label class="forms-item border-line">
							<text class="label">摄氏度</text>
							<radio value="0" :checked="formData.temperature == 0" :color="color" :activeBorderColor="color"
								style="transform: scale(0.8);" />
						</label>
						<label class="forms-item">
							<text class="label">华氏度</text>
							<radio value="1" :checked="formData.temperature == 1" :color="color" :activeBorderColor="color"
								style="transform: scale(0.8);" />
						</label>
					</uni-forms-item>
				</radio-group>
			</template>
			<!-- 手表模式 -->
			<template v-if="title == '手表模式'">
				<uni-forms-item label="">
					<view class="forms-item border-line">
						<text class="label">自动定位</text>
						<mySwitch :value="formData.isLocation" @change="onChange($event,'isLocation')" />
					</view>
				</uni-forms-item>
				<uni-forms-item label="" name="interval" v-if="formData.isLocation || formData.isPower">
					<picker mode="multiSelector" :range="intervalData" :value="interval"
						@change="bindPickerChange($event,'interval')">
						<view class="forms-item border-line">
							<text class="label">定位&传输间隔</text>
							<view class="box-itemr">
								<text>{{intervalData[0][interval[0]]}}小时{{intervalData[1][interval[1]]}}分钟</text>
								<image class="arrow_black" src="@/static/images/pages_watch/icons/my_right_arrow_right_icon.png"
									mode="aspectFill"></image>
							</view>
						</view>
					</picker>
				</uni-forms-item>
				<uni-forms-item label="">
					<view class="forms-item border-line">
						<view>
							<text class="label">放置省电</text>
							<view class="label-tips" style="margin-right: 40rpx;">该功能打开后，手表未佩戴进入放置后，手表无法接听和上传数据</view>
						</view>
						<mySwitch :value="formData.isPower" @change="onChange($event,'isPower')" />
					</view>
				</uni-forms-item>
			</template>
			<!-- 添加闹钟 -->
			<template v-if="title == '添加闹钟'">
				<uni-forms-item label="" name="title">
					<view class="forms-item border-line">
						<uni-easyinput type="text" v-model="formData.title" placeholder="标题" :placeholderStyle="placeholderStyle" :inputBorder="false" :clearable="false" />
					</view>
				</uni-forms-item>
				<uni-forms-item label="">
					<picker mode="multiSelector" :range="clockalarmRange" :value="clockalarmVal"
						@change="bindPickerChange($event,'clockalarmVal')">
						<view class="forms-item border-line">
							<text class="label">开始</text>
							<view class="box-itemr">
								<view>{{formData.hour}}:{{formData.minute}}</view>
								<image class="arrow_black" src="@/static/images/pages_watch/icons/my_right_arrow_right_icon.png"
									mode="aspectFill"></image>
							</view>
						</view>
					</picker>
				</uni-forms-item>
				<uni-forms-item label="">
					<view class="forms-item border-line" @click="openPop">
						<text class="label">重复</text>
						<view class="box-itemr">
							<text>{{formData.repeatWeek.length == 0 ? '不重复': repeatWeekText}}</text>
							<image class="arrow_black" src="@/static/images/pages_watch/icons/my_right_arrow_right_icon.png"
								mode="aspectFill"></image>
						</view>
					</view>
				</uni-forms-item>
			</template>
		</uni-forms>
		<!-- 久坐提醒 重复 -->
		<uni-popup ref="popup" type="bottom">
			<view class="popbox">
				<view class="popbox-head">
					<text style="color: #888;" @tap="closePop()">取消</text>
					<text style="color:#007aff;" @tap="comfirmPop()">完成</text>
				</view>
				<view class="popbox-body">
					<view class="weektype item-flex border-line" @click="handleWeek(1)">
						<text>每天</text>
						<uni-icons type="checkmarkempty" size="20" :color="color" v-show="weekType == 1"></uni-icons>
					</view>
					<view class="weektype item-flex border-line" @click="handleWeek(2)">
						<text>工作日</text>
						<uni-icons type="checkmarkempty" size="20" :color="color" v-show="weekType == 2"></uni-icons>
					</view>
					<view class="weektype item-flex" @click="handleWeek(3)">
						<text>周末</text>
						<uni-icons type="checkmarkempty" size="20" :color="color" v-show="weekType == 3"></uni-icons>
					</view>
					<view class="weektype-item item-flex border-line" v-for="(item,index) in repeatWeek" :key="index"
						@click="handleWeekItem(item)">
						<text>{{item.label}}</text>
						<uni-icons type="checkmarkempty" size="20" :color="color" v-show="item.checked"></uni-icons>
					</view>
				</view>
			</view>
		</uni-popup>
		<view class="footer">
			<button class="savebtn" :loading="btnLoading" :disabled="btnLoading" @click="submit">
				{{title=='省电设置'?'一键省电':'保 存'}}
			</button>
		</view>
	</view>
</template>

<script>
	import mySwitch from "/pages_watch/components/mySwitch/mySwitch.vue";
	import {
		getSetUpInfoByDeviceId,
		setSedentary,
		hralarm,
		spo2alarm,
		power,
		lcdgesture,
		setDeviceTime,
		setDeviceUnit,
		setDeviceMode,
		setClockalarm
	} from "@/api/pages_watch/index.js";

	export default {
		components: {
			mySwitch
		},
		data() {
			return {
				deviceId: "",
				color: "#FF7700",
				placeholderStyle: "{font-family: PingFang SC, PingFang SC;font-weight: 400;font-size: 32rpx;color: #CCCCCC;}",
				title: "",
				arrDate: [
					['00:00', '01:00', '02:00', '03:00', '04:00', '05:00', '06:00', '07:00', '08:00', '09:00', '10:00',
						'11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00',
						'21:00', '22:00', '23:00'
					],
					['01:00', '02:00', '03:00', '04:00', '05:00', '06:00', '07:00', '08:00', '09:00', '10:00', '11:00',
						'12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00', '21:00',
						'22:00', '23:00', '24:00'
					],
				],
				timeVal: [0, 0],
				palmingVal: [0, 1],
				repeatWeek: [{
					label: "周一",
					value: "monday",
					checked: false
				}, {
					label: "周二",
					value: "tuesday",
					checked: false
				}, {
					label: "周三",
					value: "wednesday",
					checked: false
				}, {
					label: "周四",
					value: "thursday",
					checked: false
				}, {
					label: "周五",
					value: "friday",
					checked: false
				}, {
					label: "周六",
					value: "saturday",
					checked: false
				}, {
					label: "周日",
					value: "sunday",
					checked: false
				}],
				// weekType: 0,
				repeatWeekText: "",
				visible: true,
				indicatorStyle: `height: 100rpx;`,
				hrRangeValue: [20, 50],
				hrActive: undefined,
				hrRangetag: [{
					name: '热身运动',
					value: [57, 66]
				}, {
					name: '脂肪燃烧',
					value: [77, 86]
				}, {
					name: '有氧运动',
					value: [97, 105]
				}, {
					name: '无氧运动',
					value: [116, 125]
				}],
				boRange: ["80%", "81%", "82%", "83%", "84%", "85%", "86%", "87%", "88%", "89%", "90%", "91%", "92%",
					"93%"],
				boRangeValue: 10,
				defaultOption: [{
					name: "关闭翻腕亮屏",
					type: "isLcdgesture",
					desc: "该功能关闭后，则无法通过翻腕自动点亮屏幕",
					opendesc: "翻腕亮屏:开启翻腕亮屏后会增加功耗，是否继续?",
					checked: false,
				}, {
					name: "关闭24小时心脏健康",
					type: "isHeartHealth",
					desc: "该功能关闭后,则无法查看心脏健康散点图和REM睡眠",
					opendesc: "24小时心脏健康:开启24小时心脏健康后，会增加功耗，是否继续?",
					checked: false,
				}, {
					name: "关闭自动定位",
					type: "isLocation",
					desc: "该功能关闭后,手表不再定时自动定位",
					opendesc: "自动定位:开启自动定位后会增加功耗，是否继续?",
					checked: false,
				}, {
					name: "关闭放置省电",
					type: "isPower",
					desc: "关闭放置省电后，会增加功耗，是否继续?",
					opendesc: "关闭放置省电后，会增加功耗，是否继续?",
					checked: false,
				}],
				option: [],
				optionChoose: [],
				intervalData: [
					['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17',
						'18', '19', '20', '21', '22', '23'
					],
					["00", "30"]
				],
				interval: [0, 0],
				clockalarmVal: [0,0],
				clockalarmInfo: [], // 原有闹钟信息
				formData: {
					sedentaryOpen: 0,
					start_hour: "",
					end_hour: "",
					repeatWeek: [],
					duration: 5,
					threshold: 40,
					hralarmOpen: false,
					hralarmHigh: null,
					hralarmLow: null,
					timeout: 3,
					alarm_interval: 10,
					spo2alarmOpen: false,
					spo2alarmLow: null,
					lcdgestureOpen: false,
					lcdgestureStart: null,
					lcdgestureEnd: null,
					Itime: '0',
					IDate: '0',
					measure: '0', // 度量单位0公制，1英制
					temperature: '0', // 度量单位0公制，1英制
					isLocation: false,
					interval: null,
					isPower: false,
					title: "",
					hour: "",
					minute: ""
				},
				rules: {
					start_hour: {
						rules: [{
							required: true,
							errorMessage: '请选择时间段设置'
						}]
					},
					hralarmHigh: {
						rules: [{
							required: true,
							errorMessage: '请选择区间'
						}]
					},
					spo2alarmLow: {
						rules: [{
							required: true,
							errorMessage: '请选择血氧预警值'
						}]
					},
					lcdgestureStart: {
						rules: [{
							required: true,
							errorMessage: '请选择时间段设置'
						}]
					},
					Itime: {
						rules: [{
							required: true,
							errorMessage: '请选择时间格式'
						}]
					},
					IDate: {
						rules: [{
							required: true,
							errorMessage: '请选择日期格式'
						}]
					},
					measure: {
						rules: [{
							required: true,
							errorMessage: '请选择度量单位'
						}]
					},
					temperature: {
						rules: [{
							required: true,
							errorMessage: '请选择温度单位'
						}]
					},
					interval: {
						rules: [{
							required: true,
							errorMessage: '请选择定位&传输间隔'
						}]
					},
					title: {
						rules: [{
							required: true,
							errorMessage: '请输入标题'
						}]
					},
				},
				btnLoading: false,
				isEdit: false,
				index: 0, //修改的闹钟index
			}
		},
		computed: {
			weekType() {
				const repeatWeekChoose = this.repeatWeek.filter(item => item.checked == true).map(it => it.label)
				// 判断是否为工作日
				const isWorkDay = repeatWeekChoose.length == 5 && ["周一", "周二", "周三", "周四", "周五"].every(day =>
					repeatWeekChoose.includes(day));
				// 判断是否为周末
				const isWeekend = repeatWeekChoose.length == 2 && ["周六", "周日"].every(day => repeatWeekChoose.includes(
				day));
				// 判断是否为每天
				const isEveryday = repeatWeekChoose.length == 7 && !isWorkDay && !isWeekend;

				return isEveryday ? 1 : isWorkDay ? 2 : isWeekend ? 3 : 0
			},
			hrRange() {
				let one = Array.from({
					length: 151
				}, (_, i) => i + 40)
				let two = Array.from({
					length: 151
				}, (_, i) => i + 50)
				return [one, two]
			},
			clockalarmRange() {
				let hours = [];
				for (let i = 0; i <= 23; i++) {
				  hours.push(i.toString());
				}
				
				let minutes = [];
				for (let i = 0; i <= 59; i++) {
				  minutes.push(i.toString().padStart(2, '0'));
				}
				
				return [hours, minutes]
			},
		},
		onLoad(option) {
			this.isEdit = option.isEdit || false
			this.index = option.index || false
			this.title = option.title || ''
			uni.setNavigationBarTitle({
				title: this.isEdit && this.title == '添加闹钟' ? '修改闹钟' : this.title,
			});
			this.option = this.defaultOption
			
			const nowH = this.$timeFormat(new Date(),'h')
			const nowM = this.$timeFormat(new Date(),'MM')
			this.clockalarmVal = [this.clockalarmRange[0].indexOf(nowH),this.clockalarmRange[1].indexOf(nowM)]
			this.formData.hour = nowH
			this.formData.minute = nowM
		},
		onReady() {
			// 需要在onReady中设置规则
			this.$refs.form.setRules(this.rules)
		},
		onShow() {
			this.deviceId = uni.getStorageSync("deviceId") || ""
			if (this.$isLogin()) {
				if (this.deviceId) {
					this.getSetUpInfo()
				} else {
					console.log("set.vue ---- deviceId is undefined")
					// uni.showToast({
					// 	title: "deviceId不存在",
					// 	icon: "none"
					// })
				}
			} else {
				this.$showLoginPage()
			}
		},
		methods: {
			handlePower(item){
				uni.showModal({
					title: '取消省电设置',
					content: item.opendesc,
					success: (res)=> {
						if (res.confirm) {
							let param = {
								deviceId: this.deviceId,
								isLcdgesture: null,
								isLocation: null,
								isPower: null,
								isHeartHealth: null
							}
							param[item.type] =  true
							power(param).then(res => {
								if(res.code == 200) {
									this.$navBack()
								} else {
									uni.showToast({
										title: res.msg,
										icon: "none"
									})
								}
							})
						}
					}
				});
			},
			
			getSetUpInfo() {
				getSetUpInfoByDeviceId({
					deviceId: this.deviceId
				}).then(res => {
					if (res.code == 200 && res.data) {
						this.clockalarmInfo = res.data.alarmClock.alarmClockObjectVos || []
						this.resetInfo(res.data)
					} else {
						uni.showToast({
							title: res.msg,
							icon: "none"
						})
					}
				})
			},
			resetInfo(resData) {
				if(this.title == "久坐提醒") {
					this.formData.sedentaryOpen = resData.sedentary.open
					this.formData.start_hour = resData.sedentary.sedentaries && resData.sedentary.sedentaries.length > 0 ? this.$formatHour(resData.sedentary.sedentaries[0].start_hour) : ''
					this.formData.end_hour = resData.sedentary.sedentaries && resData.sedentary.sedentaries.length > 0 ? this.$formatHour(resData.sedentary.sedentaries[0].end_hour) : ''
					this.formData.duration = resData.sedentary.sedentaries && resData.sedentary.sedentaries.length > 0 ?resData.sedentary.sedentaries.duration : 5
					this.formData.threshold = resData.sedentary.sedentaries && resData.sedentary.sedentaries.length > 0 ?resData.sedentary.sedentaries.threshold : 40
					this.formData.repeatWeek = []
					if(resData.sedentary.sedentaries && resData.sedentary.sedentaries.length > 0 && !resData.sedentary.sedentaries.repeat) {
						const weekDays = {
						  monday: '周一',
						  tuesday: '周二',
						  wednesday: '周三',
						  thursday: '周四',
						  friday: '周五',
						  saturday: '周六',
						  sunday: '周日'
						};
						
						Object.keys(weekDays).forEach((day) => {
						  if (resData.sedentary.sedentaries[0][day]) {
						    this.formData.repeatWeek.push(weekDays[day]);
						  }
						});
					}
					this.repeatWeek = this.repeatWeek.map(item => ({
						...item,
						checked: this.formData.repeatWeek.includes(item.label)
					}))
					this.comfirmPop()
					this.timeVal = [this.arrDate[0].indexOf(this.formData.start_hour),this.arrDate[1].indexOf(this.formData.end_hour)]
					return
				}
				if(this.title == "心率指导") {
					this.formData.hralarmOpen = resData.hralarm.open
					this.formData.hralarmHigh = resData.hralarm.high 
					this.formData.hralarmLow = resData.hralarm.low 
					this.formData.timeout = resData.hralarm.threshold || 3
					this.formData.alarm_interval = resData.hralarm.alarm_interval || 10
					this.hrRangeValue = [this.hrRange[0].indexOf(this.formData.hralarmLow),this.hrRange[1].indexOf(this.formData.hralarmHigh)]
					return
				}
				if(this.title == "血氧预警") {
					this.formData.spo2alarmOpen = resData.spo2alarm.open
					this.formData.spo2alarmLow = resData.spo2alarm.low + '%'
					this.boRangeValue = [this.boRange.indexOf(this.formData.spo2alarmLow)]
					return
				}
				if(this.title == "省电设置") {
					let option = []
					let optionChoose = []
					Object.keys(resData.power).forEach(key=> {
					  const obj = this.defaultOption.find(item => item.type === key);
					  const checked = resData.power[key] ? false : true;
					  const newItem = { ...obj, checked };
					  
					  if (checked) {
					    optionChoose.push(newItem);
					  } else {
					    option.push(newItem);
					  }
					});
					this.option = option
					this.optionChoose = optionChoose
					return
				}
				if(this.title == "日期与时间") {
					this.formData.Itime = resData.time.itime + ''
					this.formData.IDate = resData.time.idate + ''
					return 
				}
				if(this.title == "翻腕亮屏") {
					this.formData.lcdgestureOpen = resData.lcdgesture.open
					this.formData.lcdgestureStart = this.$formatHour(resData.lcdgesture.start_hour)
					this.formData.lcdgestureEnd = this.$formatHour(resData.lcdgesture.end_hour)
					this.palmingVal = [this.arrDate[0].indexOf(this.formData.lcdgestureStart),this.arrDate[1].indexOf(this.formData.lcdgestureEnd)]
					return 
				}
				if(this.title == "单位设置") {
					this.formData.measure = resData.unit.measure + ''
					this.formData.temperature = resData.unit.temperature + ''
					return 
				}
				if(this.title == "手表模式") {
					let hours = Math.floor(resData.mode.interval / 60) + '';
					let remainingMinutes = resData.mode.interval % 60;
						remainingMinutes = remainingMinutes || '00'
					this.interval = [this.intervalData[0].indexOf(hours),this.intervalData[1].indexOf(remainingMinutes+ '')]
					this.formData.isLocation = resData.mode.isLocation
					this.formData.interval = resData.mode.interval
					this.formData.isPower = resData.mode.isPower
					return 
				}
				if(this.title == "添加闹钟"&&this.isEdit) {
					this.formData.title = this.clockalarmInfo[this.index].title
					this.formData.hour = this.clockalarmInfo[this.index].hour
					this.formData.minute = this.clockalarmInfo[this.index].minute
					this.clockalarmVal = [this.clockalarmRange[0].indexOf(this.formData.hour),this.clockalarmRange[1].indexOf(this.formData.minute)]
					const weekDays = {
					  monday: '周一',
					  tuesday: '周二',
					  wednesday: '周三',
					  thursday: '周四',
					  friday: '周五',
					  saturday: '周六',
					  sunday: '周日'
					};
					
					Object.keys(weekDays).forEach((day) => {
					  if (this.clockalarmInfo[this.index][day]) {
					    this.formData.repeatWeek.push(weekDays[day]);
					  }
					});
					this.repeatWeek = this.repeatWeek.map(item => ({
						...item,
						checked: this.formData.repeatWeek.includes(item.label)
					}))
					this.comfirmPop()
					return
				}
			},
			onChange(e, type) {
				this.formData[type] = e
				if(type == "hralarmOpen") {
					this.formData.hralarmLow = this.hrRange[0][this.hrRangeValue[0]]
					this.formData.hralarmHigh = this.hrRange[1][this.hrRangeValue[1]]
				} else if(type == "spo2alarmOpen") {
					this.formData.spo2alarmLow = this.boRange[this.boRangeValue]
				}
			},
			openPop() {
				this.repeatWeek = this.repeatWeek.map(item => ({
					...item,
					checked: this.formData.repeatWeek.includes(item.label)
				}))
				this.$refs.popup.open()
			},
			closePop() {
				this.$refs.popup.close()
			},
			comfirmPop() {
				const repeatWeekChoose = this.repeatWeek.filter(item => item.checked == true).map(it => it.label)
				this.formData.repeatWeek = repeatWeekChoose
				this.repeatWeekText = this.weekType == 1 ? '每天' : this.weekType == 2 ? '工作日' : this.weekType == 3 ? '周末' :
					repeatWeekChoose.join(',')
				this.$refs.popup.close()
			},
			handleWeek(type) {
				if (type == 1) {
					// 每天
					this.repeatWeek = this.repeatWeek.map(item => ({
						...item,
						checked: true
					}))
				} else if (type == 2) {
					// 工作日
					this.repeatWeek = this.repeatWeek.map(item => ({
						...item,
						checked: item.label != "周六" && item.label != "周日"
					}))
				} else if (type == 3) {
					// 周末
					this.repeatWeek = this.repeatWeek.map(item => ({
						...item,
						checked: item.label == "周六" || item.label == "周日"
					}))
				}
			},
			handleWeekItem(item) {
				item.checked = !item.checked
			},
			// 心率
			hrRangeChange(e) {
				this.hrRangeValue = e.detail.value
				this.hrActive = this.hrRangetag.findIndex(el => el.value[0] === this.hrRangeValue[0] && el.value[1] ===
					this.hrRangeValue[1]);
				if (this.hrActive === -1) {
					this.hrActive = undefined;
				}
				this.formData.hralarmLow = this.hrRange[0][this.hrRangeValue[0]]
				this.formData.hralarmHigh = this.hrRange[1][this.hrRangeValue[1]]
			},
			handlehrRangetag(item, index) {
				this.hrActive = index
				this.hrRangeValue = item.value
				this.formData.hralarmLow = this.hrRange[0][this.hrRangeValue[0]]
				this.formData.hralarmHigh = this.hrRange[1][this.hrRangeValue[1]]
			},
			// 省电设置
			handleOption(item, index) {
				item.checked = !item.checked
			},
			bindPickerChange(e, type) {
				this[type] = e.detail.value
				if (type == "timeVal") {
					// 久坐时间
					// this.timeVal = e.detail.value
					this.formData.start_hour = this.arrDate[0][e.detail.value[0]]
					this.formData.end_hour = this.arrDate[1][e.detail.value[1]]
				} else if (type == "boRangeValue") {
					// 血氧
					// this.boRangeValue = e.detail.value
					this.formData.spo2alarmLow = this.boRange[this.boRangeValue]
				} else if (type == "palmingVal") {
					// 翻腕亮屏
					// this.palmingVal = e.detail.value
					this.formData.lcdgestureStart = this.arrDate[0][e.detail.value[0]]
					this.formData.lcdgestureEnd = this.arrDate[1][e.detail.value[1]]
				} else if (type == "interval") {
					// 手表模式
					// this.interval = e.detail.value
					const minute = this.intervalData[0][e.detail.value[0]] * 60 + Number(this.intervalData[1][e.detail.value[1]])
					this.formData.interval = minute
				} else if (type == "clockalarmVal") {
					// 添加闹钟
					// this.clockalarmVal = e.detail.value
					this.formData.hour = this.clockalarmRange[0][e.detail.value[0]]
					this.formData.minute = this.clockalarmRange[1][e.detail.value[1]]
				}
			},
			radioChange(e,type) {
				this.formData[type] = e.detail.value
			},
			submit() {
				this.$refs.form.validate().then(res => {
					if (this.title == "久坐提醒") {
						if (this.formData.sedentaryOpen == 1) {
							if (this.timeVal[0] > this.timeVal[1]) {
								uni.showToast({
									title: '时间无效',
									icon: 'none'
								})
								return
							}
						}
					} else if (this.title == "心率指导") {
						if (this.formData.hralarmOpen) {
							if (this.hrRangeValue[0] >= this.hrRangeValue[1]+10) {
								uni.showToast({
									title: '区间无效',
									icon: 'none'
								})
								return
							}
						}
					} else if (this.title == "翻腕亮屏") {
						if (this.formData.lcdgestureOpen) {
							if (this.palmingVal[0] > this.palmingVal[1]) {
								uni.showToast({
									title: '区间无效',
									icon: 'none'
								})
								return
							}
						}
					} else if (this.title == "手表模式") {
						if (this.formData.isLocation || this.formData.isPower) {
							if (this.formData.interval == 0) {
								uni.showToast({
									title: '时间间隔不能设置为0',
									icon: 'none'
								})
								return
							}
						}
					} else if (this.title == "添加闹钟"&&!this.isEdit) {
						const obj = {
							repeat: this.formData.repeatWeek.length == 0 ? false : true,
							monday: this.formData.repeatWeek.includes('周一'),
							tuesday: this.formData.repeatWeek.includes('周二'),
							wednesday: this.formData.repeatWeek.includes('周三'),
							thursday: this.formData.repeatWeek.includes('周四'),
							friday: this.formData.repeatWeek.includes('周五'),
							saturday: this.formData.repeatWeek.includes('周六'),
							sunday: this.formData.repeatWeek.includes('周日'),
							hour: Number(this.formData.hour),
							minute: Number(this.formData.minute),
							title: this.formData.title,
							status: true,
						}
						this.clockalarmInfo.push(obj)
					} else if (this.title == "添加闹钟"&&this.isEdit) {
						this.clockalarmInfo[this.index] = {
							repeat: this.formData.repeatWeek.length == 0 ? false : true,
							monday: this.formData.repeatWeek.includes('周一'),
							tuesday: this.formData.repeatWeek.includes('周二'),
							wednesday: this.formData.repeatWeek.includes('周三'),
							thursday: this.formData.repeatWeek.includes('周四'),
							friday: this.formData.repeatWeek.includes('周五'),
							saturday: this.formData.repeatWeek.includes('周六'),
							sunday: this.formData.repeatWeek.includes('周日'),
							hour: Number(this.formData.hour),
							minute: Number(this.formData.minute),
							title: this.formData.title,
							status: true,
						}
					}
					this.handleFun()
				}).catch(err => {
					console.log('表单错误信息：', err);
				})
			},
			handleFun() {
				const options = {
					// 久坐提醒
					"久坐提醒": () => setSedentary({
						deviceid: this.deviceId,
						sedentaries: [{
							repeat: this.formData.repeatWeek.length == 0 ? true : false,
							monday: this.formData.repeatWeek.includes('周一'),
							tuesday: this.formData.repeatWeek.includes('周二'),
							wednesday: this.formData.repeatWeek.includes('周三'),
							thursday: this.formData.repeatWeek.includes('周四'),
							friday: this.formData.repeatWeek.includes('周五'),
							saturday: this.formData.repeatWeek.includes('周六'),
							sunday: this.formData.repeatWeek.includes('周日'),
							start_hour: this.formData.start_hour ? this.$formatHour(this.formData.start_hour,1) : '',
							end_hour: this.formData.end_hour ? this.$formatHour(this.formData.end_hour,1) : '',
							duration: 5,
							threshold: 40
						}]
					}),
					// 心率指导
					"心率指导": () => hralarm({
						deviceid: this.deviceId,
						open: this.formData.hralarmOpen,
						high: this.formData.hralarmHigh,
						low: this.formData.hralarmLow,
						timeout:3,
						interval:10
					}),
					// 血氧预警
					"血氧预警": () => spo2alarm({
						deviceid: this.deviceId,
						open: this.formData.spo2alarmOpen,
						low: this.formData.spo2alarmLow ? Number(this.formData.spo2alarmLow.replace('%','')) : '',
					}),
					// 省电设置
					"省电设置": () => power({
						deviceId: this.deviceId,
						isLcdgesture: this.optionChoose.some(item=>item.name!="关闭翻腕亮屏") ? false : this.option.some(item=>item.name=="关闭自动定位" && item.checked) ? false : true,
						isLocation: this.optionChoose.some(item=>item.name=="关闭自动定位") ? false : this.option.some(item=>item.name=="关闭自动定位" && item.checked) ? false : true,
						isPower: this.optionChoose.some(item=>item.name=="关闭放置省电") ? false : this.option.some(item=>item.name=="关闭放置省电" && item.checked) ? false : true,
						isHeartHealth: this.optionChoose.some(item=>item.name=="关闭24小时心脏健康") ? false : this.option.some(item=>item.name=="关闭24小时心脏健康" && item.checked) ? false : true
					}),
					"翻腕亮屏": () => lcdgesture({
						deviceId: this.deviceId,
						flag: this.formData.lcdgestureOpen,
						start: this.formData.lcdgestureStart ? this.$formatHour(this.formData.lcdgestureStart,1) : '',
						end: this.formData.lcdgestureEnd ? this.$formatHour(this.formData.lcdgestureEnd,1) : '',
					}),
					"日期与时间": () => setDeviceTime({
						deviceId: this.deviceId,
						Itime: Number(this.formData.Itime || 0),
						IDate: Number(this.formData.IDate || 0),
					}),
					"单位设置": () => setDeviceUnit({
						deviceId: this.deviceId,
						measure: Number(this.formData.measure || 0),
						temperature: Number(this.formData.temperature || 0),
					}),
					"手表模式": () => setDeviceMode({
						deviceId: this.deviceId,
						isLocation: this.formData.isLocation,
						interval: this.formData.interval,
						isPower: this.formData.isPower,
					}),
					"添加闹钟": () => setClockalarm({
						deviceId: this.deviceId,
						alarmclock: this.clockalarmInfo,
					}),
				}
				const option = options[this.title];
				if (option) {
					this.btnLoading = true
					option().then(res => {
						this.btnLoading = false
						if(res.code == 200) {
							this.$navBack()
						} else {
							uni.showToast({
								title: res.msg,
								icon: "none"
							})
						}
					}).catch(()=>{
						this.btnLoading = false
					})
				}
			}
		}
	}
</script>

<style scoped lang="scss">
	@mixin u-flex($flexD, $alignI, $justifyC) {
		display: flex;
		flex-direction: $flexD;
		align-items: $alignI;
		justify-content: $justifyC;
	}

	::v-deep {
		.uni-forms-item {
			margin-bottom: 0;
		}
		.uni-easyinput__content-input {
			    padding-right: 0 !important;
			    padding-left: 0 !important;
		}
	}

	.container {
		padding-bottom: 50rpx;
	}

	.picker-view {
		width: 100%;
		height: 300rpx;
		margin-top: 20rpx;
	}

	.item {
		// #ifndef MP-WEIXIN
		line-height: 100rpx;
		// #endif
		text-align: center;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.hrRangetag {
		width: 100%;
		padding: 30rpx;
		box-sizing: border-box;
		@include u-flex(row, center, flex-start);
		// gap: 30rpx;
		margin: 0 -30rpx -30rpx 0;
		flex-wrap: wrap;

		view {
			width: 200rpx;
			height: 60rpx;
			margin: 0 30rpx 30rpx 0;
			box-sizing: border-box;
			border-radius: 60rpx;
			line-height: 57rpx;
			text-align: center;
			background-color: #fff;
			font-size: 28rpx;
			color: #FF7700;
			border: 1rpx solid #FF7700;
		}

		.hractive {
			border: none !important;
			color: #fff !important;
			background-color: #FF7700 !important;
		}
	}

	.popbox {
		background-color: #f7f7f7;
		padding: 0;

		&-head {
			height: 90rpx;
			font-size: 34rpx;
			line-height: 90rpx;
			@include u-flex(row, center, space-between);
			background-color: #fff;

			text {
				box-sizing: border-box;
				padding: 0 28rpx;
			}
		}

		&-body {
			height: 50vh;
			overflow-y: auto;
		}

		.weektype {
			height: 90rpx;
			line-height: 90rpx;
			background-color: #fff;
			padding: 0 24rpx;
		}

		.weektype-item {
			height: 90rpx;
			line-height: 90rpx;
			padding: 0 24rpx;
		}

		.item-flex {
			@include u-flex(row, center, space-between);
		}
	}

	.forms-item-title {
		font-family: PingFang SC, PingFang SC;
		font-weight: 400;
		font-size: 30rpx;
		color: #333333;
		line-height: 80rpx;
		padding: 0 24rpx;
	}

	.forms-item {
		min-height: 108rpx;
		background-color: #fff;
		padding: 24rpx;
		box-sizing: border-box;
		@include u-flex(row, center, space-between);

		.label {
			font-family: PingFang SC, PingFang SC;
			font-weight: 400;
			font-size: 32rpx;
			color: #333333;
		}

		.label-tips {
			margin-top: 10rpx;
			font-size: 24rpx;
			color: #999;
		}

		.choose-radio {
			width: 32rpx;
			height: 32rpx;
			box-sizing: border-box;
			border-radius: 50%;
			border: 2rpx solid #999999;
		}

		.choose-image {
			width: 32rpx;
			height: 32rpx;
		}

		.box-itemr {
			font-size: 28rpx;
			color: #999999;
			display: inline-flex;
			align-items: center;
			justify-content: flex-start;
		}

		.arrow_black {
			flex-shrink: 0;
			height: 48rpx;
			width: 48rpx;
		}
	}

	.footer {
		padding: 50rpx 0;

		.savebtn {
			width: 622rpx;
			height: 88rpx;
			line-height: 88rpx;
			border-radius: 44rpx 44rpx 44rpx 44rpx;
			background-color: #FF7700;
			font-family: PingFang SC, PingFang SC;
			font-weight: 600;
			font-size: 32rpx;
			color: #FFFFFF;

			&::after {
				border: none;
			}
		}
	}
</style>