<template>
	<view class="select-serve">
		<custom-navbar title="设置佣金" backgroundColor="#FFFFFF"></custom-navbar>
		<view class="select-tip">
			<text style="color: #E8101E;">温馨提示：</text>支持 快速设置“百分比”（如每单返 2%）佣金，成功成交的订单，系统会按照实付金额*佣金比例进行扣减。
		</view>
		<view v-for="(item,index) in selectedItems" :key="index" class="serve-card">
			<image :src="item.photo[0]" mode="aspectFill" class="serve-card__img"></image>
			<view class="serve-card-right">
				<view class="serve-card-right-text">{{item.title}}</view>
				<view class="serve-card-right-price">¥<text style="font-size: 30rpx;">{{item.server_price}}</text>  </view>
				<view class="serve-card-right-number">
					<text class="serve-card-right-number-text">设置佣金比例</text>
					<!-- <numberBox v-model="item.numberValue" :price="item.server_price"></numberBox> -->
					<view class="numberValue">
							<view class="fuHao" @click="calculate(item,-1)">-</view>
							<view class="numberValue-card">
								<input type="number" v-model="item.numberValue" @input="changeInput(item,$event)" class="numberValue-input" placeholder="请输入比例" />
								<text class="percentage">%</text>
							</view>
							<view class="fuHao" @click="calculate(item,1)">+</view>
					</view>
				</view>
				<view class="serve-card-right-estimate" v-show="estimate(item.numberValue,item.server_price)">
					预估佣金:{{ estimate(item.numberValue,item.server_price) }}
					<image src="/static/images/recruit/tip.png" class="serve-card-right-estimate-img"
						@click="openModal"></image>
				</view>
			</view>
		</view>
		<view class="select-serve-footer">
			<view class="select-serve-footer__btn" @click="submit">确定</view>
		</view>

		<uv-modal ref="modal" title="提示" width="620rpx">
			<view class="slot-content">
				预估佣金按<text style="color: #E8101E;">「订单实付金额 × 佣金比例」</text>计算。因服务实付金额受活动参与程度影响存在波动，最终佣金以订单实际结算结果为准。
			</view>
			<template v-slot:confirmButton>
				<view type="default" @click="closeModal" class="closeModal">确定</view>
			</template>
		</uv-modal>
	</view>
</template>

<script>
	import request from "@/utils/request";
	import numberBox from "@/components/number-box/number-box";
	export default {
		components: {
			numberBox,
		},
		data() {
			return {
				clickType: false, //点击状态，防止连续点击
				selectedItems: [], // 用于接收上一页传递的选中项
				numberValue: null,
				apiObj: {
					add: {
						2: "/sj/serversPromotion/batchAdd",
						1: "/syr/serversPromotion/batchAdd"
					},
					edit: {
						2: "/sj/serversPromotion/edit",
						1: "/syr/serversPromotion/edit"
					}
				},
				identityIndex: 2,
				type: 1. //1为编辑。2为修改3为添加
			};
		},
		onLoad(options) {
			// 解析参数（注意：需先解码再转JSON）
			if (options.type) {
				this.type = options.type
			}
			if (options.selectedItems) {
				this.selectedItems = JSON.parse(decodeURIComponent(options.selectedItems));
				this.selectedItems.forEach(item => {
					this.$set(item, 'numberValue', Math.round(Number(item.commission_rate) * 100) || null);
				})
				console.log('接收的选中项：', this.selectedItems);
			}
		},
		methods: {
			calculate(item,value) {
				let num = Number(item.numberValue) + value;
				if (num > 30) {
					if(num<31){
						this.$nextTick(() => {
							item.numberValue = 30
						});
						return
					}
					uni.showToast({
						title: `不能大于30%`,
						icon: "none",
					});
				} else if (num < 0) {
					if(num>-1){
						this.$nextTick(() => {
							item.numberValue = 0
						});
						return
					}
					uni.showToast({
						title: `不能小于0%`,
						icon: "none",
					});
				}else{
					this.$nextTick(() => {
						item.numberValue = num
					});
				}
			},
			changeInput(item,event) {
				let value = parseInt(event.detail.value);
				// 将输入值转为数字（处理可能的字符串输入）
				let num = Number(value);
				// 处理非数字的情况（如输入非数字字符时，默认设为0）
				if (isNaN(num)) {
					num = 0;
				}
				// 边界值处理
				if (num > 30) {
					num = 30;
				} else if (num < 0) {
					num = 0;
				}
				this.$nextTick(()=>{
					item.numberValue = num
				})
				
			},
			openModal() {
				this.$refs.modal.open();
			},
			closeModal() {
				this.$refs.modal.close();
			},
			estimate(a, b) {
				if (a && b) {
					console.log('计算结果：', a,b);
					let product =Math.floor(a * b) / 100; // 先计算乘积
					console.log('计算结果1：', product);
					console.log('计算结果2：', product.toFixed(2));
					return product.toFixed(2); // 保留 2 位小数（返回字符串）
				} else {
					return ""
				}

			},
			submit() {
				let list = []
				for (let item of this.selectedItems) {
					if (!item.numberValue) { // 检测到未设置的项
						uni.showToast({
							title: `请设置完成佣金比例`,
							icon: "none",
						});
						return; // 直接退出整个 submit 函数，后续代码全不执行
					}
					if (this.estimate(item.numberValue, item.server_price) < 0.01) { // 检测到未设置的项
						uni.showToast({
							title: `预估佣金必须不得小于0.01`,
							icon: "none",
						});
						return; // 直接退出整个 submit 函数，后续代码全不执行
					}
					// 处理有效项
					let obj = {};
					if (this.type == 2) {
						obj.id = item.id;
					}
					obj.server_id = item.server_id || item.id;
					obj.commission_rate = item.numberValue / 100;
					list.push(obj); // 添加到数组
				}
				let data = {
					data: JSON.stringify(list)
				}
				let url = this.apiObj.add[this.identityIndex]
				if (this.type == 2) {
					data = {
						id: list[0].id,
						commission_rate: list[0].commission_rate
					}
					url = this.apiObj.edit[this.identityIndex]
				}
				if (this.clickType) {
					return
				}
				this.clickType = true
				request.post(url, data).then((res) => {
					console.log(res);
					if (res.code == 200) {
						// 修改上一页页面信息
						const pages = getCurrentPages();
						console.log(11111, pages)
						const prevPage = this.type == 3 ? pages[pages.length - 3] : pages[pages.length - 2];
						if (prevPage) {
							if (prevPage.$vm && typeof prevPage.$vm.search === "function") {
								prevPage.$vm.search(); // 存在则调用
							}
							let delta = this.type == 3 ? 2 : 1
							uni.navigateBack({
								delta
							});
						}
					}else{
						uni.showToast({
							title: res.msg || '操作失败',
							icon: "none",
						});
					}
				}).finally(() => {
					this.clickType = false
				});
			}
		}
	};
</script>

<style lang="scss">
	.select-serve {
		background-color: #f5f5f5;
		min-height: 100vh;
		padding-bottom: 160rpx;

		.select-tip {
			margin-top: 20rpx;
			background: rgba(232, 16, 30, 0.1);
			padding: 20rpx;
			font-family: PingFangSC, PingFang SC;
			font-weight: 400;
			font-size: 24rpx;
			color: #333333;
			line-height: 33rpx;
			text-align: left;
			font-style: normal;
		}

		.serve-card {
			background: #FFFFFF;
			border-radius: 20rpx;
			padding: 20rpx;
			margin: 20rpx;
			display: flex;
			gap: 20rpx;

			.serve-card__img {
				width: 150rpx;
				height: 150rpx;
				border-radius: 20rpx;
			}

			.serve-card-right {
				flex: 1;

				.serve-card-right-text {
					font-weight: 500;
					font-size: 30rpx;
					color: #333333;
					line-height: 34rpx;
					text-align: left;
					font-style: normal;
				}

				.serve-card-right-price {
					margin-top: 15rpx;
					font-family: DINPro, DINPro;
					font-weight: 500;
					font-size: 22rpx;
					color: #E8101E;
					line-height: 34rpx;
					text-align: left;
					font-style: normal;
				}

				.serve-card-right-number {
					display: flex;
					align-items: center;
					margin-top: 23rpx;

					.serve-card-right-number-text {
						font-weight: 400;
						font-size: 28rpx;
						color: #333333;
						text-align: left;
						font-style: normal;
						margin-right: 86rpx;
					}
				}

				.serve-card-right-estimate {
					display: flex;
					align-items: center;
					margin-top: 16rpx;
					background-color: rgba(245, 191, 133, 0.10);
					border-radius: 10rpx;
					font-weight: 400;
					font-size: 26rpx;
					color: #B6732B;
					text-align: left;
					font-style: normal;
					box-sizing: border-box;
					width: 100%;
					padding: 6rpx 10rpx;

					.serve-card-right-estimate-img {
						margin-left: 10rpx;
						width: 24rpx;
						height: 24rpx;
					}
				}
			}
		}


		.select-serve-footer {
			background-color: #fff;
			position: fixed;
			bottom: 0;
			left: 0;
			right: 0;
			padding: 40rpx 30rpx;

			&__btn {
				width: 690rpx;
				height: 78rpx;
				background: #E8101E;
				border-radius: 798rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				font-weight: 400;
				font-size: 30rpx;
				color: #ffffff;
				line-height: 39rpx;
				text-align: center;
				font-style: normal;
			}
		}
	}


	.closeModal {
		width: 556rpx;
		height: 80rpx;
		background: #E8101E;
		border-radius: 40rpx;
		font-weight: 500;
		font-size: 28rpx;
		color: #FFFFFF;
		line-height: 40rpx;
		text-align: left;
		font-style: normal;
		display: flex;
		align-items: center;
		justify-content: center;
		margin: 0 32rpx 50rpx 32rpx;
	}

	::v-deep .uv-modal__title {
		padding-top: 50rpx;
		font-weight: 500;
		font-size: 32rpx;
		color: #333333!important;
		line-height: 45rpx;
		text-align: center;
		font-style: normal;
	}

	::v-deep .uv-modal__content {
		padding: 30rpx 32rpx 30rpx 30rpx;
		font-weight: 400;
		font-size: 30rpx;
		color: #333333;
		line-height: 40rpx;
		text-align: left;
		font-style: normal;
	}
	
	//
	.numberValue {
			display: flex;
			gap: 12rpx;
	
			.numberValue-card {
				position: relative;
				width: 140rpx;
				padding-right: 40rpx;
				height: 46rpx;
				background: #F6F6F6;
	
				.numberValue-input {
					width: 140rpx;
					height: 46rpx;
					background: #F6F6F6;
					border-radius: 6rpx;
					text-align: center !important;
					font-weight: 500;
					font-size: 28rpx;
					color: #333333;
					line-height: 40rpx;
					text-align: left;
					font-style: normal;
				}
	
				.percentage {
					position: absolute;
					right: 9rpx;
					top: 50%;
					transform: translateY(-50%);
					font-weight: 500;
					font-size: 26rpx;
					color: #333333;
					line-height: 37rpx;
					text-align: left;
					font-style: normal;
				}
			}
	
			.fuHao {
				font-weight: 500;
				font-size: 34rpx;
				color: #333333;
				line-height: 48rpx;
				text-align: left;
				font-style: normal;
			}
	
		}
		.uni-input-placeholder{
			font-weight: 400;
			font-size: 24rpx;
			color: #D1CCCC;
			line-height: 33rpx;
			text-align: center;
			font-style: normal;
		}
</style>