<template>
	<view>
		<uni-nav-bar fixed :border="false" left-icon="left" title="我的家人" :statusBar="true" @clickLeft="$navBack()" @clickRight="handleAdd">
			<!-- #ifndef MP-WEIXIN -->
			<template v-slot:right>
				<view class="add">
					<image src="@/static/images/pages_watch/icons/nav_add_icon.png"></image>
					新增
				</view>
			</template>
			<!-- #endif -->
		</uni-nav-bar>
		<view class="container">
			<view class="family-card" v-for="(item,index) in list" :key="index">
				<view class="card-header border-line">
					<view class="card-title">{{item.name}}</view>
					<view class="card-header-right" v-if="item.name !== '自己'" @tap="handleEdit(index-1)">
						编辑
						<image src="@/static/images/pages_watch/icons/edit_right_arrow_right_icon.png"></image>
					</view>
				</view>
				<view class="card-body">
					<scroll-view v-if="item.child && item.child.length > 0 &&item.child[0].ble" scroll-x="true" class="device-list">
						<view class="device-item x-f" v-for="i in item.child">
							<image src="@/static/images/pages_watch/images/watch_icon.png" mode="aspectFill"></image>
							<view style="flex: 1;overflow: hidden;">
								<view>{{i.ble}}</view>
								<view class="device-item-desc x-f">
									<view :class="i.status == 1 ? 'device-status green x-f':'device-status red x-f'">
										{{i.status == 1 ? '在线' : '离线'}}
									</view>
								</view>
							</view>
						</view>
					</scroll-view>
					<!-- h5平台不扫码 -->
					<!-- #ifdef APP-PLUS || MP-WEIXIN -->
					<button class="bind_btn" @tap="handleBind(index)" :disabled="btnLoading" :loading="editIndex == index && btnLoading">
						<template v-if="editIndex == index &&btnLoading">
							绑定中...
						</template>
						<template v-else>
							<image src="@/static/images/pages_watch/icons/edit_add_icon.png"></image>
							绑定预警手表
						</template>
					</button>
					<!-- #endif -->
				</view>
			</view>
			<!-- #ifndef APP-PLUS || H5 -->
			<view class="footer-add" @click="handleAdd">新增</view>
			<!-- #endif -->
		</view>
	</view>
</template>

<script>
	import {getUser} from '@/utils/common.js'
	import permision from "@/utils/permission.js"; 
	import { getWatchUserInfo,getStatus,editUser,editMyfamily,editDevice,getFamWatchInfo } from "@/api/pages_watch/user.js";
	
	export default {
		data() {
			return {
				editIndex: 0,
				// 扫描出来的deviceId
				deviceId: "",
				// // 选择绑定的人index
				// index: 0,
				btnLoading: false,
				list: [],
				// 不包含自己
				userList: [],
				status: 1
			}
		},
		onLoad() {
			uni.$on('getScanCodeInfoFamily',(data)=>{
				this.deviceId = data.imei || ""
				this.verifyDeviceId(this.editIndex,data)
			})
		},
		onUnload() {
			uni.$off("getScanCodeInfoFamily")
		},
		onShow() {
			if(this.$isLogin()){
				this.getList()
			}
		},
		methods: {
			back() {
				uni.navigateBack({
					delta: 1
				})
			},
			// 新增
			handleAdd() {
				uni.navigateTo({
					url: "/pages_watch/index/myfamily/changeTitle?type=add",
				})
			},
			// 编辑
			handleEdit(index) {
				uni.navigateTo({
					url: '/pages_watch/index/myfamily/changeTitle?type=edit&index='+ index
				})
			},
			getList() {
				getFamWatchInfo().then(res=>{
					if(res.code == 200 && res.data && res.data.length > 0) {
						// 使用reduce方法根据name和relationship字段进行分组
						const groupedByNameAndRelationship = res.data.reduce((acc, cur) => {
						  // 如果acc中没有这个name的键，就创建一个
						  if (!acc.find(item => item.name === cur.name)) {
						    acc.push({ name: cur.name, child: [] });
						  }
						  // 将当前对象添加到对应的name下的child数组中
						  const index = acc.findIndex(item => item.name === cur.name);
						  if (index !== -1) {
						    acc[index].child.push(cur);
						  }
						  return acc;
						}, []);
						let arry = groupedByNameAndRelationship.filter(el=>el.name!='自己')
						let my = groupedByNameAndRelationship.filter(el=>el.name=='自己')
						this.list = my.concat(arry)
						this.userList = groupedByNameAndRelationship.filter(el=>el.name!='自己').map(item=>({
							name: item.name,
							deviceId: item.child.map(device => 
								device.deviceId ? device.deviceId.split(',') : []
							).reduce((acc, ids) => acc.concat(ids), []),
							relationship: item.child[0].relationship
						}))
					} else {
						this.list = []
					}
				})
			},
			// getUser(){
			// 	getWatchUserInfo({isFamily: false}).then(res=>{
			// 		let otherDevice = res.user.otherDevice ? JSON.parse(res.user.otherDevice) : []
			// 		this.userList = otherDevice.map(item=>({
			// 			...item,
			// 			deviceId: item.deviceId ? item.deviceId.split(',') : []
			// 		}))
			// 		const arry = [{
			// 			name: "自己",
			// 			deviceId: res.user.deviceId,
			// 			relationship: ""
			// 		}]
			// 		this.list = arry.concat(this.userList)
			// 	})
			// },
			// 绑定预警手表
			async handleBind(index) {
				this.editIndex = index
				// #ifdef APP-PLUS
					let status = await this.checkAppCamera(index)
					if(status == 1) {
						// this.scanQRCode(index)
						uni.navigateTo({
							url: '/pages_watch/healthMonitoring/scanCode?typeFun=getScanCodeInfoFamily'
						})
					}
				// #endif
				// #ifdef MP-WEIXIN
					this.checkWXCamera(index)
				// #endif
			},
			scanQRCode(index) {
				const that = this
			    uni.scanCode({
			        success(res) {
			            if (res.result) {
			                // 扫描成功，处理二维码内容
			                console.log('扫描结果：', res.result);
							const scanInfo = JSON.parse(res.result)
							that.deviceId = scanInfo.dev_info.imei || ""
			                that.verifyDeviceId(index,scanInfo.dev_info)
			            } else {
			                // 扫描失败
			                uni.showToast({
			                    title: '扫描失败',
			                    icon: 'none'
			                });
			            }
			        },
			        fail() {}
			    });
			},
			// 验证设备
			verifyDeviceId(index,data) {
				// index,0表示自己，如果是自己绑定直接调用修改用户信息接口
				this.btnLoading = true
				if(index == 0) {
					editDevice(data).then(res=>{
						this.btnLoading = false
						if(res.code == 200) {
							uni.showToast({
								title: res.msg,
								icon: "none",
								position: 'top',
								duration: 2000
							})
							// this.getUser()
							this.getList()
						} else {
							uni.showToast({
								title: res.msg,
								icon: "none",
								position: 'top',
								duration: 2000
							})
						}
					}).catch(err=>{
						this.btnLoading = false
					})
				} else {
					this.bindDeviceId(index)
					// getStatus({deviceId: this.deviceId}).then(res=>{
					// 	if(res.code == 200) {
					// 		if(res.data === 0 || res.data === 1 || res.data === 2 || res.data === 3) {
					// 			this.bindDeviceId(index)
					// 		} else {
					// 			this.btnLoading = false
					// 			uni.showToast({
					// 				title: '绑定失败',
					// 				icon: "none",
					// 				position: 'top',
					// 				duration: 2000
					// 			})
					// 		}
					// 	}else {
					// 		this.btnLoading = false
					// 		uni.showToast({
					// 			title: res.msg,
					// 			icon: "none",
					// 			position: 'top',
					// 			duration: 2000
					// 		})
					// 	}
					// }).catch(err=>{
					// 	this.btnLoading = false
					// })
				}
			},
			// 绑定设备
			bindDeviceId(index) {
				const param = this.userList.map((item,idx)=>({
					...item,
					deviceId: idx == index-1 && !item.deviceId.includes(this.deviceId) ? item.deviceId.concat([this.deviceId]).join(',') : item.deviceId.join(',')
				}))
				console.log("this.userList=====",this.userList)
			
				editMyfamily({otherDevice: JSON.stringify(param)}).then(res=>{
					this.btnLoading = false
					if(res.code == 200) {
						uni.showToast({
							title: "绑定成功",
							icon: "none",
							position: 'top',
							duration: 2000
						})
						// this.getUser()
						this.getList()
					} else {
						uni.showToast({
							title: res.msg,
							icon: "none",
							position: 'top',
							duration: 2000
						})
					}
				}).catch(err => {
					this.btnLoading = false
					console.log('err', err);
				})
			},
			async checkAppCamera() {
				let status = permision.isIOS ? await permision.requestIOS("camera") : await permision.requestAndroid("android.permission.CAMERA")
				if(status === null || status == 1) {
					status == 1 
				} else if(status == 2) {
					uni.showModal({
						content: "相机权限已关闭",
						showCancel: false,
						success: () => {}
					})
				} else if(status.code) {
					uni.showModal({
						content: status.message
					})
				} else {
					uni.showModal({
						content: "为了使用相机功能，请点击设置开启相机权限",
						confirmText: "设置",
						success: (res) => {
							if(res.confirm) {
								permision.gotoAppSetting()
							}
						}
					})
				}
				return status
			},
			checkWXCamera(index) {
				const that = this
				uni.getSetting({
					success(res) {
						// 判断是否拥有此权限进行拉起授权  和 重新授权功能
						if (!res.authSetting['scope.camera']) {
							// 未授权此项权限 拉起授界面
							uni.authorize({
								scope: 'scope.camera',
								success() {
									// 授权成功后 就可以执行 需要权限的  操作函数了
									// 使用已授权的功能
									that.scanQRCode(index);
								},
								fail(err) {
									/*
									 第一次拒绝授权后必须在 uni.authorize的fail中使用
									 uni.openSetting 才能进入设置界面打开授权按钮
									 */
									uni.showToast({
										title: '您拒绝了授权',
										icon: 'none'
									});
									// 这里必须经过一个confirm 不然也会出现问题（啥问题我也不知道）
									uni.showModal({
										title: '是否重新授权相机功能',
										success(res) {
											if (res.confirm) {
												uni.openSetting({
													success() {
														console.log('开启权限成功');
													},
													fail() {
														console.log('开启权限失败');
													}
												});
											} else if (res.cancel) {
												console.log('拒绝开启开启权限');
											}
										}
									});
								}
							});
						} else {
							that.scanQRCode(index)
						}
					}
				});
			}
		}
	}
</script>

<style lang="scss" scoped>
	@mixin u-flex($flexD, $alignI, $justifyC) {
		display: flex;
		flex-direction: $flexD;
		align-items: $alignI;
		justify-content: $justifyC;
	}
	.device-list {
		white-space: nowrap;
		padding-top: 24rpx;
	}
	.device-item {
		display: inline-flex;
		border-radius: 16rpx;
		padding: 16rpx;
		margin-right: 20rpx;
		box-sizing: border-box;
		font-family: PingFang SC, PingFang SC;
		font-weight: 500;
		font-size: 32rpx;
		color: #333333;
		border: 2rpx solid #f5f5f5;
		&:last-of-type {
			margin-bottom: 0;
		}
		image {
			width: 78rpx;
			height: 78rpx;
			border-radius: 50%;
			padding: 10rpx;
			margin-right: 28rpx;
		}
		.green {
			&::after {
				background-color: #52D087;
			}
		}
		.red {
			&::after {
				background-color: #FF5558;
			}
		}
		.device-status {
			padding-left: 30rpx;
			position: relative;
			&::after {
				content: "";
				width: 16rpx;
				height: 16rpx;
				border-radius: 50%;
				position: absolute;
				left: 0;
				top: 50%;
				transform: translateY(-50%);
			}
		}
		.device-item-desc {
			margin-top: 6rpx;
			font-family: PingFang SC, PingFang SC;
			font-weight: 400;
			font-size: 28rpx;
			color: #757575;
			.watch {
				flex-shrink: 0;
				width: 40rpx;
				height: 40rpx;
				margin-left: -16rpx;
				margin-right: -6rpx;
			}
			.electricity {
				flex-shrink: 0;
				width: 36rpx;
				height: 32rpx;
				margin: 0 10rpx 0 64rpx;
			}
		}
	}
	.footer-add {
		width: 702rpx;
		height: 98rpx;
		background: #FFFFFF;
		border-radius: 16rpx;
		font-family: PingFang SC, PingFang SC;
		font-weight: 500;
		font-size: 32rpx;
		color: #FF7700;
		line-height: 98rpx;
		text-align: center;
		margin-top: 24rpx 0;
	}
	.add {
		font-family: PingFang SC, PingFang SC;
		font-weight: 400;
		font-size: 24rpx;
		color: #FF7700;
		@include u-flex(row, center, flex-end);
		image {
			flex-shrink: 0;
			width: 48rpx;
			height:  48rpx;
			margin-right: 6rpx;
		}
	}
	.container {
		padding: 24rpx;
		.family-card {
			width: 100%;
			min-height: 298rpx;
			margin-bottom: 20rpx;
			padding: 24rpx;
			box-sizing: border-box;
			background: #FFFFFF;
			border-radius: 16rpx 16rpx 16rpx 16rpx;
		}
	}
	.card{
		&-header {
			height: 64rpx;
			padding-bottom: 18rpx;
			width: 100%;
			line-height: 64rpx;
			@include u-flex(row, center, space-between);
			font-family: PingFang SC, PingFang SC;
			font-weight: 400;
			font-size: 24rpx;
			color: #999999;
			position: relative;
			image {
				height: 48rpx;
				width: 48rpx;
			}
			&-right {
				flex-shrink: 0;
				@include u-flex(row, center, flex-start);
			}
		}
		&-title {
			font-weight: 500;
			font-size: 32rpx;
			color: #333333;
		}
		&-body {
			.bind_btn {
				width: 308rpx;
				height: 72rpx;
				background-color: #fff;
				border-radius: 36rpx 36rpx 36rpx 36rpx;
				border: 2rpx solid #ECECEC;
				font-family: PingFang SC, PingFang SC;
				font-weight: 400;
				font-size: 24rpx;
				color: #333333;
				@include u-flex(row, center, center);
				margin: auto;
				margin-top: 60rpx;
				&::after {
					border: none;
				}
				image {
					width: 24rpx;
					height: 24rpx;
					margin-right: 12rpx;
				}
			}
		}
	}
</style>