<template>
	<view class="vipInfo">
		<view class="msg">
			<text>价格区间(元)</text>
			<text>{{type==0?'会员':'分销'}}加价率%</text>
			<text>利润空间(元）</text>
		</view>
		<view class="classifyContainer">
			<view class="category">
				<view class="rangeHandle" @click="addCatego(list.length)">
					<view class="addFlag">+</view>
					<text>新增分类模板</text>
				</view>
				<view class="rangeHandle" @click="delCatego('',1)" style="border-left:1px solid #E2E2E2;">
					<view class="delBtn">-</view>
					<text>删除分类模板</text>
				</view>
			</view>
			<view class="classifyItem" v-for="(item,index_1) in list" :key="index_1">
				<view class="classTitle">
					<view class="category_box" @click="onCategory(item.category,index_1)">
						<text class="maxWith">{{item.category_name?item.category_name:'请选择分类'}}</text>
						<u-icon name="arrow-right" color="#292929" size="28"></u-icon>
					</view>
					<view class="category" style="padding: 0;">
						<view class="rangeHandle" v-if="list.length>1" @click="delCatego(index_1,2)">
							<view class="delBtn">-</view>
							<text>删除分类</text>
						</view>
					</view>
				</view>
				<view class="priceRange">
					<view class="rangeItem" v-for="(val,index_2) in item.price_list" :key="index_2">
						<view class="rangeInput" @click="setUp(index_1,index_2)">
							<text v-if="val. min>=0 && val.max>0 ">
								<text>{{val. min}}</text> - <text>{{val.max}}</text>
							</text>
							<text v-else style="color: #8F8F8F;">请设置</text>
						</view>
						<view class="rangeInput fix">
							<input type="text" style="border: none;line-height:70rpx;height: 70rpx;"
								@input="onRate($event,index_1,index_2)" placeholder="请设置"
								v-model="val.add_price_rate" />
						</view>
						<view class="profit">
							<text>{{val.startProfit}}</text> - <text>{{val.endProfit}}</text>
						</view>

					</view>
				</view>
				<view class="rangeBtn">
					<view class="rangeHandle" @click="addHandle(index_1)">
						<view class="addFlag">+</view>
						<text>新增价格区间</text>
					</view>
					<view class="rangeHandle" @click="delHandle(item)" style="border-left:1px solid #E2E2E2;">
						<view class="delBtn">-</view>
						<text>删除价格区间</text>
					</view>
				</view>
			</view>
			<view class="price_rat" v-if="type==0">
				<view class="price_set">
					<view class="price_txt">
						<text>最低利润：</text><input type="text" @input="onSetRate" :min="5"
							style="border: none;height: 60rpx;border-bottom: 1rpx solid #E6E6E6;padding-left: 10rpx;"
							placeholder="请输入最低利润" v-model="min_profit" /><text
							style="position: absolute;right: 10rpx;">元</text>
					</view>
					<view class="price_bnt" @click="onSubmitProfit" :style="{'opacity': min_profit?1:0.6 }">
						确认
					</view>
				</view>
				<view class="ruleText" v-if="type==0">
					说明：低于最低利润的商品不展示在商城里。
				</view>
			</view>
		</view>
		<view class="price-fd">
			<view class="btn" @click="onSubmit">提交</view>
		</view>
		<setRange ref="setRange" @getprice="getprice"></setRange>
		<category ref="category" :tabList='categoryList' @getChoseCategory="getChoseCategory"
			:activeIndex='activeIndex'></category>
	</view>
</template>

<script>
	import * as newFunApi from '@/api/newFun'
	import setRange from './components/setRange.vue'
	import category from './components/category.vue'
	export default {
		components: {
			setRange,
			category
		},
		data() {
			return {
				activeIndex: [],
				categoryIndex: '',
				index_1: '',
				index_2: '',
				list: [],
				categoryList: '',
				type: '',
				min_profit: null
			}
		},
		onLoad(op) {
			uni.setNavigationBarTitle({
				title: op.type == 0 ? '会员价' : '分销价'
			})
			this.type = op.type
			this.getCategory();
			this.getStore()

		},
		methods: {
			async onSubmitProfit() {
				if (!this.min_profit) {
					return this.$toast('请输入最低利润')
				}
				let {
					status,
					message,
					data
				} = await newFunApi.editStore({
					min_profit: this.min_profit
				});
				if (status == 200) {
					uni.showToast({
						title: "保存成功"
					})
					this.getStore()
				}
			},
			async getStore() {
				let {
					status,
					message,
					data
				} = await newFunApi.storeData();
				if (status == 200) {
					this.min_profit = data.storeInfo.min_profit || ''
				}
			},
			onSetRate(e) {
				let rate = Number(e.detail.value)
				if (5 >= rate) {
					this.min_profit = ''
					return this.$toast('最低利不能低于等于5')
				}
				this.min_profit = rate

			},
			// 获取详情
			async getInfor() {
				let {
					status,
					message,
					data
				} = await newFunApi.getStorePriceInfo({
					type: this.type
				});
				if (status == 200) {
					if (data.list.length > 0) {
						data.list.forEach((item_1, index_1) => {
							if (typeof item_1.category == 'string') {
								item_1.category = item_1.category.split(",").map(item => Number(item))
								item_1.category_name = this.findElementsById(this.categoryList, item_1
									.category).join(',');
							}
							if (typeof item_1.category == 'number') {
								item_1.category = [item_1.category]
								item_1.category_name = this.findElementsById(this.categoryList, item_1
									.category).join(',');
							}
							item_1.price_list.forEach((item_2, index_2) => {
								item_2.startProfit = Number((Number(item_2.min) * (Number(item_2
									.add_price_rate) / 100)).toFixed(2));
								item_2.endProfit = Number((Number(item_2.max) * (Number(item_2
									.add_price_rate) / 100)).toFixed(2));
							})
						})
						this.list = data.list
					} else {
						this.list = []
					}
				}
			},
			// 提交参数
			async onSubmit() {
				let that = this
				let step = 0;
				let list = this.list
				let ids = []
				list.forEach((item, index) => {
					ids = ids.concat(item.category)
					if (!item.category_name) {
						step++
						let name = "请选择第" + (index + 1) + '行分类'
						uni.showToast({
							title: name,
							duration: 3000,
							icon: 'none'
						});
						return
					}
					if (item.price_list.length > 0) {
						item.price_list.forEach((item_1, index_1) => {
							if (!item_1.min) {
								step++
								let name = "请完善" + item.category_name + "第" + (index_1 + 1) +
									'行分类的最低价格'
								uni.showToast({
									title: name,
									duration: 3000,
									icon: 'none'
								});
								return
							}
							if (!item_1.max) {
								step++
								let name = "请完善" + item.category_name + "第" + (index_1 + 1) +
									'行分类的最高价格'
								uni.showToast({
									title: name,
									duration: 3000,
									icon: 'none'
								});
								return
							}
							if (!item_1.add_price_rate) {
								step++
								let name = "请完善" + item.category_name + "第" + (index_1 + 1) +
									'行分类的会员加价率'
								uni.showToast({
									title: name,
									duration: 3000,
									icon: 'none'
								});
								return
							}

						});
					} else {
						step++
						let name = "请新增第" + (index + 1) + '行的价格区间'
						uni.showToast({
							title: name,
							duration: 3000,
							icon: 'none'
						});
						return
					}
					if (Array.isArray(item.category)) {
						item.category = item.category.join(',')
					}
				});
				if (this.hasDuplicate(ids)) {
					this.$toast('分类模板有重复设置的分类')
					return
				}
				if (step == 0) {
					list.forEach((item, index) => {
						delete item.category_name
						list.forEach((item_1, index) => {
							delete item_1.endProfit
							delete item_1.startProfit
						})
					})
					let {
						status,
						message,
						data
					} = await newFunApi.setStorePrice({
						list: list,
						type: this.type
					});
					console.log(status)
					if (status == 200) {
						uni.showToast({
							title: "保存成功",
							duration: 2000,
							icon: 'none'

						})
						setTimeout(() => {
							this.getCategory()
						}, 2000);
					}
				}
			},
			hasDuplicate(arr) {
				return new Set(arr).size !== arr.length;
			},
			// 獲取分类
			async getCategory() {
				let {
					status,
					message,
					data
				} = await newFunApi.category();
				this.categoryList = data.list
				this.list = []
				this.list.push({
					category_name: '',
					category: '',
					price_list: [],
				})
				this.getInfor()
			},
			// 计算利润率
			onRate(e, index_1, index_2) {
				let rate = Number(e.detail.value)
				if (0 > rate) {
					this.list[this.index_1].price_list[this.index_2].add_price_rate = ''
					return this.$toast('最低利率不能低于等于0%')
				}
				this.list[this.index_1].price_list[this.index_2].startProfit = Number((this.list[this.index_1].price_list[
						this
						.index_2]
					.min * (rate / 100)).toFixed(2))
				this.list[this.index_1].price_list[this.index_2].endProfit = Number((this.list[this.index_1].price_list[
						this
						.index_2]
					.max * (rate / 100)).toFixed(2))
				this.list[this.index_1].price_list[this.index_2].add_price_rate = rate
			},
			// 获取区间价格
			getprice(res) {
				this.list[this.index_1].price_list[this.index_2].min = Number(res.min)
				this.list[this.index_1].price_list[this.index_2].max = Number(res.max)
				this.$refs.setRange.afterSale = false;
			},
			// 新增价格区间
			addHandle(index_1) {
				if (this.list[index_1].price_list.length > 19) {
					return this.$toast('最多可新增20条')
				} else {
					this.list[index_1].price_list.push({
						min: null,
						max: null,
						add_price_rate: null,
						startProfit: null,
						endProfit: null
					})
					this.index_1 = index_1
					this.index_2 = this.list[index_1].price_list.length - 1;

					this.$refs.setRange.afterSale = true;
				}

			},
			// 获取当前设置的索引
			setUp(index_1, index_2) {
				this.index_1 = index_1;
				this.index_2 = index_2;
				this.$refs.setRange.afterSale = true;
			},
			// 删除区间价格
			delHandle(item) {
				if (item.price_list.length == 0) {
					return this.$toast('暂无可删除的价格区间')
				}
				item.price_list.pop()
			},
			// 对比数组中取不同的
			mergeArrays(arr1, arr2) {
				// 创建一个空数组存放结果
				let mergedArr = [];
				// 遍历第一个数组
				for (let i = 0; i < arr1.length; i++) {
					if (!arr2.includes(arr1[i])) {
						// 如果第二个数组没有包含当前元素，则将其添加到结果数组中
						mergedArr.push(arr1[i]);
					}
				}

				// 再次遍历第二个数组
				for (let j = 0; j < arr2.length; j++) {
					if (!arr1.includes(arr2[j]) && !mergedArr.includes(arr2[j])) {
						// 如果第一个数组也没有包含该元素且结果数组中还未包含该元素，则将其添加到结果数组中
						mergedArr.push(arr2[j]);
					}
				}

				return mergedArr;
			},
			// 选择分类
			onCategory(categoryId, index) {
				if (typeof categoryId == 'string') {
					categoryId = categoryId.split(",").map(item => Number(item))
				}
				console.log(categoryId)
				this.categoryIndex = index;
				this.activeIndex = categoryId
				this.$refs.category.afterSale = true;
			},
			findElementsById(arr, ids) {
				let result = []
				arr.forEach(item => {
					if (ids.indexOf(item.category_id) > -1) {
						result.push(item.name);
					}
					if(item.children && item.children.length > 0){
						item.children.forEach(item1 => {
							if (ids.indexOf(item1.category_id) > -1) {
								result.push(item1.name);
							}
						});
					}
					
				});
				return result;
			},
			// 获取分类
			getChoseCategory(res) {
				let nameList = [];
				nameList = this.findElementsById(this.categoryList, res.category_id);
				this.list[this.categoryIndex].category_name = nameList.join(',') + (nameList.length > 0 ? '等' : '');
				this.list[this.categoryIndex].category = res.category_id;
				this.$refs.category.afterSale = false;
			},
			// 新增分类
			addCatego(index) {
				if (this.list > 19) {
					return this.$toast('暂无可新增的分类模块')
				}
				this.list.push({
					category_name: '',
					category: '',
					price_list: [],
				})
			},
			// 删除分类
			delCatego(index, type) {
				if (this.list.length == 1) {
					return this.$toast('暂无可删除的分类模块')
				}
				if (type == 1) {
					this.list.pop()
				} else {
					this.list.splice(index, 1)
				}

			},
		}
	}
</script>

<style lang="scss" scoped>
	page {
		min-height: 100%;
		padding-bottom: 60upx;
	}

	.price_rat {
		margin-top: 20rpx;
		padding: 40rpx;
		background: #fff;
	}

	.price_set {
		display: flex;
		align-items: center;
		justify-content: space-between;

		::v-deep .uni-input-wrapper {
			width: 270rpx !important;
			text-align: left !important;
			height: 70rpx !important;
			line-height: 70rpx !important;
			margin-left: 20rpx;

		}

		::v-deep uni-input {
			height: 70rpx !important;
			font-size: 28rpx;
			line-height: 70rpx !important;
			border-bottom: 1rpx solid #E6E6E6 !important;
		}


	}

	.price_bnt {
		width: 140upx;
		height: 60upx;
		background: linear-gradient(180deg, #FD5D06 0%, #F3211A 100%);
		border-radius: 20px;
		opacity: 1;
		font-size: 28upx;
		font-family: PingFang SC, PingFang SC;
		font-weight: 500;
		color: #FFFFFF;
		line-height: 60upx;
		text-align: center;
	}

	.price_txt {
		display: flex;
		align-items: center;
		position: relative;
	}

	.ruleText {
		margin-top: 20rpx;
		font-size: 28upx;
		font-family: PingFang SC, PingFang SC;
		font-weight: 400;
		color: #8B8B8B;
		line-height: 32px;

	}



	.category_box {
		display: flex;

		.maxWith {
			max-width: 400rpx;
			white-space: nowrap;
			overflow: hidden;
			text-overflow: ellipsis;
			display: block;
		}
	}

	.vipInfo {
		.msg {
			background: #FFE7E7;
			border-radius: 0px 0px 0px 0px;
			opacity: 1;
			padding: 36upx 56upx;
			display: flex;
			align-items: center;
			justify-content: space-between;

			text {

				font-size: 28upx;
				font-family: PingFang SC, PingFang SC;
				font-weight: 400;
				color: #3B3B3B;

			}
		}

		.classifyContainer {
			padding-bottom: 200rpx;

			.classifyItem {
				padding: 36upx 56upx;
				background-color: #fff;
				margin-bottom: 14upx;

				::v-deep .uni-input-wrapper {
					width: 180rpx !important;
					text-align: center !important;
					height: 70rpx !important;
					line-height: 70rpx !important;
				}

				::v-deep uni-input {
					height: 70rpx !important;
					font-size: 28rpx;
					line-height: 70rpx !important;
				}

				.classTitle {
					display: flex;
					justify-content: space-between;
					align-items: center;
					font-size: 28upx;
					font-family: PingFang SC, PingFang SC;
					font-weight: 500;
					color: #292929;

				}

				.priceRange {
					margin-top: 40upx;

					.rangeItem {
						margin: 13upx 0;
						display: flex;
					}

					.fix {
						display: flex;
					}

					.rangeInput {
						width: 180rpx;
						height: 70rpx;
						border-radius: 4rpx;
						border: 2rpx solid #DADADA;
						text-align: center;
						line-height: 66rpx;
						margin-right: 50rpx;

						text {
							;
							font-family: PingFang SC, PingFang SC;
							font-weight: 400;
							font-size: 28rpx;
							color: #3B3B3B;
							text-align: left;
							font-style: normal;
							text-transform: none;
						}
					}

					::v-deep .u-input {

						// height: 64upx;
						background: #FFFFFF;
						border-radius: 2px 2px 2px 2px;
						opacity: 1;
						border: 1px solid #DADADA;
						text-align: center !important;

					}

					.profit {
						min-width: 180rpx;
						border: none !important;
						background: transparent !important;
						line-height: 70rpx;
						text-align: center;

						::v-deep .uni-input-placeholder {
							display: none;
						}
					}
				}

				.rangeBtn {
					display: flex;
					margin-top: 30upx;
					border-top: 1px solid #E6E6E6;

					.rangeHandle {
						flex: 1;
						display: flex;
						align-items: center;
						justify-content: center;
						margin-top: 34rpx;

						.addFlag {
							width: 30upx;
							height: 30upx;
							background: #FF6551;
							border-radius: 50%;
							color: #fff;
							line-height: 26upx;
							text-align: center;
							opacity: 1;
						}

						.delBtn {
							width: 30upx;
							height: 30upx;
							line-height: 26upx;
							text-align: center;
							background: #BDBDBD;
							border-radius: 50%;
							color: #fff;
							opacity: 1;

						}

						text {

							font-size: 24upx;
							font-family: PingFang SC, PingFang SC;
							font-weight: 400;
							color: #3B3B3B;
							margin-left: 50upx;
						}
					}
				}
			}
		}
	}

	.category {
		display: flex;
		align-items: center;
		padding: 40rpx 0;

		.rangeHandle {
			flex: 1;
			display: flex;
			align-items: center;
			justify-content: center;
			margin-right: 20rpx;

			.addFlag {
				width: 30upx;
				height: 30upx;
				background: #FF6551;
				border-radius: 50%;
				color: #fff;
				line-height: 26upx;
				text-align: center;
				opacity: 1;
			}

			.delBtn {
				width: 30upx;
				height: 30upx;
				line-height: 26upx;
				text-align: center;
				background: #BDBDBD;
				border-radius: 50%;
				color: #fff;
				opacity: 1;

			}

			text {

				font-size: 24upx;
				font-family: PingFang SC, PingFang SC;
				font-weight: 400;
				color: #3B3B3B;
				margin-left: 10upx;
			}
		}
	}

	.price-fd {
		width: 100%;
		position: fixed;
		left: 0;
		bottom: 0;
		padding: 0.9375rem;
		z-index: 99;
		background-color: #fafafa;
		box-sizing: border-box;

		.btn {
			width: 630rpx;
			line-height: 88rpx;
			background: #F34A40;
			border-radius: 88rpx;
			text-align: center;
			font-size: 28rpx;
			font-weight: 500;
			color: #FFFFFF;
			margin: auto;
		}
	}
</style>
