<template>
	<view class="add-goods">
		<u-form :model="form" ref="goodsForm" label-width="160">
			<view class="form-title">基本信息</view>
			<view class="form-cont">
				<u-form-item required label="商品相册" label-position="top"><upload :images="form.images" @handleRemove="imgRemove" @uploadSuccess="uploadSuccess" /></u-form-item>
				<u-form-item required label="商品名称"><u-input input-align="right" v-model="form.title" /></u-form-item>
				<u-form-item required label="商品分类">
					<view class="form-main" @click="openSel('cate_show')">
						<text v-if="category_name">{{ category_name }}</text>
						<text class="input-pl" v-else>请选择商品分类</text>
					</view>
					<view slot="right"><u-icon name="arrow-down-fill" size="24"></u-icon></view>
				</u-form-item>
				<u-form-item label="商品品牌">
					<view class="form-main" @click="goPage('/pagesT/brand/selBrand')">
						<text v-if="brand_name">{{ brand_name }}</text>
						<text class="input-pl" v-else>请选择品牌</text>
					</view>
					<view slot="right"><u-icon name="arrow-down-fill" size="24"></u-icon></view>
				</u-form-item>
				<u-form-item label="商品卖点"><u-input input-align="right" v-model="form.describe" /></u-form-item>
				<u-form-item label="抄码商品">
					<view class="form-value">
						<u-switch style="transform: translateY(14rpx);" @change="switchChange" v-model="isEq" :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="distributionChange"
							v-model="isDistribution"
							: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="enableStatusChange"
							v-model="enableStatus"
							:active-value="5"
							:inactive-value="4"
							size="40"
						></u-switch>
					</view>
				</u-form-item>
				<u-form-item label="保质期">
					<u-input input-align="right" v-model="form.expireTime" />
					<view slot="right">天</view>
				</u-form-item>
				<u-form-item label="关键词" label-position="top">
					<view class="top-value">
						<u-tag class="tag-li" v-for="(item, index) in form.tag" :key="index" :text="item" closeable type="primary" @close="deletTag(index)" />
						<u-button size="mini" @click="openSel('tag_show')">
							<u-icon name="plus" margin-right="20"></u-icon>
							新增
						</u-button>
					</view>
				</u-form-item>
			</view>
			<view class="form-title">规格明细</view>
			<view class="form-cont">
				<u-form-item required label="基本单位">
					<view class="form-main" @click="openSel('m_unit_show')">
						<text v-if="master_unit">{{ master_unit }}</text>
						<text class="input-pl" v-else>请选择基本单位</text>
					</view>
					<view slot="right"><u-icon name="arrow-down-fill" size="24"></u-icon></view>
				</u-form-item>
				<u-form-item label="辅助单位" label-position="top">
					<view class="top-value">
						<block v-for="(item, index) in form.unitData" :key="index">
							<u-tag
								class="tag-li"
								v-if="item.isMaster === 4"
								:text="'1' + item.unitName + '=' + item.conversion + master_unit"
								:closeable="isEditSpec === 5 || isEq"
								type="primary"
								@close="deletUnit(index, item.unitName)"
							/>
						</block>
						<u-button v-if="!isEq || (isEq && form.unitData.length < 1)" size="mini" @click="openSel('unit_show')">
							<u-icon name="plus" margin-right="20"></u-icon>
							新增
						</u-button>
					</view>
				</u-form-item>
				<u-form-item label="商品规格">
					<view @click="editSku" slot="right" style="font-size: 28rpx; color: #007AFF;">
						<u-icon name="edit-pen" size="28"></u-icon>
						<text style="margin-left: 10rpx;">编辑</text>
					</view>
				</u-form-item>
			</view>
			<view class="form-title">物流设置</view>
			<view class="form-cont">
				<u-form-item label="快递运费">
					<view class="form-main" @click="openSel('expressType_show')">
						<text v-if="expressType_name">{{ expressType_name }}</text>
						<text class="input-pl" v-else>请选择</text>
					</view>
					<view slot="right"><u-icon name="arrow-down-fill" size="24"></u-icon></view>
				</u-form-item>
				<u-form-item label="运费模版" v-if="form.expressType === 2">
					<view class="form-main" @click="openSel('template_show')">
						<text v-if="template_name">{{ template_name }}</text>
						<text class="input-pl" v-else>请选择</text>
					</view>
					<view slot="right"><u-icon name="arrow-down-fill" size="24"></u-icon></view>
				</u-form-item>
				<u-form-item label="统一运费" v-if="form.expressType === 3">
					<u-input input-align="right" v-model="form.expressFee" />
					<view slot="right">元</view>
				</u-form-item>
			</view>
			<view class="form-title">商品详情</view>
			<view class="form-cont"><editorW :html="form.description" @editInput="editInput"></editorW></view>
		</u-form>
		<view class="submit-btn"><u-button class="handel-btn" @click="submit" :loading="sub_load" :ripple="true" type="primary">提交发布</u-button></view>
		<u-popup v-model="tag_show" border-radius="10" mode="center">
			<view class="pop-model">
				<view class="pop-tit">新增关键词</view>
				<input :focus="true" type="text" confirm-type="done" @confirm="tagConfirm" placeholder-class="input-pl" placeholder="请输入" v-model="tag_key" />
				<u-button type="primary" size="medium" @click="tagConfirm">确定</u-button>
			</view>
		</u-popup>
		<u-popup v-model="unit_show" mode="center" border-radius="10">
			<view class="pop-model">
				<view class="pop-tit">新增辅助单位</view>
				<view class="unit-model-main">
					<text>1</text>
					<view class="sel-view" @click="openSel('fz_unit_show')">
						<text v-if="pop_unit_obj.label">{{ pop_unit_obj.label }}</text>
						<text class="input-pl" v-else>请选择</text>
					</view>
					=
					<input class="uni-num-input" type="digit" v-model="conversion" />
					<text>{{ master_unit }}</text>
				</view>
				<view class="confirm-btn" @click="unitPopConfirm">确定</view>
			</view>
		</u-popup>
		<tki-tree ref="tkitree" :selectParent="true" :range="cate_list" rangeKey="title" @confirm="cateConfirm"></tki-tree>
		<u-select v-model="m_unit_show" mode="single-column" value-name="id" label-name="unitName" :list="unit_options" @confirm="unitConfirm"></u-select>
		<u-select z-index="10080" v-model="fz_unit_show" mode="single-column" value-name="id" label-name="unitName" :list="unit_options" @confirm="unitPopSelConfirm"></u-select>
		<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>
	</view>
</template>

<script>
import editorW from '@/components/editor/editor.vue';
import upload from '@/components/qiniu/QiniuUpload.vue';
import tkiTree from '@/components/tki-tree/tki-tree.vue';
const priceDataLi = {
	conversion: 0,
	unitName: '',
	unitId: 0,
	isMaster: 5,
	enabledLadder: 0,
	salePriceAreaType: 1,
	salePrice: 0,
	ladderPrice: [],
	marketPrice: 0,
	memberPrice: '',
	setNum: 1,
	specImage: '',
	barCode: '',
	weight: ''
};
export default {
	components: { editorW, upload, tkiTree },
	data() {
		return {
			sub_load: false,
			express_list: [],
			expressType_show: false,
			template_show: false,
			expressType_name: '包邮',
			isEq: false,
			isDistribution: false,
			enableStatus: true,
			shopData: '',
			conversion: '', //辅助单位换算比例
			master_unit: '', //基本单位
			pop_unit_obj: {}, // 弹窗辅助单位
			tag_show: false, //新增关键词弹窗
			tag_key: '', // 新增关键词
			brandData: {}, //品牌数据
			brand_name: '', //品牌名称
			category_name: '', //分类名称
			unit_options: [], //计量单位
			copy_unit_options: [], //计量单位
			expressType_list: [
				{
					label: '包邮',
					value: 1
				},
				{
					label: '运费模版',
					value: 2
				},
				{
					label: '统一运费',
					value: 3
				}
			],
			unit_show: false, // 新增辅助弹窗
			cate_show: false, // 商品分类弹窗
			m_unit_show: false, // 单位弹窗
			fz_unit_show: false,
			brand_list: [],
			cate_list: [],
			isEditSpec: 5, // 5 表示此商品从未采购过，允许用户随意编辑单位和属性；4 表示商品已经采购过，隐藏添加属性按钮，避免skuid重组
			form: {
				merchantId: '',
				assistCategoryPath: [],
				assistCategoryId: '',
				delUnitIds: [],
				delSpecSkuIds: [],
				createUserName: '',
				isDistribution: '',
				isShield: '',
				deliverySupIds: '',
				expressType: '', //运费模版
				expressFee: '', // 统一运费
				showExpress: '',
				ruleId: '',
				notArea: [],
				notCustomerType: '',
				notCustomer: '',
				title: '', //商品名称
				storage: '', //货架编码
				specType: 1, // 是否启用多规格 1单规格 2多规格
				specGroup: [], //多规格数据
				specMultiple: [], //多规格明细
				unitData: [], //计量单位
				describe: '', //商品卖点
				code: '', //商品code
				barCode: '', //商品条码
				weight: '', //商品重量
				categoryId: '', //分类ID
				categoryPath: '', //分类路径
				expireTime: '', //保质期
				brandId: '', //品牌ID
				tag: [], //关键词
				description: '', //商品详情
				noSalesShop: '', //不销售店铺ID
				images: [], //商品图片
				enableStatus: 5, //是否上架
				isStore: false, //是否是商户后台上传商品
				isEq: 4 //超码商品 4否 5是
			}
		};
	},
	watch: {
		brandData(val) {
			if (val.id) {
				this.form.brandId = val.id;
				this.brand_name = val.title;
			}
		}
	},
	onLoad(options) {
		this.getAllExpressRule()
		if (options.id) {
			this.goods_id = options.id;
			this.getQuickGoodsInfo();
			uni.setNavigationBarTitle({
				title: '编辑商品'
			});
		}
		this.getAllCategory();
		this.getAllUnit();
	},
	methods: {
		//抄码商品
		switchChange(val) {
			this.form.isEq = val;
		},
		// 负库存销售
		distributionChange(val) {
			this.form.isDistribution = val;
		},
		// 是否上架
		enableStatusChange(val) {
			this.form.enableStatus = val;
		},
		templateConfirm(arr) {
			this.template_name = arr[0].label;
			this.form.ruleId = arr[0].value;
		},
		expressTypeConfirm(arr) {
			this.expressType_name = arr[0].label;
			this.form.expressType = arr[0].value;
		},
		//运费模版
		getAllExpressRule() {
			this.$u.api.getAllExpressRule().then(res => {
				this.express_list = res.data;
			});
		},
		cateConfirm(arr) {
			this.category_name = arr[0].title;
			this.form.categoryId = arr[0].id;
			if (arr[0].parents.length) {
				this.form.categoryPath = arr[0].parents.map(item => item.id).join(',') + ',' + arr[0].id;
			} else {
				this.form.categoryPath = arr[0].id;
			}
		},
		editInput(val) {
			this.form.description = val;
		},
		// 获取商品详情
		getQuickGoodsInfo() {
			this.$u.api.getQuickGoodsInfo(this.goods_id).then(res => {
				const data = res.data;
				this.category_name = data.categoryName;
				this.brand_name = data.brandName;
				this.isDistribution = data.isDistribution === 5;
				this.isEq = data.isEq === 5;
				this.enableStatus = data.enableStatus === 5;
				this.master_unit = data.unitData.find(item => item.isMaster === 5).unitName;
				const expressTypeData = this.expressType_list.find(item => item.value === data.expressType);
				this.expressType_name = expressTypeData ? expressTypeData.label : '';
				if (data.expressType === 2) {
					this.template_name = this.express_list.find(item => item.id === data.ruleId).title;
				}
				this.form = {
					basicGoodsId: data.basicGoodsId,
					merchantId: data.merchantId,
					assistCategoryPath: data.assistCategoryPath,
					assistCategoryId: data.assistCategoryId,
					delUnitIds: data.delUnitIds,
					delSpecSkuIds: data.delSpecSkuIds,
					createUserName: data.createUserName,
					isDistribution: data.isDistribution,
					isShield: data.isShield,
					deliverySupIds: data.deliverySupIds,
					expressType: data.expressType,
					expressFee: data.expressFee,
					showExpress: data.showExpress,
					ruleId: data.ruleId,
					notArea: data.notArea,
					notCustomerType: data.notCustomerType,
					notCustomer: data.notCustomer,
					title: data.title,
					storage: data.storage,
					specType: data.specType,
					specGroup: data.specGroup,
					specMultiple: data.specMultiple,
					unitData: data.unitData.map(item => {
						return {
							id: item.id,
							unitName: item.unitName,
							isMaster: item.isMaster,
							unitId: item.unitId,
							conversion: item.conversion || 0
						};
					}),
					describe: data.describe,
					code: data.code,
					barCode: data.barCode,
					weight: data.weight,
					categoryId: data.categoryId,
					categoryPath: data.categoryPath,
					expireTime: data.expireTime,
					brandId: data.brandId,
					tag: data.tag.filter(item => !!item),
					description: data.description,
					noSalesShop: data.noSalesShop,
					images: data.images,
					enableStatus: data.enableStatus,
					isStore: data.isStore,
					isEq: data.isEq
				};
				console.log(this.form);
			});
		},
		//基本单位选择
		unitConfirm(arr) {
			// 检查辅助单位是否包含当前选择的单位
			const isFu = this.form.unitData.find(item => item.unitName === arr[0].label);
			if (!!isFu) {
				this.$u.toast('基本单位不能与辅助单位用同一个');
				return;
			}

			this.master_unit = arr[0].label;
			const index = this.form.unitData.findIndex(item => item.isMaster === 5);

			const unit = {
				isMaster: 5,
				isDefault: 5,
				isNew: 5,
				specType: 1,
				barCode: '',
				weight: '',
				unitName: arr[0].label,
				unitId: arr[0].value
			};
			if (index === -1) {
				this.form.unitData.push(unit);
			} else {
				this.form.unitData[index] = {
					...this.form.unitData[index],
					...unit
				};
			}

			const skuIndex = this.form.specMultiple.findIndex(item => item.isMaster === 5);
			if (skuIndex > -1) {
				this.form.specMultiple[skuIndex].unitId = arr[0].value;
				this.form.specMultiple[skuIndex].unitName = arr[0].label;
				this.form.specMultiple[skuIndex].salePrice = {
					...this.form.specMultiple[skuIndex].salePrice,
					unitName: arr[0].label,
					unitId: arr[0].value
				};
			}
		},
		editSku() {
			if (!this.master_unit) {
				this.$u.toast('请先选择基本单位');
				return;
			}
			let obj = [];
			if (this.form.specMultiple.length) {
				obj = this.form.specMultiple;
			} else {
				obj = this.form.unitData;
			}
			// console.log(obj)
			// console.log(this.form.specType);
			// return
			if (this.form.specType === 1) {
				this.goPage('/pages/goods/SkuOneStore?specType=' + this.form.specType + '&unitData=' + JSON.stringify(obj));
			} else {
				this.goPage(
					'/pages/goods/SkuOneStore?specType=' +
						this.form.specType +
						'&unitData=' +
						JSON.stringify(this.form.unitData) +
						'&specMultiple=' +
						JSON.stringify(this.form.specMultiple) +
						'&specGroup=' +
						JSON.stringify(this.form.specGroup)
				);
			}
		},
		openSel(key) {
			if (key === 'unit_show') {
				if (!this.master_unit) {
					this.$u.toast('请先选择基本单位');
					return;
				}
			} else if (key === 'cate_show') {
				this.$refs.tkitree._show();
				return;
			} else if (key === 'm_unit_show') {
				if (this.isEditSpec === 4) {
					return;
				}
				// 抄码商品主单位只能选择KG
				if (this.isEq) {
					this.unit_options = this.copy_unit_options.filter(item => item.unitName === 'KG');
				} else {
					this.unit_options = this.$u.deepClone(this.copy_unit_options);
				}
			} else if (key === 'fz_unit_show') {
				if (this.isEq) {
					this.unit_options = this.copy_unit_options.filter(item => item.unitName === '件');
				} else {
					this.unit_options = this.$u.deepClone(this.copy_unit_options);
				}
			}
			this[key] = true;
		},
		// 新增关键词确定
		tagConfirm() {
			this.tag_show = false;
			this.form.tag.push(this.tag_key);
			this.tag_key = '';
		},
		deletTag(index) {
			this.form.tag.splice(index, 1);
		},
		deletShop(index) {
			this.no_sales_shop.splice(index, 1);
		},
		// 图片上传成功
		uploadSuccess(imgUrl) {
			this.form.images.push(imgUrl);
		},
		//移除图片
		imgRemove(arr) {
			this.form.images = arr;
		},
		//  获取所有商品分类
		getAllCategory() {
			this.$u.api
				.getAllCategory({
					enableStatus: 5
				})
				.then(res => {
					this.cate_list = res.data;
				});
		},
		reduceCate(list) {
			list.forEach(item => {
				if (!item.children) {
					item.children = [
						{
							id: '',
							title: '全部'
						}
					];
				} else {
					item.children = this.reduceCate(item.children);
				}
			});
			return list;
		},
		getAllUnit() {
			this.$u.api
				.getAllUnit({
					page: 1,
					pageSize: 99
				})
				.then(res => {
					// 备份一份单位数据
					this.copy_unit_options = this.$u.deepClone(res.data);
					this.unit_options = res.data;
				});
		},
		// 辅助单位选择
		unitPopSelConfirm(arr) {
			if (arr[0].label === this.master_unit) {
				this.$u.toast('辅助单位不能与基本单位用同一个');
				return;
			}
			const index = this.form.unitData.findIndex(item => item.unitName === arr[0].label);
			if (index > -1) {
				this.$u.toast('该单位已被选择');
				return;
			}
			this.pop_unit_obj = arr[0];
		},
		// 辅助单位确定
		unitPopConfirm() {
			if (!this.conversion) {
				this.$u.toast('请输入换算比例');
				return;
			}
			this.form.unitData.push({
				unitName: this.pop_unit_obj.label,
				isMaster: 4,
				unitId: this.pop_unit_obj.value,
				conversion: this.conversion
			});
			if (this.form.specType === 1) {
				this.form.specMultiple = this.form.unitData.map(item => {
					return {
						unitName: item.unitName,
						isMaster: item.isMaster,
						isSale: 5,
						isDefault: 4,
						unitId: item.unitId,
						conversion: item.conversion || 0,
						specImage: '',
						specGroup: [],
						salePrice: {
							unitName: item.unitName,
							isMaster: item.isMaster,
							unitId: item.unitId,
							conversion: item.conversion || 0,
							deleteStatus: 4,
							enabledLadder: 0,
							salePriceAreaType: 1,
							salePrice: 0,
							ladderPrice: [],
							marketPrice: 0,
							memberPrice: '',
							setNum: 1
						}
					};
				});
			} else {
				const skuArr = this.form.specMultiple.filter(item => item.isMaster === 5);
				const fuskuArr = skuArr.map(item => {
					return {
						unitName: this.pop_unit_obj.label,
						isMaster: 4,
						isSale: 5,
						isDefault: 4,
						unitId: this.pop_unit_obj.value,
						conversion: this.conversion,
						specImage: '',
						specGroup: item.specGroup,
						salePrice: {
							unitName: this.pop_unit_obj.label,
							isMaster: 4,
							unitId: this.pop_unit_obj.value,
							conversion: this.conversion,
							deleteStatus: 4,
							enabledLadder: 0,
							salePriceAreaType: 1,
							salePrice: 0,
							ladderPrice: [],
							marketPrice: 0,
							memberPrice: '',
							setNum: 1
						}
					};
				});
				this.form.specMultiple = this.form.specMultiple.concat(fuskuArr);
			}

			// 重置弹窗数据
			this.unit_show = false;
			this.conversion = '';
			this.pop_unit_obj = {};
		},
		deletUnit(index, unitName) {
			this.form.unitData.splice(index, 1);
			this.form.specMultiple.forEach((item, index) => {
				if (item.unitName === unitName) {
					this.form.specMultiple.splice(index, 1);
				}
			});
		},
		submit() {
			if (!this.form.images.length) {
				this.$u.toast('请至少选择一张商品图片');
				return;
			}
			if (!this.form.title) {
				this.$u.toast('请输入商品名称');
				return;
			}
			if (!this.form.categoryId) {
				this.$u.toast('请选择商品分类');
				return;
			}
			if (!this.form.unitData.length) {
				this.$u.toast('请选择基本单位');
				return;
			}
			if (!this.form.specMultiple || !this.form.specMultiple.length) {
				this.$u.toast('请编辑商品规格');
				return;
			}
			// 检查规格里面的销售价是不是为0
			let isSalePrice = true;
			for (let i in this.form.specMultiple) {
				let item = this.form.specMultiple[i];
				if (!item.salePrice.salePrice || item.salePrice.salePrice <= 0) {
					const skuName = item.specGroup.map(sku => sku.specValueName).join(';');
					this.$u.toast(`规格【${item.unitName + ';' + skuName}】的销售价必须大于0`);
					isSalePrice = false;
					break;
				}
			}
			if (!isSalePrice) {
				return;
			}
			// 编辑页面清楚ID
			this.form.specMultiple.map(item => {
				if (item.id) {
					delete item.id;
				}
				return item;
			});
			// 做延迟处理是为了获取富文本框中的值
			setTimeout(() => {
				this.sub_load = true;
				if (this.goods_id) {
					this.$u.api
						.editQuickGoods({
							...this.form,
							id: this.goods_id,
							tag: this.form.tag ? this.form.tag.join(',') : ''
						})
						.then(res => {
							this.sub_load = false;
							this.$u.toast('修改成功');
							setTimeout(() => {
								uni.navigateBack();
							}, 2000);
						})
						.catch(err => {
							this.sub_load = false;
						});
				} else {
					this.$u.api
						.addBasicAndPublishGoods({ ...this.form, tag: this.form.tag ? this.form.tag.join(',') : '' })
						.then(res => {
							this.sub_load = false;
							this.$u.toast('新增成功');
							setTimeout(() => {
								uni.navigateBack();
							}, 2000);
						})
						.catch(err => {
							this.sub_load = false;
						});
				}
			}, 200);
		}
	}
};
</script>

<style scoped lang="scss">
.add-goods {
	padding-bottom: 120rpx;
	.form-title {
		line-height: 90rpx;
		font-weight: 700;
		padding: 0 24rpx;
	}
	.form-cont {
		padding: 0 24rpx;
		background-color: #ffffff;
		.form-value {
			text-align: right;
			width: 100%;
		}
		.top-value {
			text-align: left;
			width: 100%;
		}
		.form-main {
			text-align: right;
			.input-pl {
				color: #c0c4cc;
				font-size: 28rpx;
			}
		}
	}
}
.pop-model {
	padding: 0 30rpx 20rpx;
	text-align: center;
	input {
		border: 1px solid #f5f5f5;
		line-height: 70rpx;
		height: 70rpx;
		margin-bottom: 20rpx;
	}
	.pop-tit {
		line-height: 70rpx;
	}
	.confirm-btn {
		width: 80%;
		display: block;
		background-color: $uni-color-primary;
		text-align: center;
		color: #ffffff;
		line-height: 70rpx;
		height: 70rpx;
		border-radius: 10rpx;
		margin: 0 auto;
	}
	.unit-model-main {
		margin-bottom: 30rpx;
		margin-top: 10rpx;
		width: 600rpx;
		line-height: 70rpx;
		input {
			display: inline-block;
			vertical-align: middle;
			width: 200rpx;
			margin: 0 10rpx;
		}
		.sel-view {
			margin: 0 10rpx;
			display: inline-block;
			vertical-align: middle;
			width: 200rpx;
			height: 70rpx;
			border: 1px solid #f5f5f5;
		}
	}
}
.tag-li {
	margin-right: 20rpx;
}
</style>
