<template>
	<view class="detail-view">
		<u-form label-width="150" :model="add_form" ref="uForm">
			<view class="form-model-view">
				<u-form-item required label="选择店铺" prop="shopName">
					<u-input @click="goPage('/pagesT/shop/selShop')" class="dis-input" disabled v-model="add_form.shopName" placeholder="请选择" />
					<u-icon name="arrow-right" size="24" color="#6c6c6c"></u-icon>
				</u-form-item>
				<u-form-item required label="选择商品" prop="goodsName">
					<u-input @click="selGoods" class="dis-input" disabled v-model="add_form.goodsName" placeholder="请选择" />
					<u-icon name="arrow-right" size="24" color="#6c6c6c"></u-icon>
				</u-form-item>
				<u-form-item label="上下架">
					<view class="form-value">
						<u-switch
							style="transform: translateY(14rpx);"
							@change="enableStatusChange"
							v-model="enableStatus"
							:active-value="5"
							:inactive-value="4"
							size="40"
						></u-switch>
					</view>
				</u-form-item>
				<u-form-item label="负库存销售">
					<view class="form-value">
						<u-switch
							style="transform: translateY(14rpx);"
							@change="isDistributionChange"
							v-model="isDistribution"
							:active-value="5"
							:inactive-value="4"
							size="40"
						></u-switch>
					</view>
				</u-form-item>
			</view>
			<view class="form-model-view">
				<u-form-item label="快递运费">
					<u-input @click="openSel('expressType_show')" class="dis-input" disabled v-model="expressType_name" placeholder="请选择" />
					<u-icon name="arrow-right" size="24" color="#6c6c6c"></u-icon>
				</u-form-item>
				<u-form-item label="商品服务" label-position="top">
					<u-checkbox-group>
						<u-checkbox v-model="item.checked" v-for="(item, index) in serve_list" :key="index" :name="item.id">{{ item.servicesName }}</u-checkbox>
					</u-checkbox-group>
				</u-form-item>
				<u-form-item label="运费模版" v-if="add_form.expressType === 2">
					<u-input @click="openSel('template_show')" class="dis-input" disabled v-model="template_name" placeholder="请选择" />
					<u-icon name="arrow-right" size="24" color="#6c6c6c"></u-icon>
				</u-form-item>
				<u-form-item label="统一运费" v-if="add_form.expressType === 3"><u-input v-model="add_form.expressFee" placeholder="请输入" /></u-form-item>
			</view>
			<view class="form-model-view" v-if="spec_multiple.length">
				<u-form-item label-position="top" label="价格明细">
					<view class="price-ul">
						<view class="price-li clearfix">
							<view class="price-li-in">规格明细</view>
							<view class="price-li-in">共{{ spec_multiple.length }}种规格</view>
							<view class="price-li-in" @click="openSel('price_show')" v-if="add_form.specType === 2">
								批量设置
								<u-icon name="arrow-right" size="24" color="#6c6c6c"></u-icon>
							</view>
						</view>
						<view class="price-li thead ">
							<view class="price-li-in">规格名称</view>
							<view class="price-li-in" style="color: #333333;">订货价</view>
						</view>
						<view class="price-li clearfix" v-for="(item, index) in spec_multiple" :key="index">
							<view class="price-li-in">
								{{ item.unitName }};
								<text v-for="(sku, skuI) in item.specGroup" :key="skuI">{{ sku.specValueName }}</text>
							</view>
							<view class="price-li-in" @click="openSel('price_show', item, index)">
								{{ (item.enabledLadder !== 1 && item.salePrice > 0) || item.enabledLadder === 1 ? '已设置' : '未设置' }}
								<u-icon name="arrow-right" size="24" color="#999999"></u-icon>
							</view>
						</view>
					</view>
				</u-form-item>
			</view>
		</u-form>
		<view class="submit-btn"><view class="btn-min" @click="submit">提交发布</view></view>
		<u-select v-model="expressType_show" @confirm="expressTypeConfirm" :list="expressType_list"></u-select>
		<!-- 运费模版 -->
		<u-select v-model="template_show" @confirm="templateConfirm" label-name="title" value-name="id" :list="express_list"></u-select>
		<u-popup v-model="price_show" mode="bottom" :mask-close-able="false">
			<view class="pop-ul">
				<view class="sku-name" v-if="!pop_price.unitName">批量设置</view>
				<view class="sku-name" v-else>
					{{ pop_price.unitName }};
					<text v-for="(sku, skuI) in pop_price.specGroup" :key="skuI">{{ sku.specValueName }}</text>
					<text v-if="pop_price.isMaster === 4" style="font-weight: 400;font-size: 24rpx;">
						（1{{ pop_price.unitName }}={{ Number(pop_price.conversion) }}{{ primary_unit }})
					</text>
				</view>
				<view class="pop-li clearfix">
					<view class="float_left">阶梯价</view>
					<view class="float_right">
						<u-switch
							:disabled="isEq === 5 && pop_price.isMaster === 4"
							style="transform: translateY(14rpx);"
							@change="ladderChange"
							v-model="pop_enabled_ladder"
							:active-value="1"
							:inactive-value="0"
							size="40"
						></u-switch>
					</view>
				</view>
				<view class="pop-li clearfix" v-if="pop_price.enabledLadder !== 1">
					<view class="float_left">销售价/元</view>
					<view class="float_right">
						<input
							@blur="salePriceBlur"
							:disabled="isEq === 5 && pop_price.isMaster === 4"
							input-align="right"
							placeholder="请输入"
							v-model="pop_price.salePrice"
							height="90"
							type="digit"
						/>
					</view>
				</view>
				<view class="pop-li ladder-price clearfix" v-if="pop_price.enabledLadder === 1">
					<view class="clearfix" style="padding: 10rpx 0;">
						<view class="float_left">销售价/元</view>
						<view class="float_right" v-if="pop_price.ladderPrice.length < 3"><u-button @click="addLadderprice" size="mini" type="primary">新增</u-button></view>
					</view>
					<view style="padding-bottom: 10rpx;" v-for="(ladder, ladderI) in pop_price.ladderPrice" :key="ladderI">
						<view class="input-view">
							<input disabled type="digit" v-model="ladder.from" />
							<u-tag :text="pop_price.unitName || '件'" mode="light" />
						</view>
						-
						<view class="input-view">
							<input
								:disabled="isEq === 5 && pop_price.isMaster === 4"
								@blur="ladderBlur($event, ladderI)"
								type="digit"
								v-if="ladderI !== pop_price.ladderPrice.length - 1"
								v-model="ladder.to"
							/>
							<input v-else disabled value="∞" />
							<u-tag :text="pop_price.unitName || '件'" mode="light" />
						</view>
						=
						<view class="input-view">
							<input :disabled="isEq === 5 && pop_price.isMaster === 4" type="digit" @blur="salePriceLadderBlur(ladderI)" v-model="ladder.price" />
							<u-icon
								name="shanchu"
								v-if="pop_price.ladderPrice.length > 2 && ladderI !== pop_price.ladderPrice.length - 1"
								color="#ff4501"
								custom-prefix="custom-icon"
								@click="delLadderPrice(ladderI)"
							></u-icon>
						</view>
					</view>
				</view>
				<view class="pop-li clearfix">
					<view class="float_left">会员价/元</view>
					<view class="float_right">
						<input
							:disabled="isEq === 5 && pop_price.isMaster === 4"
							input-align="right"
							placeholder="请输入"
							v-model="pop_price.memberPrice"
							height="90"
							type="digit"
						/>
					</view>
				</view>
				<view class="pop-li clearfix">
					<view class="float_left">市场价/元</view>
					<view class="float_right"><input input-align="right" placeholder="请输入" v-model="pop_price.marketPrice" height="90" type="digit" /></view>
				</view>
				<view class="pop-li clearfix">
					<view class="float_left">起订数量</view>
					<view class="float_right"><u-input input-align="right" placeholder="请输入" v-model="pop_price.setNum" height="90" type="number" /></view>
				</view>
				<view class="pop-li clearfix">
					<view class="float_left">是否销售</view>
					<view class="float_right">
						<u-switch style="transform: translateY(14rpx);" v-model="pop_price.isSale" :active-value="5" :inactive-value="4" size="40"></u-switch>
					</view>
				</view>
				<view class="btn" @click="popconfirm">确定</view>
			</view>
		</u-popup>
	</view>
</template>

<script>
export default {
	data() {
		return {
			template_show: false,
			template_name: '',
			pop_enabled_ladder: false,
			pop_price: {},
			sku_price_index: 0,
			price_show: false,
			expressType_show: false,
			expressType_list: [
				{
					value: 1,
					label: '包邮'
				},
				{
					value: 2,
					label: '运费模版'
				},
				{
					value: 3,
					label: '统一运费'
				}
			],
			shopData: '',
			goodsSel: '',
			enableStatus: true,
			isDistribution: false,
			expressType_name: '包邮',
			spec_multiple: [],
			add_form: {
				createUserName: '',
				goodsName: '',
				enableStatus: 5,
				isDistribution: 4, //负库存销售
				specType: '',
				goodsBasicId: 0, // 商品基础资料
				shopId: '', // 店铺
				shopName: '', // 店铺
				images: [], // 相册
				salesArea: [], // 销售区域
				serviceInfo: 1,
				price: [], // 区域价
				specification: [], // // 规格
				content: '', // 商品描述
				isRecommend: 5, // 5推荐 4不推荐
				sort: '1', // 排序
				deliverySupIds: '1,2', // 物流支持 固定值 1 快递 2 自提 传参格式：1,2
				expressType: 1, // 快递运费 1 包邮 2 运费模版 3 固定费用
				expressFee: '', // 固定费用
				showExpress: 5, // 是否展示快递 5展示 4不展示
				ruleId: '', // 运费模版id
				isShield: 4, // 经营屏蔽 4关闭 5开启
				notArea: [], //经营屏蔽地区
				notCustomerType: '', //经营屏蔽 客户类型屏蔽
				notCustomer: '', //经营屏蔽 客户屏蔽
				support: ''
			},
			express_list: [],
			goods_id: '',
			primary_unit: '',
			primary_unit_num: '',
			serve_list: [],
			support_list: [], // 预存商品服务数据
			isEq: 4 //是否是抄码商品
		};
	},
	computed: {
		userName() {
			return this.$store.state.userInfo.name;
		}
	},
	watch: {
		shopData(val) {
			if (val) {
				this.add_form.shopId = val.id;
				this.add_form.shopName = val.name;
			}
		},
		goodsSel(val) {
			if (val) {
				this.getGoodsBasicInfoById(val.id);
			}
		}
	},
	async onLoad(options) {
		if (options.id) {
			this.goods_id = options.id;
			uni.setNavigationBarTitle({
				title: '编辑商品'
			});
			await this.getGoodsInfo();
		}
		await this.getAllExpressRule();
		await this.getAllGoodsSupport();
	},
	methods: {
		// 商品详情
		async getGoodsInfo() {
			await this.$u.api.getGoodsInfo(this.goods_id).then(({ data }) => {
				// this.goods_detail = res.data;
				this.isEq = data.isEq;
				this.enableStatus = data.enableStatus === 5;
				this.isDistribution = data.isDistribution === 5;
				this.spec_multiple = data.specMultiple;
				this.support_list = data.support.map(item => Number(item));
				this.add_form = {
					createUserName: data.createUserName,
					goodsName: data.title,
					enableStatus: data.enableStatus,
					isDistribution: data.isDistribution, //负库存销售
					specType: data.specType,
					goodsBasicId: data.basicGoodsId, // 商品基础资料
					shopId: data.shopId, // 店铺
					shopName: data.shopName, // 店铺
					images: data.images, // 相册
					salesArea: data.salesArea, // 销售区域
					serviceInfo: data.serviceInfo,
					price: data.price, // 区域价
					specification: data.specification, // // 规格
					content: data.content, // 商品描述
					isRecommend: data.isRecommend, // 5推荐 4不推荐
					sort: data.sort, // 排序
					deliverySupIds: data.deliverySupIds, // 物流支持 固定值 1 快递 2 自提 传参格式：1,2
					expressType: data.expressType, // 快递运费 1 包邮 2 运费模版 3 固定费用
					expressFee: data.goodsName, // 固定费用
					showExpress: data.showExpress, // 是否展示快递 5展示 4不展示
					ruleId: data.ruleId, // 运费模版id
					isShield: data.isShield, // 经营屏蔽 4关闭 5开启
					notArea: data.notArea, //经营屏蔽地区
					notCustomerType: data.notCustomerType, //经营屏蔽 客户类型屏蔽
					notCustomer: data.notCustomer //经营屏蔽 客户屏蔽
				};
			});
		},
		expressTypeConfirm(arr) {
			this.expressType_name = arr[0].label;
			this.add_form.expressType = arr[0].value;
		},
		templateConfirm(arr) {
			this.template_name = arr[0].label;
			this.add_form.ruleId = arr[0].value;
		},
		openSel(key, row, index) {
			this[key] = true;
			if (key === 'price_show') {
				if (!row) {
					this.pop_enabled_ladder = false;
					this.sku_price_index = '';
					this.pop_price = {
						ladderPrice: [],
						marketPrice: '',
						memberPrice: '',
						salePrice: '',
						setNum: 1,
						isSale: true,
						enabledLadder: 0
					};
				} else {
					this.pop_enabled_ladder = row.enabledLadder === 1;
					this.sku_price_index = index;
					this.pop_price = {
						...row,
						isSale: row.isSale !== 4
					};
				}
			}
		},
		selGoods() {
			if (!this.add_form.shopId) {
				this.$u.toast('请选择店铺');
				return;
			}
			this.goPage(`/pagesT/goods/selBaseGoods?check=-1&shopId=${this.add_form.shopId}`);
		},
		//运费模版
		getAllExpressRule() {
			this.$u.api.getAllExpressRule().then(res => {
				this.express_list = res.data;
			});
		},
		getGoodsBasicInfoById(id) {
			this.$u.api
				.getGoodsBasicInfoById(id, {
					isAddGoods: 5
				})
				.then(({ data }) => {
					let arr = '';
					data.unitData.forEach(item => {
						if (item.isMaster === 5) {
							arr = item.unitName;
						}
					});
					this.primary_unit = arr;
					this.add_form.goodsName = data.title;
					this.add_form.images = data.images;
					this.add_form.specType = data.specType;
					this.add_form.content = data.description;
					this.add_form.goodsBasicId = data.id;
					if (data.specType === 1) {
						this.add_form.specification = (data.branchUnit || []).concat(data.masterUnit);
					} else if (data.specType === 2) {
						this.add_form.specification = data.specMultiple;
					}
					this.spec_multiple = data.specMultiple.map(item => {
						return {
							...item,
							ladderPrice: [],
							marketPrice: '',
							memberPrice: '',
							salePrice: '',
							salePriceAreaType: 1,
							setNum: 1,
							isSale: 5,
							enabledLadder: 0
						};
					});
				});
		},
		submit() {
			this.add_form.createUserName = this.userName;
			if (!this.add_form.shopName) {
				this.$u.toast('请选择发布商铺');
				return;
			}
			if (!this.add_form.goodsName) {
				this.$u.toast('请选择发布商品');
				return;
			}

			// 判断价格是否为0
			const isFSale = this.spec_multiple.every(item => item.isSale === 4);
			if (isFSale) {
				this.$u.toast('至少保留一条规格的销售状态为【启用】');
				return;
			}
			let isPrice = false;
			for (let i in this.spec_multiple.length) {
				let item = this.spec_multiple[i];
				if (item.enabledLadder === 1) {
					isPrice = item.ladderPrice.some(item => item.price <= 0);
				} else {
					isPrice = item.salePrice <= 0;
				}
				let skuName = '';
				if (item.specGroup && item.specGroup.length) {
					skuName = item.specGroup.map(item => item.specValueName).join(';');
				}
				if (isPrice) {
					this.$u.toast(`规格【${item.unitName};${skuName}】的价格不能为0`);
					break;
				}
			}
			if (isPrice) {
				return;
			}
			this.add_form.support = this.serve_list.filter(item => item.checked).map(item => item.id);
			this.add_form.price = this.spec_multiple;
			if (this.goods_id) {
				this.$u.api.editGoods(this.goods_id, this.add_form).then(res => {
					this.$u.toast('修改成功');
					setTimeout(() => {
						uni.navigateBack();
					}, 2000);
				});
			} else {
				this.$u.api.addGoods(this.add_form).then(res => {
					this.$u.toast('新增成功');
					setTimeout(() => {
						uni.navigateBack();
					}, 2000);
				});
			}
		},
		isDistributionChange(val) {
			this.add_form.isDistribution = val;
		},
		enableStatusChange(val) {
			this.add_form.enableStatus = val;
		},
		addLadderprice() {
			const target = this.$u.deepClone(this.pop_price);
			if (!target.ladderPrice.length) {
				target.ladderPrice.push({
					from: 1,
					price: '',
					to: 2
				});
			} else {
				const upL = target.ladderPrice[0];
				target.ladderPrice.splice(1, '', {
					from: upL.to + 1,
					price: '',
					to: upL.to + 2
				});
				if (target.ladderPrice.length === 3) {
					target.ladderPrice[target.ladderPrice.length - 1].from = upL.to + 3;
				}
			}
			this.pop_price = target;
		},
		ladderChange(val) {
			this.pop_price.enabledLadder = val;
			if (val === 1) {
				this.pop_price.ladderPrice = [
					{
						from: 1,
						price: 0,
						to: 2
					},
					{
						from: 3,
						price: 0,
						to: 4
					},
					{
						from: 5,
						price: 0,
						to: 999999999
					}
				];
			} else {
				this.pop_price.ladderPrice = [];
			}
		},
		//  价格设置
		popconfirm() {
			if (this.pop_price.enabledLadder === 1) {
				const isPrice = this.pop_price.ladderPrice.some(item => item.price <= 0);
				if (isPrice) {
					this.$u.toast('销售价不能为0');
					return;
				}
			} else {
				if (this.pop_price.salePrice <= 0) {
					this.$u.toast('销售价不能为0');
					return;
				}
			}
			let target = this.$u.deepClone(this.spec_multiple);
			if (!this.pop_price.unitName) {
				// 批量设置
				this.spec_multiple = target.map(item => {
					item = {
						...item,
						...this.pop_price,
						isSale: this.pop_price.isSale ? 5 : 4
					};
					// 根据换算关系 批量设置
					if (Number(item.conversion)) {
						item.salePrice = this.$NP.times(Number(item.conversion), this.pop_price.salePrice);
						item.marketPrice = this.$NP.times(Number(item.conversion), this.pop_price.marketPrice);
						item.memberPrice = this.$NP.times(Number(item.conversion), this.pop_price.memberPrice);
						if (this.pop_price.enabledLadder === 1) {
							item.ladderPrice = this.pop_price.ladderPrice.map(ladder => {
								return {
									...ladder,
									price: this.$NP.times(Number(item.conversion), ladder.price)
								};
							});
						}
					}
					// const salePrice = Number(item.)
					return item;
				});
			} else {
				// 抄码商品根据比例自动换算
				if (this.add_form.specType === 1 && this.pop_price.isMaster === 5) {
					target.forEach(item => {
						if (item.conversion && item.isMaster === 4) {
							item.marketPrice = this.$NP.times(this.pop_price.marketPrice, item.conversion);
							item.salePrice = this.$NP.times(this.pop_price.salePrice, item.conversion);
							item.memberPrice = this.$NP.times(this.pop_price.memberPrice, item.conversion);
							if (this.isEq === 5) {
								item.enabledLadder = this.pop_price.enabledLadder;
								item.ladderPrice = this.pop_price.ladderPrice.map(ladder => {
									return {
										...ladder,
										price: this.$NP.times(ladder.price, item.conversion)
									};
								});
							}
						}
					});
				}
				target[this.sku_price_index] = {
					...this.pop_price,
					isSale: this.pop_price.isSale ? 5 : 4
				};
				this.spec_multiple = target;
			}
			this.price_show = false;
		},
		ladderBlur(e, index) {
			let val = Number(e.detail.value);
			const target = this.$u.deepClone(this.pop_price);
			if (val <= target.ladderPrice[index].from) {
				val = target.ladderPrice[index].from + 1;
				target.ladderPrice[index].to = val;
			}
			target.ladderPrice[index + 1].from = val + 1;
			if (index === 0) {
				target.ladderPrice[index + 1].to = val + 2;
				if (target.ladderPrice[index + 2]) {
					target.ladderPrice[index + 2].from = val + 3;
				}
			}
			this.pop_price = target;
		},
		delLadderPrice(index) {
			const target = this.$u.deepClone(this.pop_price);
			target.ladderPrice.splice(index, 1);
			target.ladderPrice[0].from = 1;
			target.ladderPrice[target.ladderPrice.length - 1].from = target.ladderPrice[0].to + 1;
			this.pop_price = target;
		},
		// 销售价失去焦点
		salePriceBlur(val) {
			this.pop_price.marketPrice = this.$NP.times(this.pop_price.salePrice, 1.5);
		},
		// 阶梯价第一级失去焦点
		salePriceLadderBlur(index) {
			if (index === 0) {
				this.pop_price.marketPrice = this.$NP.times(this.pop_price.ladderPrice[0].price, 1.5);
			}
		},
		async getAllGoodsSupport() {
			await this.$u.api
				.getAllGoodsSupport({
					page: 1,
					pageSize: 99
				})
				.then(res => {
					this.serve_list = res.data.map(item => {
						return {
							...item,
							checked: this.support_list.indexOf(item.id) > -1
						};
					});
				});
		}
	}
};
</script>

<style lang="scss" scoped>
.price-ul {
	.price-li {
		width: 700rpx;
		line-height: 90rpx;
		display: flex;
		border-top: 1px solid #eeeeee;

		.price-li-in {
			flex: 2;
			text-align: center;
			color: #999999;

			&:first-child {
				text-align: left;
				color: #333333;
			}

			&:last-child {
				text-align: right;
			}
		}
	}

	.thead {
		padding-top: 30rpx;
		line-height: 60rpx;
		font-size: 24rpx;
		font-weight: bold;
	}
}

.pop-ul {
	line-height: 90rpx;

	.sku-name {
		font-weight: bold;
		padding: 0 24rpx;
	}

	.pop-li {
		padding: 0 24rpx;
		border-top: 1px solid #eeeeee;
		line-height: 90rpx;

		input {
			text-align: right;
			line-height: 90rpx;
			height: 90rpx;
			display: inline-block;
			vertical-align: middle;
		}
	}

	.ladder-price {
		line-height: 60rpx;

		.input-view {
			line-height: 60rpx;
			display: inline-block;
			width: 210rpx;
			margin: 0 6rpx;

			input {
				padding: 0 8rpx;
				display: inline-block;
				vertical-align: middle;
				width: 100rpx;
				border: 1px solid #eeeeee;
				border-radius: 10rpx;
				line-height: 60rpx;
				height: 60rpx;
				margin-right: 8rpx;
			}
		}
	}

	.btn {
		text-align: center;
		color: #ffffff;
		line-height: 90rpx;
		background-color: $uni-color-primary;
	}
}
</style>
