<template>
	<view class="page">
		<u-navbar title="车型编辑" :border-bottom="false" :background="bgc" title-color='#000' title-size='36'
			height='45'></u-navbar>
		<view class="card">
			<view class="card_li">
				<view class="card_left">
					车型名称
				</view>
				<view class="card_right">
					<input type="text" v-model="data.model" placeholder="请输入车型名称" class="input"
						placeholder-style="color:#C7CDD3">
				</view>
			</view>
			<view class="card_li" style="margin-top: 30rpx;">
				<view class="up_left">
					<view class="txt1">
						上传车辆照片
					</view>
					<view class="txt2">
						门头照片必须清晰、方正、易于辨识
					</view>
				</view>
				<view class="up_rignt">
					<image src="https://lxnapi.ccttiot.com/bike/img/static/u08cpfIllwweGcS9awYP" mode=""
						v-if="data.picture == ''" @click="btn()"></image>
					<image :src="data.picture" mode="" v-else @click="btn()"></image>
					<image src="https://lxnapi.ccttiot.com/bike/img/static/uFp9riSLtpmuq6gyKfdr" mode="" class="close"
						v-if="data.picture != ''" @click="clearPicture"></image>
				</view>
			</view>
		</view>
		<view class="card">
			<view class="card_li">
				<view class="card_left">
					最高电压
				</view>
				<view class="card_right">
					<input type="text" v-model="data.fullVoltage" placeholder="请输入电压" class="input"
						placeholder-style="color:#C7CDD3"><span> v</span>
				</view>
			</view>
			<view class="card_li">
				<view class="card_left">
					最低电压
				</view>
				<view class="card_right">
					<input type="text" v-model="data.lowVoltage" placeholder="请输入电压" class="input"
						placeholder-style="color:#C7CDD3"><span> v</span>
				</view>
			</view>
			<view class="card_li">
				<view class="card_left">
					满电续航
				</view>
				<view class="card_right">
					<input type="text" v-model="data.fullEndurance" placeholder="请输入续航公里" class="input"
						placeholder-style="color:#C7CDD3">
					<span> KM</span>
				</view>
			</view>
			<view class="card_li">
				<view class="card_left">
					押金
				</view>
				<view class="card_right">
					<input type="text" v-model="data.deposit" placeholder="请输入押金金额" class="input"
						placeholder-style="color:#C7CDD3">
					<span> 元</span>
				</view>
			</view>
			<view class="card_li">
				<view class="card_left">
					车型简介
				</view>
				<view class="card_right">
					<input type="text" v-model="data.description" placeholder="请输入车型简介" class="input"
						placeholder-style="color:#C7CDD3">

				</view>
			</view>
		</view>
		<view class="card">
			<view class="card_li" @click="toRule">
				<view class="card_left">
					收费模板
				</view>
				<view class="card_right">
					<view class="iconfont icon-xiangyou1 " style="color: #CBCBCB;">

					</view>
				</view>
			</view>
			<view class="rule_box">
				<view class="rule_item" v-for="item in ruleList" :key="item.ruleId">
					<view class="rule_txt">
						收费价格：{{ item.price }}元/1{{ timetype(item.rentalUnit) }}
					</view>
					<view class="rule_txt">
						超出费用：超出每{{ timetype(item.outUnit) }}收费{{ item.outPrice }}元
					</view>
				</view>
			</view>
		</view>


		<view class="btn_box">
			<view class="btn1" @click="back">
				取消
			</view>
			<view class="btn2" @click="sub">
				保存
			</view>
		</view>
	</view>
</template>

<script>
export default {
	data() {
		return {
			bgc: {
				backgroundColor: "#fff",
			},
			showpart: false,
			list: [],
			Accessorylist: [],
			chooseIdxArr: [], // 存储选中的索引
			data: {
				model: "",
				fullVoltage: "",
				lowVoltage: "",
				fullEndurance: "",
				accessoryIds: [],
				deposit: "",
				picture: "",
				description: "",

			},
			token: '',
			upurl: '',
			modelId: '',
			ruleList: [],
			originRuleList: []
		}
	},
	onLoad(e) {
		if (e.modelId) {
			console.log(e);
			this.modelId = e.modelId
			this.getmodelInfo()
		}
		this.getQiniuToken()

	},
	onShow() {

		// this.getModelList()
		this.ruleList = this.originRuleList.filter(item =>
			this.data.feeRulesIds.includes(item.ruleId)
		);
		console.log(this.data.feeRulesIds, 'this.data.feeRulesIds');
		console.log(this.ruleList, 'this.ruleList');
	},

	methods: {
		clearPicture() {
            uni.showModal({
                title: '提示',
                content: '确定要删除该图片吗？',
                success: (res) => {
                    if (res.confirm) {
                        this.data.picture = '';
                        uni.showToast({
                            title: '删除成功',
                            icon: 'none',
                            duration: 2000
                        });
                    }
                }
            });
        },
		timetype(time) {
			if (time == 'hours') {
				return '小时'
			} else if (time == 'day') {
				return '天'
			} else if (time == 'week') {
				return '周'
			} else if (time == 'month') {
				return '月'
			} else if (time == 'quarter') {
				return '季度'
			} else if (time == 'year') {
				return '年'
			}
		},
		toRule() {
			uni.navigateTo({
				url: '/pages_store/Operator/chooseRule?modelIds=' + this.data.feeRulesIds.join(',')
			});
		},
		getRuleList() {
			this.$u.get("/appVerify/ruleList").then((res) => {
				if (res.code == 200) {
					this.originRuleList = res.data;
					// 在获取数据成功后进行筛选
					if (this.data.feeRulesIds && this.data.feeRulesIds.length > 0) {
						this.ruleList = this.originRuleList.filter(item =>
							this.data.feeRulesIds.includes(item.ruleId)
						);
					}
					console.log(this.data.feeRulesIds, 'this.data.feeRulesIds');
					console.log(this.ruleList, 'this.ruleList');
				}
			});
		},
		back() {
			uni.navigateBack()
		},
		getmodelInfo() {

			let data = {
				modelId: this.modelId
			}
			this.$u.get("appVerify/getModelById?", data).then((res) => {
				if (res.code == 200) {
					this.data = res.data
					if (this.data.accessorys && this.data.accessorys.length > 0) {
						this.data.accessoryIds = this.data.accessorys.map(accessory => accessory.accessoryId);
					} else {
						// 如果没有配件数据，确保 accessoryIds 是空数组
						this.data.accessoryIds = [];
					}

					this.chooseIdxArr = this.data.accessoryIds.map(accessoryId => {
						// 找到 Accessorylist 中与 accessoryId 匹配的索引
						const index = this.Accessorylist.findIndex(item => item.accessoryId ==
							accessoryId);
						return index > -1 ? index : null; // 如果找到匹配项，返回索引，否则返回 null
					}).filter(idx => idx !== null); // 过滤掉未找到的 null 值


					// 调用 getAccessoryNames 方法获取选中的配件名称
					const selectedAccessoryIds = this.chooseIdxArr.map(i => this.Accessorylist[i].accessoryId);
					const selectedAccessoryNames = this.getAccessoryNames(selectedAccessoryIds);

					this.getRuleList()
				}
			});
		},
		sub() {
			if (!this.data.model) {
				uni.showToast({
					title: '请填写车型名称',
					icon: 'none',
					duration: 2000
				});
				return;
			}
			if (!this.data.deposit) {
				uni.showToast({
					title: '请填写押金',
					icon: 'none',
					duration: 2000
				});
				return;
			}

			// 转换 feeRulesIds 为数字数组
			if (this.data.feeRulesIds && this.data.feeRulesIds.length > 0) {
				this.data.feeRulesIds = this.data.feeRulesIds.map(Number);
			}

			if (this.modelId) {
				this.$u.put("/appVerify/model", this.data).then((res) => {
					if (res.code == 200) {
						uni.showToast({
							title: '操作成功',
							icon: 'none',
							duration: 1000
						});
						setTimeout(() => {
							uni.navigateBack()
						}, 1200)
					}
				});
			} else {
				this.$u.post("/appVerify/model", this.data).then((res) => {
					if (res.code == 200) {
						uni.showToast({
							title: '操作成功',
							icon: 'none',
							duration: 1000
						});
						setTimeout(() => {
							uni.navigateBack()
						}, 1200)
					}
				});
			}
		},
		btn() {
			let _this = this
			let math = 'static/' + _this.$u.guid(20)
			uni.chooseImage({
				count: 1,
				type: 'all',
				success(res) {
					// tempFilePath可以作为img标签的src属性显示图片
					const tempFilePaths = res.tempFiles
					// let tempFilePaths = chooseImageRes.tempFilePaths;
					// console.log(tempFilePaths)
					// tempFilePaths.forEach(item=>{
					// 	// 上传图片到七牛云

					// })
					wx.uploadFile({
						url: 'https://up-z2.qiniup.com',
						name: 'file',
						filePath: tempFilePaths[0].path,
						formData: {
							token: _this.token, //后端返回的token
							key: 'bike/img/' + math
						},
						success: function (res) {

							let str = JSON.parse(res.data)

							_this.data.picture = _this.upurl + '/' + str.key
							console.log(_this.data.picture)
						}
					});
				}
			})

			// });
		},
		getQiniuToken() {

			this.$u.get("/common/qiniu/uploadInfo").then((res) => {
				if (res.code == 200) {
					this.token = res.token
					console.log(res, 'resres');
					this.upurl = res.domain
				}
			});


		},
		subacc() {
			this.showpart = false
			console.log(this.chooseIdxArr);
		},
		chooseAcc(itm, idx) {
			const index = this.chooseIdxArr.indexOf(idx);
			if (index > -1) {
				// 如果索引已存在于数组中，表示已经选中，再点击则取消选中
				this.chooseIdxArr.splice(index, 1);
			} else {
				// 如果索引不存在于数组中，表示未选中，添加到数组中
				this.chooseIdxArr.push(idx);
			}
			// 获取选中的 accessoryId 列表
			const selectedAccessoryIds = this.chooseIdxArr.map(i => this.Accessorylist[i].accessoryId);
			console.log(selectedAccessoryIds, 'selectedAccessoryIds');
			// 将 accessoryId 数组拼接成字符串
			// const selectedAccessoryIdsStr = selectedAccessoryIds.join(',');
			this.data.accessoryIds = selectedAccessoryIds
			// console.log(selectedAccessoryIdsStr,'selectedAccessoryIdsStrselectedAccessoryIdsStr');''
			// 比对数据
			// if (selectedAccessoryIdsStr === this.data.accessoryIds) {
			//     console.log('选中的配件与原始数据匹配');
			// } else {
			//     console.log('选中的配件与原始数据不匹配');
			// }
		},
		getAccessoryNames(accessoryIds) {
			// 根据 accessoryIds 找到 Accessorylist 中对应的 name 字段
			// 遍历 accessoryIds 数组，根据每个 id 找到 Accessorylist 中对应的 name 字段
			const accessoryNames = this.data.accessoryIds.map(id => {
				const item = this.Accessorylist.find(accessory => accessory.accessoryId === id);
				return item ? item.name : '';
			});

			// 拼接 name 字符串，过滤掉空值
			return accessoryNames.filter(name => name).join(', ');
		},

		getModelList() {

			this.$u.get(`appAdmin/getModelListByMerchantId`).then((res) => {
				if (res.code == 200) {
					this.list = res.data
				} else {
					// 处理接口返回错误的情况
				}
			}).catch(error => {
				// 处理接口请求失败的情况
			});
		},
	}
}
</script>

<style lang="scss">
.page {
	padding-bottom: 200rpx;

	.choose_part {
		position: fixed;
		top: 530rpx;
		left: 54rpx;
		z-index: 110;
		width: 644rpx;
		padding: 40rpx 48rpx;
		background: #FFFFFF;
		border-radius: 26rpx 26rpx 26rpx 26rpx;

		.part_box {
			margin-top: 40rpx;
			display: flex;
			flex-wrap: wrap;

			.part:nth-child(3n) {
				margin-right: 0;
			}

			.part {
				margin-top: 10rpx;
				position: relative;
				margin-right: 36rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				width: 160rpx;
				height: 60rpx;
				background: #F0F0F0;
				border-radius: 6rpx 6rpx 6rpx 6rpx;
				border: 1rpx solid #F0F0F0;
				font-weight: 500;
				font-size: 32rpx;

				color: #3D3D3D;

				image {
					position: absolute;
					right: 0;
					bottom: 0;
					width: 34rpx;
					height: 34rpx;
				}
			}

			.act {
				background: #DCEDFF;
				border: 1rpx solid #4297F3;
				color: #4297F3;
			}
		}

		.tit {
			width: 100%;
			text-align: center;
			font-weight: 600;
			font-size: 36rpx;
			color: #3D3D3D;
		}

		.btn {
			margin-top: 60rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			width: 552rpx;
			height: 88rpx;
			background: #4C97E7;
			border-radius: 10rpx 10rpx 10rpx 10rpx;
			font-weight: 600;
			font-size: 36rpx;
			color: #FFFFFF;
		}
	}


	.btn_box {
		position: fixed;
		width: 750rpx;
		bottom: 50rpx;
		display: flex;
		flex-wrap: nowrap;
		align-content: center;
		justify-content: center;

		.btn1 {
			margin-right: 52rpx;
			display: flex;
			flex-wrap: nowrap;
			align-items: center;
			justify-content: center;
			width: 310rpx;
			height: 100rpx;
			background: #E2F2FF;
			font-weight: 500;
			font-size: 40rpx;
			color: #4C97E7;
		}

		.btn2 {
			display: flex;
			flex-wrap: nowrap;
			align-items: center;
			justify-content: center;
			width: 310rpx;
			height: 100rpx;
			background: #4C97E7;
			font-weight: 500;
			font-size: 40rpx;
			color: #FFFFFF;
		}
	}

	.card {
		padding: 0 24rpx;
		margin: 0 auto;
		margin-top: 24rpx;
		width: 672rpx;
		background: #FFFFFF;
		box-shadow: 0rpx 4rpx 22rpx 0rpx rgba(0, 0, 0, 0.07);
		border-radius: 10rpx 10rpx 10rpx 10rpx;

		.rule_box {
			.rule_item {
				padding: 24rpx 0;
				border-bottom: 1rpx solid #D8D8D8;

				.rule_txt {
					font-weight: 400;
					font-size: 32rpx;
					color: #3D3D3D;
				}
			}

		}

		.card_li:last-child {
			border-bottom: 1rpx solid #fff;
		}

		.card_li {
			padding-top: 24rpx;
			display: flex;
			flex-wrap: nowrap;
			align-content: center;
			justify-content: space-between;
			border-bottom: 1rpx solid #D8D8D8;
			padding-bottom: 18rpx;

			.up_left {
				.txt1 {
					font-weight: 400;
					font-size: 30rpx;
					color: #3D3D3D;
				}

				.txt2 {
					margin-top: 16rpx;
					font-weight: 400;
					font-size: 24rpx;
					color: #3D3D3D;
				}
			}

			.up_rignt {
				width: 110rpx;
				height: 110rpx;
                position: relative;

				image {
					width: 110rpx;
					height: 110rpx;
				}

				.close {
					background: #FFFFFF;
					position: absolute;
					right: -10rpx;
					top: -10rpx;
					width: 25rpx;
					height: 25rpx;
				}
			}

			.card_left {
				font-weight: 400;
				font-size: 30rpx;
				color: #3D3D3D;
			}

			.card_right {
				display: flex;
				flex-wrap: nowrap;
				align-items: center;

				span {
					font-weight: 400;
					font-size: 30rpx;
					color: #3D3D3D;
				}

				.input {
					text-align: right;
					/* 输入框内容靠右显示 */
				}
			}
		}


	}
}
</style>