<template>
	<view>
		<uni-nav-bar fixed :border="false" title="编辑卡片" :statusBar="true" @clickLeft="back" @clickRight="handleSubmit">
			<template v-slot:left>
				<view class="nav-bar-left">取消</view>
			</template>
			<!-- #ifndef MP-WEIXIN -->
			<template v-slot:right>
				<view class="nav-bar-save">保存</view>
			</template>
			<!-- #endif -->
		</uni-nav-bar>
		<view class="container">
			<view class="tips">拖动可调整应用位置</view> 
			<view class="box-title">显示在健康监测页</view>
			<view>
				<!-- gap: rowSpace + 'rpx '+ columnSpace + 'rpx ' -->
				<movable-area class="box-con" :style="{height: boxHeight + 'px',marginBottom: `-${rowSpace}rpx`}" id="drag">
					<movable-view 
						v-for="(item, index) in currentList" 
						:key="index" 
						:x="item.x"
						:y="item.y"
						damping="40"
						disabled
						:animation="item.animation"
						:direction="direction" 
						:data-index="index"
						:class="{'active': active == index}"
						:style="{width: columnWidth + 'px', height: rpxTopx(rowHeight) + 'px'}"
						@touchstart="touchstart"
						@touchmove.stop="touchmove"
						@touchend="touchend"
					>
					<view class="box-conitem" :style="{width: columnWidth + 'px', height: rpxTopx(rowHeight) + 'px',marginBottom: `${rowSpace}rpx`}">
						<image class="editicon" src="@/static/images/pages_watch/icons/remove_icon.png" mode="aspectFill" @click.stop="close(index,item)"></image>
						<text>{{item.type}}</text>
						<image :src="item.icon" mode="aspectFill"></image>
					</view>
					</movable-view>
				</movable-area>
			</view>
			<view class="box-title" style="margin-top: 40rpx;">可添加的健康卡片</view>
			<!-- :style="{gap: rowSpace + 'rpx '+ columnSpace + 'rpx ', }" -->
			<view class="box-con" :style="{marginBottom: `-${rowSpace}rpx`}">
				<view class="box-conitem" v-for="(item,index) in list" :key="item.key" :style="{width: columnWidth + 'px', height: rpxTopx(rowHeight) + 'px',marginBottom: `${rowSpace}rpx`}">
					<image class="editicon" src="@/static/images/pages_watch/icons/increase_icon.png" mode="aspectFill" @click="handleAdd(item,index)"></image>
					<text>{{item.type}}</text>
					<image :src="item.icon" mode="aspectFill"></image>
				</view>
			</view>
			<!-- #ifndef APP-PLUS || H5 -->
			<button class="footer-save-btn" :loading="btnLoading" :disabled="btnLoading" @click="handleSubmit">保存</button>
			<!-- #endif -->
		</view>
	</view>
</template>

<script>
	import { monitorDataType } from "@/api/pages_watch/healthMonitoring.js"
	import { editUser } from "@/api/pages_watch/user.js"
	
	export default {
		data() {
			return {
				btnLoading: false,
				columnWidth: 0, //列宽，单位px
				rowHeight: 128, //行高，单位rpx
				rowNum: 1, //行数
				boxHeight: 10, //可拖动区域的高度，单位px
				windowWidth: 750, //系统获取到的窗口宽度，单位px
				columnNum: 2, // 列数
				rowSpace: 22, //行间距，单位rpx
				columnSpace: 22, //列间距，单位rpx
				xMoveUnit: 0, //沿x轴移动时的单位距离，单位px
				yMoveUnit: 0, //沿y轴移动时的单位距离，单位px
				topY: 0, // 距离顶部的距离
				topX: 0, // 距离左侧偏移位置
				deviationX: 0,
				deviationY: 0 ,// 偏移量
				active: -1, // 当前激活的item
				index: 0, // 当前激活的item的原index
				direction: "all",
				monitorDataTypeOrder: "", // 当前登录用户设置显示的健康监测卡片
				currentList: [
					
				],
				list: [
					// {
					// 	name: "血糖",
					// 	icon: require("@/static/images/pages_watch/icons/blood_sugar_icon.png")
					// },
					// {
					// 	name: "血压",
					// 	icon: require("@/static/images/pages_watch/icons/blood_pressure_icon.png")
					// },
					// {
					// 	name: "心率",
					// 	icon: require("@/static/images/pages_watch/icons/heart_rate_icon.png")
					// },{
					// 	name: "血氧",
					// 	icon: require("@/static/images/pages_watch/icons/blood_oxygen_icon.png")
					// },
					// {
					// 	name: "体温",
					// 	icon: require("@/static/images/pages_watch/icons/temperature_icon.png")
					// },
					// {
					// 	name: "呼吸",
					// 	icon: require("@/static/images/pages_watch/icons/breathe_icon.png")
					// },
					// {
					// 	name: "血脂",
					// 	icon: require("@/static/images/pages_watch/icons/blood_fat_icon.png")
					// },{
					// 	name: "尿酸",
					// 	icon: require("@/static/images/pages_watch/icons/uric_acid_icon.png")
					// },{
					// 	name: "血管硬化",
					// 	icon: require("@/static/images/pages_watch/icons/angiosclerosis_icon.png")
					// },{
					// 	name: "血酮",
					// 	icon: require("@/static/images/pages_watch/icons/blood_ketone_icon.png")
					// },{
					// 	name: "睡眠",
					// 	icon: require("@/static/images/pages_watch/icons/sleep_icon.png")
					// },{
					// 	name: "房颤",
					// 	icon: require("@/static/images/pages_watch/icons/atrial_fibrillation_icon.png")
					// },{
					// 	name: "舌诊",
					// 	icon: require("@/static/images/pages_watch/icons/tongue_diagnosis_icon.png")
					// }
				]
			}
		},
		onLoad() {
			const res = uni.getSystemInfoSync();
			this.windowWidth = res.windowWidth
			if(uni.getStorageSync("userWatchInfo")) {
				const userInfo = JSON.parse(uni.getStorageSync("userWatchInfo"))
				this.monitorDataTypeOrder = userInfo.monitorDataTypeOrder
				this.getAllList()
			}
		},
		methods: {
			back() {
				uni.navigateBack({
					delta: 1
				})
			},
			// 保存
			handleSubmit() {
				const sortList = this.currentList.slice().sort((a, b) => a.SortNumber - b.SortNumber);
				const monitorDataTypeOrder = sortList.map(item=>item.id)
				this.btnLoading = true
				editUser({monitorDataTypeOrder:monitorDataTypeOrder.join(',')}).then(res=>{
					this.btnLoading = false
					if(res.code == 200) {
						uni.showToast({
							title: "保存成功",
							icon: "none"
						})
						uni.navigateBack()
					} else {
						uni.showToast({
							title: res.msg,
							icon: "none"
						})
					}
				}).catch(()=>{
					this.btnLoading = false
				})
			},
			/* prx转换成px，返回值还是不带px单位的Number */
			rpxTopx(v) {
				return this.windowWidth * v / 750
			},
			handleAdd(item,index) {
				this.list.splice(index,1)
				this.currentList.push(item)
				this.onUpdateCurrentList()
			},
			// 关闭按钮
			close(index,item) {
				this.currentList.forEach((item, i) => {
					if (this.currentList[i].SortNumber > this.currentList[index].SortNumber) {
						item.SortNumber--
					}
				})
				this.moveUpdateCurrentList(-1)
				this.currentList[index].isShow = 0
				this.currentList.splice(index,1)
				this.list.push(item)
			},
			getAllList() {
				monitorDataType().then(res=>{
					if(res.code == 200) {
						if(this.monitorDataTypeOrder) {
							const order = this.monitorDataTypeOrder.split(',')
						    let list = res.data || []
							this.list = list.filter(item=> order.indexOf(item.id) == -1)
							const indexOrder = this.monitorDataTypeOrder.split(","); // 指定的索引顺序
							this.currentList = list.filter(item => order.includes(item.id));
							this.currentList.sort((a, b) => indexOrder.indexOf(a.id) - indexOrder.indexOf(b.id));
						} else {
							this.list = res.data || []
							this.currentList = []
						}
						const query = uni.createSelectorQuery().in(this);
						query.select('#drag').boundingClientRect(data => {
							this.columnWidth = (data.width - (this.columnNum - 1) * this.rpxTopx(this.columnSpace)) / this.columnNum
							this.onUpdateCurrentList();
						}).exec();
					}
				})
			},
			onUpdateCurrentList(list = this.currentList) {
				this.rowNum = Math.ceil(this.currentList.length / this.columnNum);
				this.boxHeight = this.rowNum * this.rpxTopx(this.rowHeight) + (this.rowNum - 1) * this.rpxTopx(this.rowSpace);
				
				this.xMoveUnit = this.columnWidth + this.rpxTopx(this.columnSpace);
				this.yMoveUnit = this.rpxTopx(this.rowHeight) + this.rpxTopx(this.rowSpace);

				let arr = []
				for (const key in list) {
					let x = this.xMoveUnit * (key % this.columnNum); //单位px
					let y = Math.floor(key / this.columnNum) * this.yMoveUnit; //单位px
					arr.push({
						...list[key],
						isShow: 1,
						index: Number(key),
						SortNumber: Number(key),
						y,
						x,
						animation: true
					})
				}
				this.currentList = arr
			},
			// 根据排序进行重新计算位置
			moveUpdateCurrentList(index) {
				for (const i in this.currentList) {
					let key
					if (this.currentList[i].SortNumber || this.currentList[i].SortNumber === 0) {
						key = this.currentList[i].SortNumber
					} else {
						key = Number(i)
					}
					// debugger
					this.currentList[i].y = Math.floor(key / this.columnNum) * this.yMoveUnit; //单位px
					if (index == key) {
						continue
					} else {
						this.currentList[i].x = this.xMoveUnit * (key % this.columnNum); //单位px
					}
				}
			},
			touchstart(e) {
				// 计算 x y 轴点击位置
				var query = uni.createSelectorQuery().in(this)
				query.select('#drag').boundingClientRect()
				query.exec((res) => {
					this.topY = res[0].top
					this.topX = res[0].left
					const mp = e.mp || e
					let touchY = mp.touches[0].clientY - res[0].top
					let touchX = mp.touches[0].clientX - res[0].left
					// this.deviationY = touchY % this.height
					// this.deviationX = touchX % (this.windowWidth * 0.2)
					this.active = Number(e.currentTarget.dataset.index)
					this.index = Number(e.currentTarget.dataset.index)

				})
			},
			touchmove(e) {
				if (this.active < 0) return
				const mp = e.mp || e
				let temY = mp.touches[0].clientY - this.topY
				let temX = mp.touches[0].clientX - this.topX
				let touchY = temY - 30
				let touchX = temX - this.windowWidth * 0.1
				this.currentList[this.active].y = touchY
				this.currentList[this.active].x = touchX
				this.currentList[this.active].animation = false
	
				this.currentList.every((res, index) => {
					let absX = Math.abs(touchX - res.x)
					let absY = Math.abs(touchY - res.y)
					// 设置元素定点距离多少进行重排
					if (res.isShow == 0){
						return true 
					}
					if (0 < absX && absX <= 20 && absY > 0 && absY <= 40 && this.active != index) {
						// debugger
						let temNumber = this.currentList[index].SortNumber
						this.currentList.every((_res, _index) => {
							// 判断从大像小移还是从小向大移
							if (this.currentList[this.active].SortNumber < this.currentList[index].SortNumber) {
								// 移动元素比目标元素所在位置小，之间元素排序--
								if (this.currentList[_index].SortNumber > this.currentList[this.active].SortNumber && this.currentList[
										_index].SortNumber <= this.currentList[index].SortNumber) {
									_res.SortNumber--
								}
							} else {
								// 反之++
								if (this.currentList[_index].SortNumber < this.currentList[this.active].SortNumber && this.currentList[
										_index].SortNumber >= this.currentList[index].SortNumber) {
									_res.SortNumber++
								}
							}
							return true
						}, this)
						this.currentList[this.active].SortNumber = temNumber
						this.moveUpdateCurrentList(temNumber)
						return false
					} else {
						return true
					}
				}, this)
			},
			touchend(e) {
				if (this.currentList[this.active]) {
					this.currentList[this.active].animation = true
				}
				this.moveUpdateCurrentList(-1)
				this.active = -1
			},
		}
	}
</script>

<style lang="scss" scoped>
	@mixin u-flex($flexD, $alignI, $justifyC) {
		display: flex;
		flex-direction: $flexD;
		align-items: $alignI;
		justify-content: $justifyC;
	}
	.nav-bar-save {
		width: 100rpx;
		height: 52rpx;
		background: #FF7700;
		border-radius: 26rpx 26rpx 26rpx 26rpx;
		font-family: PingFang SC, PingFang SC;
		font-weight: 400;
		font-size: 26rpx;
		color: #FFFFFF;
		text-align: center;
		line-height: 52rpx;
	}
	.footer-save-btn {
		width: 702rpx;
		height: 98rpx;
		margin-top: 40rpx;
		background: #FF7700 !important;
		border-radius: 16rpx 16rpx 16rpx 16rpx;
		font-family: PingFang SC, PingFang SC;
		font-weight: 500;
		font-size: 32rpx;
		color: #FFFFFF !important;
		line-height: 98rpx;
		
		&::after {
			border: none;
		}
	}
	.nav-bar-left {
		margin-left: 8rpx;
		font-family: PingFang SC, PingFang SC;
		font-weight: 400;
		font-size: 32rpx;
		color: #FF7700;
	}
	.container {
		padding: 0 24rpx 24rpx 24rpx;
		font-family: PingFang SC, PingFang SC;
		font-weight: 500;
		font-size: 32rpx;
	}
	.tips {
		padding: 16rpx 0;
		text-align: center;
		font-size: 26rpx;
		font-weight: 400;
		color: #CCCCCC;
	}
	.box {
		&-title {
			height: 80rpx;
			line-height: 80rpx;
			margin-bottom: 20rpx;
		}
		&-con {
			width: 100%;
			position: relative;
			@include u-flex(row, center, space-between);
			flex-wrap: wrap;
			// gap: 22rpx;
		}
		&-conitem {
			// width: 340rpx;
			// width: 50%;
			// flex: 1;
			// height: 128rpx;
			padding: 0 34rpx 0 24rpx;
			box-sizing: border-box;
			background: #FFFFFF;
			border-radius: 16rpx 16rpx 16rpx 16rpx;
			@include u-flex(row, center, space-between);
			position: relative;
			image {
				height: 72rpx;
				width: 72rpx;
			}
			.editicon {
				height: 32rpx;
				width: 32rpx;
				position: absolute;
				right: 0;
				top: 0;
			}
		}
	}
	.active {
		box-shadow: 0 0 40rpx #DDDDDD;
		z-index: 99;
	}
</style>