<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="保质期">
					<u-input input-align="right" v-model="form.expireTime" />
					<view slot="right">天</view>
				</u-form-item>
				<!-- <u-form-item label="货架编码"><u-input input-align="right" v-model="form.storage" /></u-form-item> -->
				<u-form-item label="禁止销售店铺" label-position="top">
					<view class="top-value">
						<u-tag class="tag-li" v-for="(item, index) in no_sales_shop" :key="index" :text="item.name" closeable type="primary" @close="deletShop(index)" />
						<u-button size="mini" @click="selShop">
							<u-icon name="plus" margin-right="20"></u-icon>
							新增
						</u-button>
					</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)"
							/>
						</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"><editorW :html="form.description" @editInput="editInput"></editorW></view>
		</u-form>
		<view class="submit-btn"><view class="btn-min" @click="submit">提交发布</view></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>
	</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';
export default {
	components: { editorW, upload, tkiTree },
	data() {
		return {
			isEq: false,
			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: [],
			no_sales_shop: [],
			origin_unit_obj: [],
			isEditSpec: 5, // 5 表示此商品从未采购过，允许用户随意编辑单位和属性；4 表示商品已经采购过，隐藏添加属性按钮，避免skuid重组
			form: {
				delUnitIds: [], // 辅助单位删除delUnitIds (unitId)
				delSpecSkuIds: [], // 属性删除delSpecSkuIds（这个用id）
				title: '', //商品名称
				storage: '', //货架编码
				specType: 1, // 是否启用多规格 1单规格 2多规格
				specGroup: [], //多规格数据
				specMultiple: '', //多规格明细
				unitData: [], //计量单位
				describe: '', //商品卖点
				code: '', //商品code
				barCode: '', //商品条码
				weight: '', //商品重量
				categoryId: '', //分类ID
				categoryPath: '', //分类路径
				assistCategoryPath: '', //副分类
				assistCategoryId: '',
				expireTime: '', //保质期
				brandId: '', //品牌ID
				tag: [], //关键词
				description: '', //商品详情
				noSalesShop: '', //不销售店铺ID
				images: [], //商品图片
				enableStatus: 5, //是否上架
				isStore: false, //是否是商户后台上传商品
				isEq: 4, //超码商品 4否 5是
				merchantId: '', //商户ID
				salesShop: ''
			}
		};
	},
	watch: {
		brandData(val) {
			if (val.id) {
				this.form.brandId = val.id;
				this.brand_name = val.title;
			}
		},
		shopData(val) {
			if (val) {
				this.no_sales_shop = val;
			}
		}
	},
	onLoad(options) {
		if (options.id) {
			this.goods_id = options.id;
			this.getGoodsBasicInfoById();
			uni.setNavigationBarTitle({
				title: '编辑商品资料'
			});
		}

		this.getAllCategory();
		this.getAllUnit();
	},
	methods: {
		selShop() {
			let selId = '';
			if (this.no_sales_shop.length) {
				selId = JSON.stringify(this.no_sales_shop.map(item => item.id));
			}
			this.goPage('/pagesT/shop/selShop?check=1&selId=' + selId);
		},
		switchChange(val) {
			this.form.isEq = val;
			// if(this.isEditSpec !== 4 &&val){
			// 	this.form.unitData = [];
			// 	this.master_unit = '';
			// }
		},
		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;
		},
		// 获取商品详情
		getGoodsBasicInfoById() {
			this.$u.api.getGoodsBasicInfoById(this.goods_id).then(({ data }) => {
				this.isEditSpec = data.isEditSpec;
				// 备份
				this.origin_unit_obj = this.$u.deepClone(data.unitData);
				this.form = {
					title: data.title, //商品名称
					storage: data.storage, //货架编码
					specType: data.specType, // 是否启用多规格 1单规格 2多规格
					specGroup: data.specGroup, //多规格数据
					specMultiple: data.specMultiple, //多规格明细
					unitData: data.unitData, //计量单位
					describe: data.describe, //商品卖点
					code: data.code, //商品code
					barCode: data.barCode, //商品条码
					weight: data.weight, //商品重量
					categoryId: data.categoryId, //分类ID
					categoryPath: data.categoryPath, //分类路径
					expireTime: data.expireTime, //保质期
					brandId: data.brandId, //品牌ID
					tag: data.tag ? data.tag.split(',') : [], //关键词
					description: data.description, //商品详情
					noSalesShop: data.noSalesShop, //不销售店铺ID
					images: data.images, //商品图片
					enableStatus: data.enableStatus, //是否上架
					isStore: false, //是否是商户后台上传商品
					isEq: data.isEq,
					salesShop: data.salesShop,
					delUnitIds: [], // 辅助单位删除delUnitIds (unitId)
					delSpecSkuIds: [], // 属性删除delSpecSkuIds（这个用id）
					assistCategoryId: data.assistCategoryId,
					assistCategoryPath: data.assistCategoryPath
				};
				this.isEq = data.isEq === 5;
				this.no_sales_shop = data.noSalesShopNames
					? data.noSalesShopNames.split(',').map((item, index) => {
							const id = data.noSalesShop.split(',')[index];
							return {
								name: item,
								id: id
							};
					  })
					: [];
				this.category_name = data.categoryTitle;
				this.brand_name = data.brandTitle;
				const masterUnit = data.unitData.find(item => item.isMaster === 5).unitName;
				this.master_unit = masterUnit;
			});
		},
		// 辅助单位删除
		deletUnit(index, row) {
			if (!!this.goods_id) {
				this.form.delUnitIds.push(row.unitId);
			}
			this.form.unitData.splice(index, 1);
		},
		//基本单位选择
		unitConfirm(arr) {
			// 编辑页面把删除 的单位ID存储下来
			if (!!this.goods_id) {
				const unitData = this.$u.deepClone(this.origin_unit_obj);
				this.form.delUnitIds = unitData.map(item => item.unitId);
				if (this.form.specType === 1) {
					const specMultiple = this.$u.deepClone(this.form.specMultiple);
					this.form.delSpecSkuIds = specMultiple.map(item => item.id);
				}
			}
			// 重置单位
			this.form.unitData = [];
			this.master_unit = arr[0].label;
			const unit = {
				isDefault: 4,
				isMaster: 5,
				weight: '',
				unitName: arr[0].label,
				unitId: arr[0].value,
				barCode: ''
			};
			this.form.unitData.unshift(unit);
		},
		editSku() {
			if (!this.master_unit) {
				this.$u.toast('请先选择基本单位');
				return;
			}
			if (this.form.specType === 1) {
				this.goPage('/pages/goods/sku?specType=' + this.form.specType + '&unitData=' + JSON.stringify(this.form.unitData));
			} else {
				this.goPage(
					'/pages/goods/sku?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.unit_show = false;
			this.form.unitData.push({
				unitName: this.pop_unit_obj.label,
				isMaster: 4,
				unitId: this.pop_unit_obj.value,
				conversion: this.conversion,
				weight: '',
				isDefault: 4,
				barCode: ''
			});
			this.conversion = '';
			this.pop_unit_obj = {};
		},

		// 提交发布
		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;
			}
			// 做延迟处理是为了获取富文本框中的值
			setTimeout(() => {
				if (this.no_sales_shop.length) {
					this.form.noSalesShop = this.no_sales_shop.map(item => item.id).join(',');
				}
				if (this.goods_id) {
					this.$u.api
						.editGoodsBasic(this.goods_id, {
							...this.form,
							tag: this.form.tag ? this.form.tag.join(',') : '',
							specMultiple: this.form.specType === 1 ? [] : this.form.specMultiple,
							specGroup: this.form.specType === 1 ? [] : this.form.specGroup
						})
						.then(res => {
							this.$u.toast('修改成功');
							uni.navigateBack();
						});
				} else {
					this.$u.api.addGoodsBasic({ ...this.form, tag: this.form.tag ? this.form.tag.join(',') : '' }).then(res => {
						this.$u.toast('新增成功');
						uni.navigateBack();
					});
				}
			}, 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>
