<template>
	<view class="page">
		<u-navbar title="店铺管理" :border-bottom="false" :background="bgc" back-icon-color="000" title-color='#000' title-size='36'
			height='50'></u-navbar>
		<view class="fzbox">
			<!-- 禁用 -->
			<view class="card" :class="{fixed: index === 0}" v-for="(item,index) in groupList " :key="index" v-if="index==0">
				<view class="card_left">
					<view class="img">
						<image src="https://api.ccttiot.com/smartmeter/img/static/u3jTlduBUSi1yA2H56m9" mode="aspectFit" v-show="index === 0"></image>
						<!-- <image src="https://api.ccttiot.com/smartmeter/img/static/uPN9ht93jyHZHQGzbsQC" mode="aspectFit" v-show="index !== 0"></image> -->
					</view>
					<view class="txt" style="font-size: 28rpx;">
						{{item.name.length > 10 ? item.name.substring(0, 10) + '...' : item.name }}({{item.deviceCount}})
					</view>
				</view>
				<view class="card_right">
					<image src="https://api.ccttiot.com/smartmeter/img/static/uzgOF6t4abt95qDf111j" mode="aspectFit"
						style="width: 34rpx;height: 34rpx;margin-right: 30rpx;"></image>
					<image src="https://api.ccttiot.com/smartmeter/img/static/u5rf4EUUv9e5KBef4efW" mode="aspectFit"></image>
				</view>
			</view>
			<HM-dragSorts ref="dragSorts" :list="newobj" :autoScroll="true" :feedbackGenerator="false"   @newList="handleNewList" rowHeight='50'
				 @change="change" @confirm="confirm" @onclick="onclick" :listBackgroundColor='F7FAFE'></HM-dragSorts>
		
		</view>
	
		<u-popup v-model="showpopup"  mode="center" border-radius='20'>
			<view class="popcard"  v-if="showremake">
				<view class="tit">
					修改店铺名称
				</view>
				<view class="ipt">
					 <u-input v-model="remake"  placeholder=" " border='surround'  placeholder-style='font-size: 24rpx;' />
				</view>
				<view class="btnbox">
					<view class="btn2" @click="close()">
						取消
					</view>
					<view class="btn1" @click="sub(1)">
						确定
					</view>
				</view>
			
			</view>
			<view class="popcard"  v-if="showpeice" >
			<!-- 	<view class="tit">
					新建分组
				</view> -->
				<view class="ipt">
					 <u-input v-model="price"  placeholder="请输入店铺名称" border='surround'  placeholder-style='font-size: 24rpx;'/>
				</view>
				<view class="btnbox">
					<view class="btn2" @click="close()">
						取消
					</view>
					<view class="btn1" @click="sub(2)">
						确定
					</view>
				</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
	import dragSorts from '@/page_user/HM-dragSorts/HM-dragSorts.vue'
	export default {
		components: {
			'HM-dragSorts': dragSorts
		},
		data() {
			return {
				bgc: {
					backgroundColor: "#fff",
				},
				obj: [],
				newobj:[],
				cardHeight: 114,
				touchStartIndex: -1,
				startY: 0,
				direction: 'vertical',
				touchMoveTimer: null,
				groupList:[],
				showpopup:false,
				remake:'',
				price:'',
				showpeice:false,
				showremake:false,
				firstlist:[]
				
				
			};
		},
		computed: {
			totalHeight() {
				return this.obj.length * this.cardHeight
			},
		},
		// 分享到好友（会话）
		  onShareAppMessage: function () {  
		    return {  
		      title: '创想物联',  
		      path: '/pages/shouye/index'  
		    }  
		  },  
		  
		  // 分享到朋友圈  
		  onShareTimeline: function () {  
		    return {  
		      title: '创想物联',  
		      query: '',  
		      path: '/pages/shouye/index'  
		    }  
		  },
		onLoad() {
			this.getgroup();
		},
		methods: {
			sub(num){
				if(num==1){
					let data ={
						storeId:this.groupid,
						name:this.remake
					}
					this.$u.put("/app/store",data).then((res) => {
							// this.$forceUpdate()
						if (res.code == 200) {
							this.showpopup=false
							this.showremake=false
							this.getgroup();
						    uni.navigateBack()
						// this.loadings=true
						// this.initChart()
						}
					});
					
				}else if(num==2){
					
					let data ={
						name:this.price,
						groupSort:1
					}
					this.showpopup=false
					this.showpeice=false
					this.$u.post("/app/store",data).then((res) => {
							// this.$forceUpdate()
						if (res.code == 200) {
							this.getgroup()
						
						// this.loadings=true
						// this.initChart()
						}
					});
					
				}
			},
			getgroup(){
				this.$u.get("app/store/listCount").then((res) => {
						// this.$forceUpdate()
					if (res.code == 200) {
					this.groupList=res.data
					// console.log(this.groupList)
					this.firstlist=	this.groupList[0]
					  this.newobj = this.groupList.slice(1)
					  // console.log(this.newobj,'2121212121');
					  // this.newobj = this.groupList
					  this.remake=''
					  this.price=''
					// this.loadings=true
					// this.initChart()
					}
				});
			},
			delgroup(id){
				let that = this
				uni.showModal({
				    title: '提示',  
				    content: '你确定要删掉该店铺吗？',  
				    success: function (res) {
						if (res.confirm) {
							that.$u.delete("/app/store/"+id).then((res) => {
								if (res.code == 200) {
								    that.getgroup();
								}else if(res.code == 500){
									uni.showToast({
										title: res.msg,
										icon: 'none',
										duration:2000 
									});
								}
							})
						} else if (res.cancel) {  
						    console.log('用户点击了取消')
						}  
				    }  
				})
			},
			putgroupname(id,name){
				this.groupid=id
				this.remake = name
				this.sremake()
			},
			 handleNewList(newList) {
				  let list = [this.firstlist, ...newList];
				  
					 const newSortedList = list.map((item, index) => {
					            return {
					                storeId: item.storeId,
					                groupSort: index + 1 // 使用索引值加 1 作为 groupSort
					            };
					        });
						console.log("新的排列数据:", newSortedList);
						let filteredArr = newSortedList.filter(item => item.storeId !== null)
					setTimeout(()=> {
						this.$u.put("/app/store/changeSort",filteredArr).then((res) => {
								// this.$forceUpdate()
							if (res.code == 200) {
								// this.getgroup()
							}
						});
					}, 200);
				
				// 在这里处理新的排列数据，可以将其存储到父组件的数据中，或者进行其他操作
			},
			sremake(){
				this.showpopup=true
				this.showremake=true
			},
			sprice(){
				this.showpopup=true
				this.showpeice=true
			},
			close() {
				this.showpeice=false
				this.showremake=false
				this.showpopup=false
				
			},
			push() {
				// 和数组的push使用方法一致，可以push单行，也可以push多行
				this.$refs.dragSorts.push({
					"name": "push行",
					"icon": "/static/img/2.png"
				});
			},
			unshift() {
				// 和数组的unshift使用方法一致，可以unshift单行，也可以unshift多行
				this.$refs.dragSorts.unshift({
					"name": "unshift行",
					"icon": "/static/img/2.png"
				});
			},
			splice() {
				// 和数组的unshift使用方法一致 下标1开始删除1个并在下标1位置插入行
				this.$refs.dragSorts.splice(1, 1, {
					"name": "splice行",
					"icon": "/static/img/2.png"
				});
			},
			onclick(e) {
				
			},
			change(e) {
				// console.log('=== change start ===');
				// console.log("被拖动行: " + JSON.stringify(e.moveRow));
				// console.log('原始下标：', e.index);
				// console.log('移动到：', e.moveTo);
				// console.log('=== change end ===');
			},
			confirm(e) {
				
			},
			
			


			handleTouchStart(e) {
				this.touchStartIndex = e.currentTarget.dataset.index
				this.startY = e.touches[0].clientY
			},

			handleTouchMove(e) {
				clearTimeout(this.touchMoveTimer)

				this.touchMoveTimer = setTimeout(() => {
					const deltaY = e.touches[0].clientY - this.startY
					const newIndex = Math.floor((this.obj[this.touchStartIndex].top + deltaY) / this.cardHeight)
					const maxIndex = this.obj.length - 1

					if (newIndex >= 1 && newIndex <= maxIndex) {
						this.obj[this.touchStartIndex].top += deltaY
						this.obj[newIndex].top -= deltaY

						this.startY = e.touches[0].clientY
						this.$nextTick(() => {
							this.direction = 'vertical'
						});
					} else {
						this.direction = 'none'
					}
				}, 16); // 控制触发频率，大约 60 帧每秒
			},

			handleTouchEnd() {
				this.touchStartIndex = -1
				this.startY = 0
			},

			handleMoveChange(e) {
				this.obj = e.detail.source

				// 调整位置，防止重叠
				this.obj.forEach((item, index) => {
					// 添加保护，确保 item 存在
					if (item) {
						item.top = index * this.cardHeight
					}
				});
			},
		},
	};
</script>

<style lang="scss">
	/deep/ .u-flex{
		padding-top: 20rpx !important;
		box-sizing: border-box;
	} 
	/deep/ .u-title{
		padding-bottom: 22rpx;
	}
	/deep/ .u-icon__icon{
		padding-bottom: 22rpx;
	}
	page {
		background-color: #fff;
	}

	.page {
		width: 750rpx;
		padding-bottom: 200rpx;
		.popcard{
			display: flex;
			justify-content: center;
			flex-wrap: wrap;
			// padding: 40rpx;
			width: 550rpx;
			height: 400rpx;
			border-radius: 20rpx;
			.tit{
				display: flex;
				justify-content: center;
				width: 100%;
				align-items: center;
				font-size: 28rpx;
				font-weight: 700;
			}
			.ipt{
				margin-top: 60rpx;
				width: 80%;
				// width: 60%;
				.u-input::placeholder {
				    font-size: 20px;
				    color: red;
				}
			}
			.btnbox{
				width: 100%;
				display: flex;
				flex-wrap: nowrap;
				border-radius: 0 0 20rpx 20rpx;
				.btn2{
					display: flex;
					align-items: center;
					justify-content: center;
					width: 50%;
					// justify-content: center;
					
					// width: 200rpx;
					// height: 70rpx;
					// border-radius: 20rpx;
					font-size: 32rpx;
					font-family: HarmonyOS Sans SC, HarmonyOS Sans SC;
					font-weight: 400;
					color: #000;
					background-color: #fff;
				}
				.btn1{
					display: flex;
					align-items: center;
					justify-content: center;
					width: 50%;
					// justify-content: center;
					
					// width: 200rpx;
					// height: 70rpx;
					// border-radius: 20rpx;
					font-size: 32rpx;
					font-family: HarmonyOS Sans SC, HarmonyOS Sans SC;
					font-weight: 400;
					color: #fff;
					background-color: #8883F0;
					border: 1rpx solid #ccc;
				}
			}
			
		}
		.fzbox {

			.card {
				display: flex;
				align-items: center;
				justify-content: space-between;
				margin: 32rpx auto 0;
				width: 682rpx;
				height: 114rpx;
				background: #FFFFFF;
				border-radius: 30rpx;
				box-shadow: 0rpx 16rpx 40rpx 0rpx rgba(42, 130, 228, 0.1);

				.card_left {
					display: flex;
					flex-wrap: nowrap;
					align-items: center;
					margin-left: 48rpx;

					.img {
						width: 35.3rpx;
						height: 35.3rpx;
					}

					.txt {
						margin-left: 52rpx;
						font-size: 36rpx;
						font-weight: 400;
						color: #000000;
					}
				}

				.card_right {
					margin-right: 38rpx;

					image {
						width: 45.51rpx;
						height: 31.86rpx;
					}
				}
			}
		}

		.btn {
			display: flex;
			align-items: center;
			justify-content: center;
			margin: 32rpx auto 0;
			border-radius: 30rpx;
			width: 682rpx;
			height: 114rpx;
			background: #FFFFFF;
			box-shadow: 0rpx 16rpx 40rpx 0rpx rgba(42, 130, 228, 0.1);

			image {
				margin-right: 28rpx;
				width: 39.92rpx;
				height: 39.92rpx;
			}

			font-size: 36rpx;
			font-family: Source Han Sans,
			Source Han Sans;
			font-weight: 400;
			color: #000000;
		}
	}
</style>