<template>
	<view class="content indexCarList">
		<!-- 头部 -->
		<headerIndex :isArea="false" v-if="isShow"></headerIndex>
		<!-- 蓝牙提示区 -->
		<view v-if="userList.length">
			<view class="bleTips" v-if="islink==0">
				{{textLink}}
			</view>
			<view class="bleTips2 bleTips" v-else @click="openBluetoothAdapter">
				{{textLink}}
			</view>
		</view>

		<view class="notice" v-if="notices.length">
			<text>头条</text>
			<!--  -->
			<swiper class="swiper" vertical="true" autoplay="true">
				<swiper-item v-for="(item,index) in notices" :key="index" @click="detail(item.id)">
					<view class='overflow'>{{item.title}}</view>
				</swiper-item>
			</swiper>
		</view>

		<!-- 工具区 -->
		<view class="tools_l">
			<view v-for="(item,index) in toollist" :key="index" class="list" @click="handleTool(index,item.path)">
				<image :src="item.icon"></image>
				<view class="text">{{item.title}}</view>
			</view>
		</view>

		<!-- banner -->
		<view class="f_banner" v-if="banner.length">
			<swiper class="swiper" indicator-dots="true" autoplay="true">
				<swiper-item v-for="(image, index) in banner" :key="index" @click="detail(image.id)">
					<image :src="image.pic" mode="aspectFill" />
				</swiper-item>
			</swiper>
		</view>

		<!-- 身体数据 -->
		<view class="report">
			<view class="bold mt-10 ml-10" v-if="info&&info.top_list.length">身体报告</view>
			<view class="box" v-if="info&&info.top_list.length">
				<view class="time">{{info?info.record_time:''}}</view>
				<view class="item2">
					<view class="item2_data" :style="userInfo.stage=='婴儿'?'width:25%':'width:33%'"
						v-for="(item,index) in info.top_list" @click="handleToggleTop(item,index)">
						<view class="data" :class="[activeHeight==index?'activeHeight':'']">
							<view class="c666 mb-5">{{item.name}}</view>
							<view><text>{{item.value}}</text>{{item.unit}}</view>
						</view>
					</view>
					<view class="myinfoPage" v-if="infoListTop">
						<view class="desc">
							<view v-if="infoListTop.desc" class="ming">{{infoListTop.desc}}</view>
							<view :class="[infoListTop.list.length?'statuevue':'']" v-if="infoListTop.list">
								<view class="bi">
									<view :style="'left:'+infoListTop.offset+'%'" class="peobox">
										<view class="xx"></view>
									</view>
									<view class="item" v-for="(ite , ind) in infoListTop.list" :key="ind"
										:style="{backgroundColor:ite.color}">
										<view class="span1">{{ite.text}}</view>
										<view class="span" v-if="ind<infoListTop.list.length-1">{{ite.max_val}}</view>
									</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<view class="nolist" v-if="!info">
				<image src="../../static/none.png"></image>
				<text>暂无数据，请手动添加~</text>
			</view>
			<view class="box2" v-if="info&&info.body_type_value">
				<view>身体得分：{{info?info.score_value:0}}分</view>
				<view>身体类型：{{info?info.body_type_value:'无'}}</view>
			</view>
			<view class="bold mt-10 ml-10" v-if="info&&info.bottom_list.length">其他数据</view>
			<view class="ml-10 mr-10" v-if="info&&info.bottom_list.length">
				<view class="myinfoPage">
					<view class="box1">
						<uni-collapse accordion>
							<uni-collapse-item class="list" v-for="(item,index) in info.bottom_list" :key="index">
								<template v-slot:title>
									<uni-list-item class="block">
										<view class="name">
											<icon class="t-icon iconfont" :class="'t-icon-'+item.key_name"></icon>
											{{item.name}}
										</view>
										<view class="val" v-if="item.title=='肥胖等级'||item.title=='体型'"> - </view>
										<view class="val" v-else>{{item.value?item.value:'0'}}{{item.unit}}</view>
										<view class="level">
											<view class="btnf"
												:style="{backgroundColor:(item.standard=='异常'?'#FFF':item.color)}"
												:class="[item.standard=='异常'?'btnC':'']">
												{{item.standard=='异常'?'-':item.standard}}
											</view>
										</view>
									</uni-list-item>
								</template>
								<view class="desc">
									<view v-if="item.desc" class="ming">{{item.desc}}</view>
									<view :class="[item.list.length?'statuevue':'']" v-if="item.list">
										<view class="bi" v-if="item.title!='基础代谢'">
											<view :style="'left:'+item.offset+'%'" class="peobox">
												<view class="xx"></view>
											</view>
											<view class="item" v-for="(ite , ind) in item.list" :key="ind"
												:style="{backgroundColor:ite.color}">
												<view class="span1">{{ite.text}}</view>
												<view class="span" v-if="ind<item.list.length-1">{{ite.max_val}}</view>
											</view>
										</view>
										<view v-else>
											<view class="kcalClass" v-if="item.list&&item.list.length">
												标准值:{{item.list[0].max_val}}kcal
											</view>
										</view>
									</view>
								</view>
							</uni-collapse-item>
						</uni-collapse>
					</view>
				</view>
			</view>
			<!-- 数据参考 -->
			<view class="tips c999 ml-15 mb-15" v-if="info.literature.length">
				<text>*数据参考：</text>
				<text v-for="(item,index) in info.literature" :key="index">
					{{item}}
				</text>
			</view>
			<view class="tips2 ml-10" v-if="info.bottom_list">
				<uni-icons type="info-filled" color="red"></uni-icons>
				此测量数据仅供参考，不可代替医学专业测试！
			</view>
			<!-- 成长建议 -->
			<view v-if="cplist.sleeplist.length||cplist.nutritionlist.length" class="ml-10 mr-10">
				<view class="bold mt-10">成长建议</view>
				<view class="jianyi_box">
					<view class="jianyi">
						<view @click="proposalnd=1" :class="{active:proposalnd==1}">
							<image src="../../static/icon4.png"></image>
							<text>营养</text>
						</view>
						<view @click="proposalnd=2" :class="{active:proposalnd==2}">
							<image src="../../static/icon1.png"></image>
							<text>睡眠</text>
						</view>
						<view @click="proposalnd=3" :class="{active:proposalnd==3}">
							<image src="../../static/icon3.png"></image>
							<text>运动</text>
						</view>
						<view @click="proposalnd=4" :class="{active:proposalnd==4}">
							<image src="../../static/icon2.png"></image>
							<text>情绪</text>
						</view>
					</view>
					<view>
						<view v-if="proposalnd==1&&cplist.nutritionlist.length" class="jianyi-con">
							<text v-for="(item,index) in cplist.nutritionlist" :key="index">{{item}}</text>
						</view>
						<view v-if="proposalnd==2&&cplist.sleeplist.length" class="jianyi-con">
							<text v-for="(item,index) in cplist.sleeplist" :key="index">{{item}}</text>
						</view>
						<view v-if="proposalnd==3&&cplist.sportlist.length" class="jianyi-con">
							<text v-for="(item,index) in cplist.sportlist" :key="index">{{item}}</text>
						</view>
						<view v-if="proposalnd==4&&cplist.moodlist.length" class="jianyi-con">
							<text v-for="(item,index) in cplist.moodlist" :key="index">{{item}}</text>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 卡片 -->
		<view class="list" v-if="user">
			<view class="bold mt-10 ml-10" v-if="user.card_data_list.length">卡片数据</view>
			<view v-for="(item,index) in user.card_data_list">
				<!-- 标题 -->
				<view class="card box" @click="handlerReport(item)" :style="{'backgroundColor':item.background_color}">
					<view class="boxBg">
						<image :src="item.background_pic"></image>
					</view>
					<view class="title border">
						<view class="name2">{{item.card_name}}</view>
						<view class="time">
							{{item.record_time}}
							<uni-icons type="right" size="20" v-if="item.inside_data[0].value"></uni-icons>
						</view>
					</view>
					<view class="target item">
						<view class="bold size16 c666" v-if="item.acd_id!=2">本次数据</view>
						<view class="bold size14" v-else>
							<text class="size32">{{item.inside_data[1].value}}</text>
							{{item.inside_data[1].unit}}
						</view>
						<view class="btnGroup">
							<view class="blueBtn" v-if="item.acd_id==2" @click.stop
								@click="$Bluetooth.handleDevicesMac(item.device_determine,item.acd_id)">蓝牙连接</view>
							<view class="blueBtn" v-else-if="item.acd_id==6">蓝牙连接</view>
							<view v-else></view>
							<view class="orangeBtn" @click="handlerRecord(item.acd_id)" @click.stop>手动记录</view>
						</view>
					</view>
					<!-- 内容 -->
					<view class="item title"
						:style="{'justifyContent':item.inside_data.length>2?'space-between':'center'}">
						<view v-for="(ite,ind) in item.inside_data" :class="[item.inside_data.length>3?'item2':'']">
							<view class="weight"><text>{{ite.value?ite.value:'-'}}</text>{{ite.unit}}</view>
							<view class="name mt-5" v-if="item.acd_id!=8">{{ite.name}}</view>
						</view>
					</view>
				</view>
			</view>
		</view>
		<!-- 设置数据卡片 -->
		<view class="setcard" @click="handleCard" v-if="userList.length&&user.measure_model==1">
			设置数据页卡片
		</view>
		<!-- 弹框广告 -->
		<view class="wrapper" v-if="isCoupon">
			<view class="bg" @click="isCoupon=false">
				<view class="edit">
					<swiper class="text" autoplay="true">
						<swiper-item v-for="(ite,ind) in pop" :key="ind" @click="detail(ite.id)">
							<image :src="ite.pic" mode="aspectFill" />
							<view class="bold mt-5">{{ite.title}}</view>
						</swiper-item>
					</swiper>
					<uni-icons type="clear" @click="isCoupon=false" size="40" class="clear"></uni-icons>
				</view>
			</view>
		</view>


		<!-- <view class="nolist"  @click="handleAddUser" :style="{'marginTop':isShow?'150px':'0'}">
			<image src="../../static/none.png"></image>
			<text>请先添加成员</text>
		</view> -->
		<!-- 手动 -->
		<record :rtype="rtype"></record>

	</view>
</template>

<script>
	import {
		mapState
	} from "vuex";
	let myTime;
	import headerIndex from "@/element/headerIndex.vue"
	import record from '@/element/manuallyAdd/record.vue';
	export default {
		data() {
			return {
				rtype: 0,
				transition: 1.6,
				isShow: true,
				infoListTop: {},
				activeHeight: 0,
				deviceName: "",
				deviceId: "",
				serviceId: "",
				write: "",
				notify: "",
				isCoupon: false,
				notices: [],
				banner: [],
				pop: [],
				devicesList: [],
				islink: 0, //-1重新连接
				textLink: "",
				proposalnd: 1,
				toollist: [{
						icon: '/static/q2.png',
						title: '中招估分',
						path: "/pages/score/score"
					}, {
						icon: '/static/q4.png',
						title: 'BMI测评',
						path: "/pageTwo/home/bmi"
					},
					{
						icon: '/static/q6.png',
						title: '遗传身高',
						path: "/pageTwo/home/inheritHeighet"
					},
					{
						icon: '/static/q1.png',
						title: '智能跳绳',
						path: "/pages/skiping/skip?acd_id=6"
					},
					{
						icon: '/static/q10.png',
						title: '肺活训练',
						path: "/pages/lunging/vitalcapacity?acd_id=8"
					},
					{
						icon: '/static/q8.png',
						title: '历史体重',
						path: "/pageTwo/history/history?acd_id=2"
					},
					{
						icon: '/static/q3.png',
						title: '减脂对比',
						path: "/pageTwo/compk/contrast?acd_id=2"
					},
					{
						icon: '/static/q5.png',
						title: '曲线/目标',
						path: "/pages/body/body?acd_id=2"
					},
					{
						icon: '/static/q7.png',
						title: '手动记录',
						path: ""
					},
					{
						icon: '/static/q9.png',
						title: '成员管理',
						path: "/pageTwo/my/manage"
					},

				],
			}
		},
		components: {
			record,
			headerIndex
		},
		computed: {
			...mapState(["user", "familayList", 'MeasureResult', "isConnected", "isBluetoothTyle"]),
			userInfo() {
				return this.user
			},
			userList() {
				return this.familayList
			},
			cplist() {
				console.log("this.MeasureResult.cplist", this.MeasureResult.cplist)
				return this.MeasureResult.cplist
			},
			info() {
				let that = this
				that.infoListTop = that.MeasureResult.top_list[0] ? that.MeasureResult.top_list[0] : {}
				that.activeHeight = 0
				return that.MeasureResult
			},
		},
		onLoad(options) {
			let that = this
			// #ifdef APP-PLUS
			if (options && options.type == 1) {
				that.handleUserList()
				that.handleBannerList()
			}
			// #endif
			//  #ifndef APP-PLUS
			that.handleoginversion()
			// #endif

			uni.onBluetoothAdapterStateChange(function(res) {
				that.$store.commit("changeBluetooth", res.available);
			})
			that.onBLEConnectionStateChange()
		},
		onPullDownRefresh() {
			let that = this
			that.isShow = true
			that.handleUserList()
			that.onBLEConnectionStateChange()
			uni.stopPullDownRefresh()
		},
		watch: {
			isConnected: function() {
				let that = this
				if (!that.isConnected) {
					that.textLink = "开始连接"
					that.islink = -1
				}
			},
			isBluetoothTyle: function() {
				let that = this
				if (!that.isBluetoothTyle) {
					that.textLink = "请打开手机蓝牙后，开始测量"
					that.islink = -1
				}
			},
		},
		onShow() {
			let that = this
			console.log("onShow", uni.getStorageSync('isBle'))
			if (uni.getStorageSync('isBle') && uni.getStorageSync('isBle') == true) {
				that.openBluetoothAdapter()
				uni.setStorageSync('isBle', false)
				console.log("首次添加玩用户后初始化蓝牙", uni.getStorageSync('isBle'))
			}
		},
		methods: {
			// 是否登录
			handleoginversion() {
				let that = this
				that.$model.getloginversion({}).then(res => {
					if (res.code == 0) {
						that.handleUserList()
						that.handleBannerList()
					} else {
						uni.setStorageSync('token', null)
						uni.setStorageSync('aan_id', null)
						uni.clearStorageSync()
						uni.reLaunch({
							url: "/pageTwo/login/login"
						})
					}
				})
			},

			// 成员列表
			handleUserList() {
				let that = this
				that.$model.getUserList({
					type: 2
				}).then(res => {
					that.isShow = true
					console.log("用户列表", res, uni.getStorageSync('userid'))
					if (res.code != 0) {
						that.$tools.msg(res.msg)
						return
					}
					that.$store.commit('changeFamilay', res.data)
					if (res.data.length) {
						let userid = ""
						if (uni.getStorageSync('userid')) {
							let found = res.data.find(e => e.id == uni.getStorageSync('userid'));
							if (found !== undefined) {
								userid = found.id
							} else {
								userid = res.data[0].id
								uni.setStorageSync('userid', res.data[0].id)
							}
						} else {
							userid = res.data[0].id
							uni.setStorageSync('userid', res.data[0].id)
						}
						console.log("正确userid", userid)
						that.$store.dispatch('getUserInfo', {
							aud_id: userid
						})
						that.$store.dispatch("getResult", {
							aud_id: userid
						})
						that.handleLabelList(userid)
						that.handlePublicRecord(userid)
						that.openBluetoothAdapter()
					}
				}).catch(err => {})
			},
			// 公共卡片列表
			handleLabelList(id) {
				let that = this
				that.$model.getLabelList({
					aud_id: id
				}).then(res => {
					console.log("公共卡片项目", res)
					if (res.code == 0) {
						that.$store.commit('changeLabelList', res.data)
					}
				})
			},
			// 公共手动记录内容
			handlePublicRecord(id) {
				let that = this
				that.$model.getPublicRecord({
					aud_id: id
				}).then(res => {
					console.log("公共手动记录", res)
					if (res.code == 0) {
						that.$store.commit('changePublicRecord', res.data)
					}
				})
			},
			// banner
			handleBannerList() {
				let that = this
				that.$model.getBannerList({}).then(res => {
					if (res.code != 0) {
						that.$tools.msg(res.msg)
						return
					}
					that.notices = res.data.notice
					that.banner = res.data.banner
					that.pop = res.data.pop
					that.isCoupon = res.data.pop.length ? false : false
				})
			},
			detail(id) {
				uni.navigateTo({
					url: "/pageTwo/webview/webview?id=" + id
				})
			},
			// 设置数据页卡片
			handleCard() {
				uni.navigateTo({
					url: "/pageTwo/cardList/card"
				})
			},
			handleTool(ind, path) {
				let that = this
				if (ind == 8) {
					that.handlerRecord(2)
				} else {
					that.navTo(path)
				}
			},
			// 报告页
			handlerReport(item) {
				console.log("item", item)
				let device = item.device_determine ? 1 : 0
				uni.navigateTo({
					url: item.page_url_report + "?acd_id=" + item.acd_id + '&device=' + device
				})
			},
			// 手动添加
			handlerRecord(id) {
				this.rtype = id
				this.$store.commit('changeRecord', true)
			},
			// 添加成员
			handleAddUser() {
				uni.navigateTo({
					url: "/pageTwo/my/userInfo"
				})
			},
			handleToggleTop(item, index) {
				this.infoListTop = item
				this.activeHeight = index
			},
			navTo(url) {
				console.log("url", url)
				uni.navigateTo({
					url: url
				})
			},
			// 初始化蓝牙
			openBluetoothAdapter() {
				let that = this
				that.devicesList = []
				uni.openBluetoothAdapter({
					success: e => {
						that.islink = 0
						that.textLink = "蓝牙搜索中"
						console.log("蓝牙初始化成功")
						that.startBluetoothDeviceDiscovery()
					},
					fail: err => {
						that.islink = -1
						that.textLink = that.$tools.getBluetoothAdapter(err)
						console.log('初始化蓝牙失败:' + err);
						return
					}
				});
			},
			// 开始搜寻附近的蓝牙外围设备
			startBluetoothDeviceDiscovery() {
				let that = this
				uni.startBluetoothDevicesDiscovery({
					allowDuplicatesKey: true, //是否允许重复上报同一设备
					success: res => {
						that.onBluetoothDeviceFound();
					},
					fail: res => {}
				});
			},
			/**
			 * 发现外围设备
			 */
			onBluetoothDeviceFound() {
				var that = this;
				uni.onBluetoothDeviceFound(res => {
					res.devices.forEach(device => {
						if (!device.name && !device.localName) {
							return
						}
						if (device.name.indexOf("G02") != -1) {
							clearTimeout(myTime);
							that.deviceName = device.name
							that.deviceId = device.deviceId;
							that.$Bluetooth.stopBluetoothDevicesDiscovery()
							that.handleDevice(device)
							return
						}
						if (device.name.indexOf("Chipsea_BLE") != -1) {
							clearTimeout(myTime);
							that.deviceName = device.name
							that.deviceId = device.deviceId;
							that.$Bluetooth.stopBluetoothDevicesDiscovery()
							that.handleDevice(device)
							return
						}
						if (device.name.indexOf('YPC') != -1) {
							clearTimeout(myTime);
							that.deviceName = device.name
							device.deviceId = device.deviceId
							that.$Bluetooth.stopBluetoothDevicesDiscovery()
							that.handleDevice(device)
							return
						}
						if (device.name.toLowerCase().indexOf('pcl') != -1 || (device.localName &&
								device.localName.toLowerCase().indexOf('pcl') != -1)) {
							clearTimeout(myTime);
							that.deviceName = device.name
							that.deviceId = device.deviceId;
							that.handleDevice(device)
							return
						}
					})
				});
				that.handleMyTime()
			},
			handleDevice(device) {
				let that = this
				const foundDevices = that.devicesList
				const idx = that.$tools.inArray(foundDevices, "deviceId", device.deviceId)
				if (idx === -1) {
					// 体脂秤
					if (device.name.indexOf("PCL") != -1) {
						that.devicesList.push(device)
						uni.navigateTo({
							url: "/pageTwo/devices/PCL?deviceId=" + device.deviceId
						})
						return
					}
					// 身高仪
					if (device.name.indexOf("G02") != -1) {
						that.devicesList.push(device)
						uni.navigateTo({
							url: "/pageTwo/devices/G02?deviceId=" + device.deviceId
						})
						return
					}
					// 跳绳
					if (device.name.indexOf("YPC") != -1) {
						that.devicesList.push(device)
						uni.navigateTo({
							url: "/pages/skiping/skip?deviceId=" + device.deviceId
						})
						return
					}
					// 婴儿秤
					if (device.name.indexOf("Chipsea_BLE") != -1) {
						that.devicesList.push(device)
						uni.navigateTo({
							url: "/pageTwo/devices/B20?deviceId=" + device.deviceId
						})
						return
					}

				}
			},
			handleMyTime() {
				var that = this;
				myTime = setTimeout(function() {
					if (!that.devicesList.length) {
						that.islink = -1
						that.textLink = "未搜索到有效设备，重新搜索"
						clearTimeout(myTime);
						that.$Bluetooth.stopBluetoothDevicesDiscovery()
					}
				}, 50000);
			},
			// 从广播秤返回后更改蓝牙状态
			getBlereload() {
				let that = this
				that.islink = -1
				that.textLink = "重新测量"
			},
			// 监听蓝牙连接状态
			onBLEConnectionStateChange() {
				let that = this
				uni.onBLEConnectionStateChange(function(res) {
					console.log("监听蓝牙连接状态", res.connected)
					that.$store.commit("changeConnected", res.connected);
				})
			},
			/**
			 * 断开蓝牙模块
			 */
			closeBluetoothAdapter() {
				let that = this;
				uni.closeBluetoothAdapter({
					success: res => {
						console.log('蓝牙模块关闭成功');
					}
				})
			},
			/**
			 * 断开蓝牙连接
			 */
			closeBLEConnection() {
				var that = this;
				uni.closeBLEConnection({
					deviceId: that.deviceId,
					success: res => {
						console.log('断开蓝牙连接成功');
						that.$store.commit("changeConnected", false);
					}
				});
			},
		}
	}
</script>

<style lang="scss" scoped>
	@import "@/scss/body.scss";

	/deep/.header {
		width: 100%;

		.top {
			color: #fff;
			background: $maincolor ;
		}
	}

	/deep/.cityList {
		margin-top: -36px;
	}

	.list {
		margin-top: 0rpx;
		padding: 0;
	}

	.blueBtn {
		color: #fff;
		padding: 5px !important;
		background-color: #2397f1;
	}

	.orangeBtn {
		color: #fff;
		padding: 5px !important;
		background-color: #FF974C;
	}

	.border {
		border-bottom: 1px solid #f7f7f7;
	}

	.target {
		height: 40px;
		display: flex;
		align-items: center;
		justify-content: space-between;
		position: relative;
		z-index: 99;

		.bold {
			width: 45%;
			text-align: left;
		}

		.btnGroup {
			width: 50%;
			display: flex;
			justify-content: space-between;
		}
	}

	.item {
		position: relative;
		z-index: 99;
	}

	.size32 {
		font-size: 80rpx;
	}

	.card {
		position: relative;
		overflow: hidden;
	}


	.boxBg {
		width: 250rpx;
		height: 215rpx;
		position: absolute;
		right: 15px;
		z-index: 9;
		bottom: -50rpx;

		image {
			width: 100%;
			height: 100%;
		}
	}

	.content {
		min-height: 100vh;
		padding-bottom: 15px;
		background-color: #f7f7f7;
	}

	.bleTips {
		height: 35px;
		line-height: 35px;
		margin: 15px 10px 10px;
		background: #fff;
		border-radius: 10px;
		text-align: center;
		box-shadow: 0px 1px 5px 2px #dfe2e1fc;
	}

	.bleTips2 {
		background: #fea606;
		color: #fff;
	}

	// 工具
	.tools_l {
		width: 100%;
		display: flex;
		flex-wrap: wrap;
		padding-top: 15px;
		background: #fff;
		justify-content: space-between;

		.list {
			width: 20%;
			text-align: center;
			font-size: 14px;
			margin-bottom: 20px;

			.text {
				margin-top: 5px;
				color: #666;
				font-size: 14px;
			}
		}

		image {
			width: 35px;
			height: 35px;
		}
	}

	.activeHeight {
		padding-bottom: 10px;
		border-bottom: 2px solid $maincolor;
	}
</style>