<template>
	<view class="container">
		<cu-custom class="main-totextbar bg-main-oil" :isBack="true" bgColor="bg-main-oil">
			<block slot="backText">返回</block>
			<block slot="content">编辑商品</block>
		</cu-custom>
		<view id="chooseType" :class="currentBoxId == 'chooseType' ? 'show' : 'hidden'">
			<uni-forms ref="productForm" :modelValue="productDate" :rules="rules" label-width="200rpx">
				<uni-forms-item label="商品分类:" name="demandRegion">
					<mulpicker v-model="productDate.demandRegion" :list="productList" rangekey="categoryName" code="id"
						pidkey="id" childkey="classificationTwoList" :emitPath="true" :level="2"
						:placeholder="'选择商品分类'" />
					<uni-icons color="#666666" type="right" size="22"
						style="position: absolute;right: 0;top: 10rpx;"></uni-icons>
				</uni-forms-item>
				<uni-forms-item label="商品名称:" name="productName">
					<input type="text" v-model="productDate.productName" placeholder="请输入商品名称" />
				</uni-forms-item>
				<uni-forms-item label="关键词:" name="keyword">
					<input type="text" v-model="productDate.keyword" placeholder="请输入关键词(空格分隔)" />
				</uni-forms-item>
				<uni-forms-item label="商品品牌:" name="brandId">
					<!-- <input type="text" v-model="productDate.brandId" placeholder="请输入商品品牌" /> -->
					<uni-data-select v-model="productDate.brandId" :localdata="brandIdList"
						placeholder="请选择商品品牌"></uni-data-select>
				</uni-forms-item>
				<uni-forms-item label="商品售价:" name="price">
					<input type="text" v-model="productDate.price" placeholder="请输入商品售价" />
				</uni-forms-item>
				<uni-forms-item label="商品上架:" name="productStatus">
					<switch v-model="productDate.productStatus" :checked="productDate.productStatus=='1'"
						color="#FE0606" @change="switchChange" style="transform:scale(0.7)" />
				</uni-forms-item>
				<uni-forms-item label="商品推荐:" name="age">
					<view class='checkbox-con'>
						<radio-group>
							<label :class="item.checked?'checkbox checked':'checkbox'" @click="checkbox(index)"
								v-for="(item, index) in radioItem" :key="item.value">
								<checkbox :value="item.value" :checked="item.checked" />{{item.name}}
							</label>
						</radio-group>
					</view>
				</uni-forms-item>
			</uni-forms>
			<view class="buttons">
				<view @click="closed">取消</view>
				<view id="next" @click="changeBox">下一步</view>
			</view>
		</view>


		<view id="instruction" :class="currentBoxId == 'instruction' ? 'show' : 'hidden'">
			<uni-forms :modelValue="productDate" label-width="200rpx">
				<uni-forms-item label="选择规格:">
					<uni-data-select v-model="productDate.attributesTypeId" :localdata="attributesTypeList"
						placeholder="请选择规格" @change="attributesData"></uni-data-select>
				</uni-forms-item>
				<view class="content" v-show="productDate.attributesTypeId">
					<view style="margin: 10rpx 0;">商品规格：</view>
					<view>
						<uni-section type="line">
							<view class="uni-px-5" v-for="(item,index) in attributesList">
								<view style="display: inline-block;">{{item.attributeName}}：</view>
								<view style="display: inline-block;">
									<uni-data-checkbox mode="tag" @change="changeCheckBox(item,index)" multiple
										v-model="item.checkboxAttributes"
										:localdata="item.attributesList"></uni-data-checkbox>
								</view>

							</view>
						</uni-section>
					</view>
				</view>
				<view style="padding-bottom: 20rpx;border-bottom: 1rpx solid #f6f6f6;">
					<view>批量填充：<text style="color: #999999;margin: 10rpx 0;">批量填充填入信息后，可以批量将内容填写到SKU 信息里</text></view>
					<view style="display: inline-block;position: relative;" v-for="item in bottonList">
						<view class="tagButton">
							<input type="text" v-model="item.marketPrice" placeholder="市场价格" />
						</view>
						<view class="tagButton">
							<input type="text" v-model="item.sellPrice" placeholder="销售价格" />
						</view>
						<view class="tagButton">
							<input type="text" v-model="item.stock" placeholder="库存数量" />
						</view>
						<view class="tagButton">
							<input type="text" v-model="item.integral" placeholder="积分价值" />
						</view>
						<view class="redButton" @tap="addStockList">确定</view>
					</view>


				</view>
				<view style="padding: 20rpx 0;;border-bottom: 1rpx solid #f6f6f6;" v-for="(tab,index) in stockList"
					:key="index">
					<view style="margin: 10rpx 0;">
						<text style="color: red;">*</text>
						<text>规格：</text>
						<text v-for="(value,key,index) in JSON.parse(tab.attributeJson)">
							<text v-if="index==0">{{value}}</text>
							<text v-else> + {{value}}</text>
						</text>
					</view>
					<view class="tagButton">
						<input type="text" v-model="tab.marketPrice" placeholder="市场价格" />
					</view>
					<view class="tagButton">
						<input type="text" v-model="tab.sellPrice" placeholder="销售价格" />
					</view>
					<view class="tagButton">
						<input type="text" v-model="tab.stock" placeholder="库存数量" />
					</view>
					<view class="tagButton">
						<input type="text" v-model="tab.integral" placeholder="积分价值" />
					</view>
					<view style="display: inline-block;vertical-align: top;margin-top: 10rpx;"
						@click="deleteCheckAll(index)">删除</view>
				</view>
				<view>
					<view style="margin: 10rpx 0;">
						<text style="color: red;">*</text>
						商品图片：
						<text style="color: #999999;">最多可上传10张图片</text>
					</view>
					<view class="imageList" v-for="(items,index) in productDate.images">
						<view class="imageBlack" v-if="items.mainMark==1">
							<image :src="items.url"></image>
							<view class="cameraText">商品主图</view>
							<uni-icons class="cameraClear" type="clear" size="20" @tap="clearImage(index)"></uni-icons>
						</view>
						<view class="imageBlack" v-else-if="items.mainMark!=1">
							<image :src="items.url"></image>
							<view class="cameraText" @click="setMainImage(items,index)">设为主图</view>
							<uni-icons class="cameraClear" type="clear" size="20" @tap="clearImage(index)"></uni-icons>
						</view>
					</view>
					<view class="imageBlack" style="background-color: #fafafa;" @tap="srcFileImage">
						<view style="margin-top: 46rpx;">
							<uni-icons type="camera-filled" size="30"></uni-icons>
						</view>
					</view>

				</view>
			</uni-forms>
			<view class="buttons">
				<view id="previous" @click="changeBox">上一步</view>
				<view @click="addCompleted">完成</view>
			</view>
		</view>




	</view>
</template>

<script>
	import utils from '@/utils/encode'
	import serve from '@/api/packageIntegral/productList.js'
	import mulpicker from '@/packageIntegral/components/mulpicker.vue'
	export default {
		components: {
			mulpicker
		},
		data() {
			return {
				currentBoxId: 'chooseType', //当前显示的view的id
				isBoxShow: false,
				productDate: {
					productStatus: '1',
					images: []
				},
				productList: [],
				brandIdList: [],
				radioItem: [{
					name: '新品',
					checked: true
				}, {
					name: '推荐',
					checked: false
				}],
				rules: {
					demandRegion: {
						rules: [{
							required: true,
							errorMessage: '请选择商品分类'
						}]
					},
					productName: {
						rules: [{
							required: true,
							errorMessage: '请输入商品名称'
						}]
					},
					brandId: {
						rules: [{
							required: true,
							errorMessage: '请选择商品品牌'
						}]
					},
					price: {
						rules: [{
							required: true,
							errorMessage: '请输入商品售价'
						}]
					},
				},
				attributesTypeList: [],
				attributesList: [],
				bottonList: [{
					marketPrice: '',
					sellPrice: '',
					stock: '',
					integral: ''
				}],

				stockList: [],
				checkedList: []
			}
		},

		onLoad(options) {
			this.getEdit(options)
			this.classfication()
			this.getProductBrands()
			this.getAttributesType()
		},
		watch: {
			'productDate.demandRegion'(val) {
				if (val) {
					this.productDate.categoryOneId = val.split(',')[0]
					this.productDate.categoryTwoId = val.split(',')[1]
				}
			},
			'productDate.attributesTypeId'(val) {
				if (!val) {
					this.stockList = []
				}
			}
		},
		methods: {
			getEdit(options) {
				serve.getEdit(options.id).then(res => {
					if (res.code === 20000 && res.data != null) {
						this.productDate = res.data
						this.productDate.demandRegion = res.data.categoryOneId + ',' + res.data.categoryTwoId
						if (this.productDate.newMark == '1') {
							this.radioItem[0].checked = true
						} else {
							this.radioItem[0].checked = false
						}
						if (this.productDate.recommend == '1') {
							this.radioItem[1].checked = true
						} else {
							this.radioItem[1].checked = false
						}
						this.attributesTypeList.forEach(tabs => {
							if (tabs.value == this.productDate.attributesTypeId) {
								this.attributesList = tabs.attributesList
								this.attributesList.forEach(tab => {
									tab.attributesList = []
									tab.checkboxAttributes = []
									tab.attributeContent.split(',').forEach(item => {
										tab.attributesList.push({
											value: item,
											text: item
										})
									})
								})
							}
						})
						this.checkedList = this.productDate.checkedList
						this.productDate.checkedList.forEach((tab, index) => {
							this.attributesList[index].checkboxAttributes = tab.checked.split(',')
						})
						this.stockList = this.productDate.stockList


					}
				})
			},
			switchChange(e) {
				if (e.detail.value == true) {
					this.productDate.productStatus = '1'
				} else if (e.detail.value == false) {
					this.productDate.productStatus = '2'
				}
			},
			classfication() {
				serve.classification().then(res => {
					this.productList = res.data
				})
			},
			getProductBrands() {
				this.brandIdList = []
				serve.getProductBrands().then(res => {
					res.data.forEach(tab => {
						this.brandIdList.push({
							value: tab.id,
							text: tab.brandName
						})
					})

				})
			},
			checkbox(e) {
				var index = e; //获取当前点击的下标
				var checkboxArr = this.radioItem; //选项集合
				if (checkboxArr[index].checked) return; //如果点击的当前已选中则返回
				checkboxArr.forEach(item => {
					item.checked = false
				})
				checkboxArr[index].checked = true; //改变当前选中的checked值

				if (checkboxArr[0].checked == true) {
					this.productDate.newMark = 1
				} else {
					this.productDate.newMark = 2
				}
				if (checkboxArr[1].checked == true) {
					this.productDate.recommend = 1
				} else {
					this.productDate.recommend = 2
				}

			},
			changeBox(e) {
				let currentFlag = e.currentTarget.id;
				if (currentFlag == 'next') {
					this.$refs.productForm.validate().then(res => {
						if (this.isNumber(this.productDate.price) == false) {
							uni.showToast({
								title: '商品售价请输入数字',
								icon: 'none'
							})
							return
						}
						switch (currentFlag) {
							case 'next':
								this.currentBoxId = 'instruction'
								break;
							case 'previous':
								this.currentBoxId = 'chooseType'
								break;
							default:
								this.currentBoxId = 'viewInstruction'
								break;
						}
						if (currentFlag == 'next') {
							this.getAttributesType()
						}
					}).catch(err => {})
				} else {
					switch (currentFlag) {
						case 'next':
							this.currentBoxId = 'instruction'
							break;
						case 'previous':
							this.currentBoxId = 'chooseType'
							break;
						default:
							this.currentBoxId = 'viewInstruction'
							break;
					}
				}

			},
			getAttributesType() {
				this.attributesTypeList = []
				serve.getAttributesType().then(res => {
					res.data.forEach(tab => {
						this.attributesTypeList.push({
							value: tab.id,
							text: tab.name,
							number: tab.number,
							attributesList: tab.attributesList
						})
					})
				})
			},
			attributesData() {
				this.bottonList = [{
					marketPrice: '',
					sellPrice: '',
					stock: '',
					integral: ''
				}]
				this.stockList = []
				if (this.productDate.attributesTypeId) {
					this.attributesTypeList.forEach(tab => {
						if (tab.value == this.productDate.attributesTypeId) {
							this.attributesList = tab.attributesList
							this.attributesList.forEach(tab => {
								tab.attributesList = []
								tab.checkboxAttributes = []
								tab.attributeContent.split(',').forEach(item => {
									tab.attributesList.push({
										value: item,
										text: item
									})
								})
							})

						}
					})
				} else {
					this.attributesList = []
				}

			},
			changeCheckBox(item, index) {
				if (this.checkedList.length < index + 1) {
					this.checkedList.push({
						attributeId: item.id,
						checked: item.checkboxAttributes[index]
					})
				} else {
					let checked = []
					item.checkboxAttributes.forEach(tab => {
						checked.push(tab)
					})
					this.checkedList[index].checked = checked.join(',')
				}
				let arrays = []
				this.attributesList.forEach(tab => {
					arrays.push(tab.checkboxAttributes)
				})
				let arrList = this.combineArrays(arrays)
				this.stockCheck(arrList)

			},
			combineArrays(arr) {
				if (arr.length === 0) {
					return [];
				} else if (arr.length === 1) {
					return arr[0];
				} else if (arr.length === 2 && JSON.stringify(arr[1]) == '[]') {
					let result = [];
					arr[0].forEach(tab => {
						result.push([tab])
					})
					return result;
				} else {
					let result = [];
					let subCombinations = this.combineArrays(arr.slice(1));
					for (let elem of arr[0]) {
						if (Array.isArray(subCombinations)) {
							for (let subComb of subCombinations) {
								result.push([elem].concat(subComb));
							}
						} else {
							result.push([elem, subCombinations]);
						}
					}
					return result;
				}
			},
			stockCheck(arrList) {
				this.stockList = []
				let obj = {
					marketPrice: '',
					sellPrice: '',
					stock: '',
					integral: ''
				}
				arrList.forEach(tab => {
					let data = {}
					let tabName = ''
					let tabValue = ''
					tab.forEach((item, i) => {
						tabName = this.attributesList[i].attributeName
						tabValue = item
						data[tabName] = tabValue
					})
					obj.attributeJson = JSON.stringify(data)
					let stockObj = JSON.parse(JSON.stringify(obj))
					this.stockList.push(stockObj)
				})
			},
			deleteCheckAll(i) {
				this.stockList.splice(i, 1)
			},
			addStockList() {
				this.stockList.forEach(tab => {
					tab.marketPrice = this.bottonList[0].marketPrice
					tab.sellPrice = this.bottonList[0].sellPrice
					tab.stock = this.bottonList[0].stock
					tab.integral = this.bottonList[0].integral
				})
			},
			//调起上传图片
			srcFileImage() {
				let _that = this
				let imageUrl = ''
				uni.chooseImage({
					count: 10, //默认9
					sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: function(res) {
						const JSESSIONID = utils.uuid()
						uni.uploadFile({
							url: 'http://uat.xingoil.com/adminapi/oil-oss/obejct/uploadFile',
							filePath: res.tempFilePaths[0],
							formData: {
								ossKey: 'xingyou',
								pathKey: 'publicxingyou',
								encrypt: 'PUBLIC',
							},
							name: 'file',
							header: {
								"Content-Type": "multipart/form-data",
								"Authorization": uni.getStorageSync('Authorization'),
								'dataSources': 'MP',
								"imei": uni.getStorageSync('unionid'),
								"openId": uni.getStorageSync('openid'),
								'JSESSIONID': JSESSIONID,
								'token': utils.md5Salt(JSESSIONID)
							},
							success(e) {
								let obj = JSON.parse(e.data),
									imageUrl = obj.data.publicUrl
								_that.getImage(imageUrl)
							},
							fail(err) {}
						})
					},
					fail(err) {
						console.log('相机调用失败', err)
					}
				})
			},
			getImage(imageUrl) {
				if (this.productDate.images.length < 10) {
					if (JSON.stringify(this.productDate.images) == '[]') {
						this.productDate.images.push({
							url: imageUrl,
							mainMark: 1
						})
					} else {
						this.productDate.images.push({
							url: imageUrl,
							mainMark: ''
						})
					}
				} else {
					uni.showToast({
						title: '最多只能上传十张图片~',
						icon: 'none'
					})
				}
			},
			setMainImage(items, index) {
				let obj = items
				obj.mainMark = 1
				this.productDate.images.splice(index, 1)
				this.productDate.images.forEach((tab, i) => {
					tab.mainMark = ''
				})

				this.productDate.images.unshift(obj)
			},
			clearImage(index) {
				if (this.productDate.images[index].mainMark == 1) {
					this.productDate.images.splice(index, 1)
					this.productDate.images[0].mainMark = 1
				} else {
					this.productDate.images.splice(index, 1)
				}
			},
			closed() {
				uni.navigateBack()
			},
			isNumber(value) {
				return /^[0-9]+$/.test(value);
			},
			addCompleted() {
				if (this.radioItem[0].checked = true) {
					this.productDate.newMark == 1
				} else {
					this.productDate.newMark == 2
				}
				if (this.radioItem[1].checked = true) {
					this.productDate.recommend == 1
				} else {
					this.productDate.recommend == 2
				}
				this.attributesList.forEach(tab => {
					if (JSON.stringify(tab.checkboxAttributes) == '[]') {
						uni.showToast({
							title: '请选择商品规格',
							icon: 'none'
						})
						throw Error(`请选择商品规格！`)
					}
				})
				if (!this.productDate.attributesTypeId) {
					uni.showToast({
						title: '请选择规格',
						icon: 'none'
					})
					return
				}
				if (JSON.stringify(this.stockList.length) == '[]') {
					uni.showToast({
						title: '请选择商品规格',
						icon: 'none'
					})
					return
				} else {
					this.stockList.forEach(tab => {
						if (!tab.marketPrice) {
							uni.showToast({
								title: '市场价格必填！',
								icon: 'none'
							})
							throw Error(`市场价格必填！`)
						} else {
							if (this.isNumber(tab.marketPrice) == false) {
								uni.showToast({
									title: '市场价格不是数字！',
									icon: 'none'
								})
								throw Error(`市场价格不是数字！`)
							}
						}
						if (!tab.sellPrice) {
							uni.showToast({
								title: '销售价格必填！',
								icon: 'none'
							})
							throw Error(`销售价格必填！`)
						} else {
							if (this.isNumber(tab.sellPrice) == false) {
								uni.showToast({
									title: '销售价格不是数字！',
									icon: 'none'
								})
								throw Error(`销售价格不是数字！`)
							}
						}
						if (!tab.stock) {
							uni.showToast({
								title: '库存数量必填！',
								icon: 'none'
							})
							throw Error(`库存数量必填！`)
						} else {
							if (this.isNumber(tab.stock) == false) {
								uni.showToast({
									title: '库存数量不是数字！',
									icon: 'none'
								})
								throw Error(`库存数量不是数字！`)
							}
						}
						if (!tab.integral) {
							uni.showToast({
								title: '积分价值必填！',
								icon: 'none'
							})
							throw Error(`积分价值必填！`)
						} else {
							if (this.isNumber(tab.integral) == false) {
								uni.showToast({
									title: '积分价值不是数字！',
									icon: 'none'
								})
								throw Error(`积分价值不是数字！`)
							}
						}
					})
				}
				if (JSON.stringify(this.productDate.images) == '[]') {
					uni.showToast({
						title: '请上传商品图片',
						icon: 'none'
					})
					return
				}
				this.productDate.checkedList = this.checkedList
				this.productDate.stockList = this.stockList
				serve.updateProduct(this.productDate).then(res => {
					uni.showToast({
						title: res.msg,
						icon: 'none'
					})
					wx.navigateBack({
						url: `../productList/index`
					})
				})
			}
		}
	}
</script>

<style lang="scss" scoped>
	.fadeBox {
		width: 100%;
		margin-bottom: 20rpx;
	}

	#chooseType {
		padding: 30rpx;

		mulpicker {
			height: 72rpx;
			line-height: 72rpx;
		}

		/deep/ .uni-forms {
			width: 100%;
		}

		.content {
			font-size: 28rpx;
			font-weight: bold;
		}


		/deep/ .uni-forms-item {
			width: 100%;
		}

		/deep/ .uni-forms-item__label {
			color: #333 !important;
			font-size: 30rpx;
			font-weight: 700;
		}

		/deep/ .uni-forms-item__content {
			width: 100%;

			input {
				height: 72rpx;
				line-height: 72rpx;
			}
		}

		switch {
			margin-top: 9rpx;
		}

		switch::before {
			content: '';
		}

		switch::after {
			content: '';
		}
	}

	#instruction {
		padding: 30rpx;

		mulpicker {
			height: 72rpx;
			line-height: 72rpx;
		}

		/deep/ .uni-forms {
			width: 100%;
		}

		/deep/ .uni-forms-item {
			width: 100%;
		}

		/deep/ .uni-forms-item__label {
			color: #333 !important;
			font-size: 30rpx;
			font-weight: 700;
		}

		/deep/ .uni-forms-item__content {
			width: 100%;

			input {
				height: 72rpx;
				line-height: 72rpx;
			}
		}

		.tagButton {
			display: inline-block;
			width: 133rpx;
			background: #f5f5f5;
			color: #666666;
			border-radius: 8rpx;
			line-height: 58rpx;
			text-align: center;
			margin: 8rpx;

			input {
				height: 58rpx;
			}
		}

		.checkedTag {
			background-color: #2979ff;
			color: #FFFFFF;
		}

		.redButton {
			position: absolute;
			right: -84rpx;
			top: 10rpx;
			display: inline-block;
			width: 84rpx;
			height: 58rpx;
			background: red;
			color: #fff;
			border-radius: 10rpx;
			line-height: 58rpx;
			text-align: center;
		}

		.commodityImage {
			display: inline-block;
			max-width: calc(100%-150rpx);
		}

		.imageList {
			display: inline-block;
			width: 140rpx;
			margin: 0 10rpx;
		}

		.imageBlack {
			display: inline-block;
			width: 140rpx;
			height: 140rpx;
			vertical-align: middle;
			text-align: center;
			position: relative;

			>image {
				width: 100%;
				height: 100%;
			}

			.cameraText {
				width: 140rpx;
				height: 30rpx;
				text-align: center;
				line-height: 30rpx;
				position: absolute;
				background-color: #333;
				opacity: 0.3;
				color: #FFFFFF;
				left: 0rpx;
				top: 110rpx;
			}

			.cameraClear {
				position: absolute;
				left: 120rpx;
				top: -10rpx;
				z-index: 20;
			}
		}

	}

	.checkbox-con {
		margin-top: 40rpx;
		text-align: center;
		position: relative;
	}

	.checkbox {
		width: 180rpx;
		height: 76rpx;
		line-height: 76rpx;
		font-size: 30rpx;
		color: #666666;
		border: 1rpx solid #B6B6B6;
		border-radius: 5rpx;
		display: inline-block;
		margin: 0 10rpx 20rpx 0;
		position: absolute;
		top: 50rpx;

		&:nth-of-type(1) {
			left: -190rpx;
		}

		&:nth-of-type(2) {
			left: 50rpx;
		}
	}

	.checked {
		color: #FFFFFF;
		background: #FE0606;
		border: 1rpx solid #FE0606;
	}

	.checkbox checkbox {
		display: none
	}




	.buttons {
		width: 100%;
		display: flex;
		justify-content: space-evenly;
		margin-top: 180rpx;

		>view {
			width: 250rpx;
			height: 76rpx;
			text-align: center;
			line-height: 76rpx;
			border-radius: 10rpx;
			font-size: 28rpx;

			&:nth-of-type(1) {
				background: #FFFFFF;
				border: 1rpx solid #B6B6B6;
				color: #333;
			}

			&:nth-of-type(2) {
				background: #FE0505;
				color: #fff;
			}
		}
	}

	.show {
		display: flex;
		flex-wrap: wrap;
	}

	.hidden {
		display: none;
	}
</style>