<template>
	<div class="container add_edit">
		<el-form label-width="150px">
			<div>
				<h3 class="margin_b_20">SKU</h3>
				<div>
					<el-form-item label="开启SKU">
						<el-switch @change="open_switch_sku" v-model="switch_sku" active-color="#ff6a6c"
							inactive-color="#dcdfe6"></el-switch>
					</el-form-item>
					<el-form-item label="编辑SKU1" v-if="switch_sku">
						<div>
							<el-checkbox @change="open_spec" class="margin_r_10" v-model="checked_spec"></el-checkbox>
							<el-input v-model="spec_s" placeholder="规格"></el-input>
						</div>
						<div class="dflex margin_t_20">
							<el-tag type="info" class="tag-new-tag" :key="idx" v-for="(tag, idx) in dynamicTags_spec"
								:closable="checked_spec" :disable-transitions="false" @close="handleClose_spec(tag)">
								{{ tag }}
							</el-tag>
							<el-input class="input-new-tag" v-if="inputVisible_spec" v-model="inputValue_spec"
								ref="saveTagInput_spec" @keyup.enter.native="handleInputConfirm_spec"
								@blur="handleInputConfirm_spec"></el-input>
							<el-button :disabled="!checked_spec" v-else class="button-new-tag" size="small"
								@click="showInput_spec">添加</el-button>
						</div>
					</el-form-item>
					<el-form-item label="编辑SKU2" v-if="switch_sku">
						<div>
							<el-checkbox @change="open_spec2" class="margin_r_10" v-model="checked_spec2"></el-checkbox>
							<el-input v-model="spec_s2" placeholder="颜色"></el-input>
						</div>
						<div class="dflex margin_t_20">
							<el-tag type="info" class="tag-new-tag" :key="idx" v-for="(tag, idx) in dynamicTags_spec2"
								:closable="checked_spec2" :disable-transitions="false" @close="handleClose_spec2(tag)">
								{{ tag }}
							</el-tag>
							<el-input class="input-new-tag" v-if="inputVisible_spec2" v-model="inputValue_spec2"
								ref="saveTagInput_spec2" @keyup.enter.native="handleInputConfirm_spec2"
								@blur="handleInputConfirm_spec2"></el-input>
							<el-button :disabled="!checked_spec2" v-else class="button-new-tag" size="small"
								@click="showInput_spec2">添加</el-button>
						</div>
					</el-form-item>
					<el-form-item v-if="switch_sku">
						<el-table :data="tableSkuData" border>
							<el-table-column label="图片" align="center">
								<template slot-scope="scope">
									<image style="width: 80px;height: 80px;" width="60%" :src="scope.row.skuImg" alt=""></image>
									<el-upload action="" list-type="picture"
			                          :on-remove="handleRemove" :on-change="handleChange"
									:http-request="
													  (file) => {
														return handleUpload(file, scope.row);
													  }
													"
			                          >
			                          <template #trigger>
			                            <view>+
											<!-- <image style="width: 80px;height: 80px;" width="60%" :src="scope.row.skuImg" alt=""></image> -->
										</view>
			                          </template>
			                        </el-upload>
									<!-- <uni-file-picker v-model="scope.row.imgs" fileMediatype="image" returnType="object"
										 @select="imgDelete" @delete="Delete" /> -->
								</template>
							</el-table-column>
							
							<el-table-column label="销售价格" align="center">
								<template slot-scope="scope">
									<el-input class="sort-container" oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')" min="0.01" v-model="scope.row.price">
									</el-input>
								</template>
							</el-table-column>
							<el-table-column label="市场价格" align="center">
								<template slot-scope="scope">
									<el-input class="sort-container" oninput="value=value.replace(/^\D*(\d*(?:\.\d{0,2})?).*$/g, '$1')" min="0.01" v-model="scope.row.marketPrice">
									</el-input>
								</template>
							</el-table-column>
							<el-table-column label="库存" align="center">
								<template slot-scope="scope">
									<el-input class="sort-container" type="number" v-model.number="scope.row.stockNum">
									</el-input>
								</template>
							</el-table-column>
							<el-table-column v-if="checked_spec" prop="spec" :label="spec_s" align="center">
							</el-table-column>
							<el-table-column v-if="checked_spec2" prop="spec2" :label="spec_s2" align="center">
							</el-table-column>
						</el-table>
					</el-form-item>
				</div>
			</div>
		</el-form>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				switch_sku: true,
				skus: [],
				goods: {},
				dynamicTags_spec: [],//规格
				dynamicTags_spec2: [],//颜色
				inputVisible_spec: false,
				inputVisible_spec2: false,
				inputValue_spec: '',
				inputValue_spec2:'',
				checked_spec: true,
				checked_spec2: true,
				spec_s: '规格',
				spec_s2: '颜色',
				tableData: [],
				tableSkuData: [],
				form:{}
			};
		},
		watch: {
			checked_spec: function(arrs) {
				for (var i = 0; i < arrs.length; i++) {
					for (var j = i + 1; j < arrs.length; j++) {
						if (arrs[i] == arrs[j]) {
							//第一个等同于第二个，splice方法删除第二个
							arrs.splice(j, 1);
							j--;
						}
					}
				}
			}
		},
		methods: {
			submitData(callback) {
				this.skus = [];
				console.log(this.tableSkuData)

				this.tableSkuData.forEach(x => {
					this.skus.push(x);
				});

				if (typeof callback === 'function') {
					callback(
						this.skus,this.switch_sku,
						JSON.stringify({
							spec_s: this.spec_s,
							spec_s2:this.spec_s2,
							spec: this.dynamicTags_spec,
							spec2:this.dynamicTags_spec2,
						})
					);
				}
			},
			getData(callback) {
				this.submitData(callback);
			},
			setData(res) {
				console.log(res,'goods')
				if(!res.skus){
					this.switch_sku=false
				}
				this.form = res;
				console.log(this.form.skuGroups,'skus')
				let skus = this.form.skuGroups
				// let skus = JSON.parse(this.form);
				console.log(skus,'skus',skus[0].attrName)
				this.spec_s = skus[0].attrName
				this.spec_s2=skus[1].attrName;

				this.tableSkuData = res.skus;
				for(var i=0;i<this.tableSkuData.length;i++){
					this.tableSkuData[i].spec=this.tableSkuData[i].saleAttrs[0].attrValue
					this.tableSkuData[i].spec2=this.tableSkuData[i].saleAttrs[1].attrValue
				}
				console.log(this.tableSkuData)

				skus[0].attrValues.forEach(data => {
					this.dynamicTags_spec.push(data.attrValue)
				})
				skus[1].attrValues.forEach(data => {
					this.dynamicTags_spec2.push(data.attrValue)
				})
				console.log(this.dynamicTags_spec)

				this.checked_spec = this.dynamicTags_spec.length > 0;
			},
			setGoods(res) {
				this.goods = res;
			},
			affirm() {
				var imgsku=''
				if(!this.form.skus){
					if(!this.goods.imgs){
						imgsku=''
					}else{
						if(this.goods.imgs.search(',')==(-1)){
							imgsku=this.goods.imgs
						}else{
							var a=this.goods.imgs.indexOf(',')
							imgsku=this.goods.imgs.substring(0, a)
						}
					}
				}else{
					imgsku=this.goods.imgs
				}
				// 规格
				this.tableSkuData=[]
					this.dynamicTags_spec.forEach((spec, spec_idx) => {
						console.log(spec_idx,'规格',spec,this.spec_s)
						// if (!this.tableSkuData.find(x => x.spec == spec)){
							if(this.dynamicTags_spec2.length>0){
								this.dynamicTags_spec2.forEach((spec2,spec_idx2) => {
									console.log(spec_idx2,'颜色',spec2)
									// if (!this.tableSkuData.find(x => x.spec2 == spec2)){
										console.log(this.goods.imgs)
										console.log(this.goods.price)
										console.log('p')
											this.tableSkuData.push({
												skuId:'',
												skuName: spec+'+'+spec2,
												skuDesc: '',
												skuImg:imgsku,
												price: this.goods.price,
												marketPrice:this.goods.marketPrice,
												stockNum: this.goods.stockNum,
												spec: spec,
												spec_s: spec_idx,
												spec2:spec2,
												spec_s2: spec_idx,
												state:'1',
												// shuxing:this.spec_s,
												saleAttrs:[
													{
														attrId:'',
														skuId:'',
														attrName:this.spec_s,
														attrValue:spec,
													},
													{
														attrId:'',
														skuId:'',
														attrName:this.spec_s2,
														attrValue:spec2,
													}
												],
											});
									// }
								});
							}
							else{
								this.tableSkuData.push({
									skuId:'',
									skuName: spec+'+'+'',
									skuDesc: '',
									skuImg:imgsku,
									price: this.goods.price,
									marketPrice:this.goods.marketPrice,
									stockNum: this.goods.stockNum,
									spec: spec,
									spec_s: spec_idx,
									spec2:'',
									spec_s2: spec_idx,
									state:'1',
									// shuxing:this.spec_s,
									saleAttrs:[
										{
											attrId:'',
											skuId:'',
											attrName:this.spec_s,
											attrValue:spec,
										},
										{
											attrId:'',
											skuId:'',
											attrName:this.spec_s2,
											attrValue:'',
										}
									],
								});
							}
						// }
						
					});
			},
			affirm2() {
				var imgsku=''
				if(!this.form.skus){
					if(!this.goods.imgs){
						if(this.goods.imgs.search(',')==(-1)){
							imgsku=this.goods.imgs
						}else{
							var a=this.goods.imgs.indexOf(',')
							imgsku=this.goods.imgs.substring(0, a)
						}
						return
					}
					imgsku=''
				}else{
					imgsku=this.goods.imgs
				}
				//颜色
				if (this.dynamicTags_spec2.length > 0) {
					console.log(this.dynamicTags_spec)
					this.dynamicTags_spec2.forEach((spec2,spec_idx2) => {
						console.log(spec_idx2,'颜色',spec2)
						if (!this.tableSkuData.find(x => x.spec2 == spec2)){
							console.log(this.tableSkuData)
								this.tableSkuData.push({
									skuId:'',
									skuName: this.dynamicTags_spec[spec_idx2]+'+'+spec2,
									skuDesc: '',
									skuImg:imgsku,
									price: this.goods.price,
									marketPrice:this.goods.marketPrice,
									stockNum: this.goods.stockNum,
									spec: this.dynamicTags_spec[spec_idx2],
									spec_s: spec_idx2,
									spec2:spec2,
									spec_s2: spec_idx2,
									state:'1',
									// shuxing:this.spec_s2
									saleAttrs:[
										{
											attrId:'',
											skuId:'',
											attrName:this.spec_s,
											attrValue:this.dynamicTags_spec[spec_idx2],
										},
										{
											attrId:'',
											skuId:'',
											attrName:this.spec_s2,
											attrValue:spec2,
										}
									],
									// arr2:[
									// 	{
									// 		attrId:'',
									// 		skuId:'',
									// 		attrName:this.spec_s2,
									// 		attrValue:spec2,
									// 	}
									// ]
								});
						}
					});
			
					this.tableSkuData = this.tableSkuData.filter(x => this.dynamicTags_spec2.find(s => s == x.spec2));
					console.log(this.tableSkuData)
				}
			},
			//规格
			handleClose_spec(tag) {
				this.dynamicTags_spec.splice(this.dynamicTags_spec.indexOf(tag), 1);
				this.affirm()
			},
			showInput_spec() {
				this.inputVisible_spec = true;
				this.$nextTick(() => {
					this.$refs.saveTagInput_spec.$refs.input.focus();
				});
			},
			handleInputConfirm_spec() {
				if (this.inputValue_spec) {
					if (this.dynamicTags_spec.find(x => x == this.inputValue_spec)) {
						this.$message({
							message: this.inputValue_spec + '已存在',
							type: 'warning'
						});
						return;
					}
					this.dynamicTags_spec.push(this.inputValue_spec);
					this.affirm();
				}
				this.inputVisible_spec = false;
				this.inputValue_spec = '';
			},
			// 颜色
			handleClose_spec2(tag) {
				this.dynamicTags_spec2.splice(this.dynamicTags_spec2.indexOf(tag), 1);
				this.affirm()
			},
			showInput_spec2() {
				this.inputVisible_spec2 = true;
				this.$nextTick(() => {
					this.$refs.saveTagInput_spec2.$refs.input.focus();
				});
			},
			handleInputConfirm_spec2() {
				if (this.inputValue_spec2) {
					if (this.dynamicTags_spec2.find(x => x == this.inputValue_spec2)) {
						this.$message({
							message: this.inputValue_spec2 + '已存在',
							type: 'warning'
						});
						return;
					}
					this.dynamicTags_spec2.push(this.inputValue_spec2);
					
					this.affirm();
				}
				this.inputVisible_spec2 = false;
				this.inputValue_spec2 = '';
			},
			open_spec() {
				if (this.checked_spec) return;
				this.$confirm(`此操作将清除【${this.spec_s}】数据, 是否继续?`, '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					})
					.then(() => {
						this.$message({
							type: 'success',
							message: '清除成功!'
						});
						this.dynamicTags_spec = [];
						this.tableSkuData = [];
					})
					.catch(() => {
						this.checked_spec = true;
					});
			},
			open_switch_sku() {
				if (this.switch_sku) return;
				this.$confirm(`此操作将清除数据, 是否继续?`, '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					})
					.then(() => {
						this.$message({
							type: 'success',
							message: '清除成功!'
						});
						this.dynamicTags_spec = [];
						this.tableData = [];
						this.tableSkuData = [];
					})
					.catch(() => {
						this.switch_sku = true;
					});
			},
			handleChange(file, fileLists) {
			// 	this.goods.skuImg=res.data
			//     console.log(file, "file11111");
			},
			// 可以获取图片参数(封面图上传图片)
			handleUpload(file2, row){
			  console.log(file2, "2222",row);
				const file = file2.file;
				const formData = new FormData();
				formData.append('file', file);
				// 文件上传
				this.$axios.post("/file/open/",formData,
				{
					headers:{
						'Content-type' : 'multipart/form-data'
					}
				}).then(response => {
					let res = response
					if (res.success) {
						row.skuImg=res.data
						// this.goods.skuImg=res.data
						// console.log(this.tableSkuData.skuImg)
					} else {
						uni.showToast({
							icon:'error',
							title: '请重新上传！'
						});
					}
				}).catch(res =>{
				});
			},
			handleRemove(e){
				// 删除文件
				this.$axios.delete("/file/open/?url="+this.tableSkuData.skuImg,
				{
				}).then(response => {
					let res = response
					if (res.success) {
						this.tableSkuData.skuImg=''
					} else {
						
					}
				}).catch(res =>{
				});
			},
			imgDelete(e) {
				console.log(e)
				var img = e.tempFiles[0].file;
				const file = img;
				
				const formData = new FormData();
				formData.append('file', file);
				// 文件上传
				this.$axios.post("/file/open/",formData,
				{
					headers:{
						'Content-type' : 'multipart/form-data'
					}
				}).then(response => {
					let res = response
					if (res.success) {
						this.tableSkuData.skuImg=res.data
						console.log(this.tableSkuData.skuImg)
					} else {
						uni.showToast({
							icon:'error',
							title: '请重新上传！'
						});
					}
				}).catch(res =>{
				});
			},
			Delete(e) {
				// 删除文件
				this.$axios.delete("/file/open/?url="+this.tableSkuData.skuImg,
				{
				}).then(response => {
					let res = response
					if (res.success) {
						this.tableSkuData.skuImg=''
					} else {
						
					}
				}).catch(res =>{
				});
			},
		}
	};
</script>

<style>
	input[type='file'] {
		position: absolute;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
		width: 100%;
		cursor: pointer;
		opacity: 0;
		z-index: 99;
	}
</style>

<style>
	.tag-new-tag {
		margin-left: 24px;
	}

	.button-new-tag,
	.input-new-tag {
		margin-left: 24px;
		height: 32px;
		margin-top: 0;
	}

	.input-new-tag {
		width: 100px;
		line-height: 32px;
	}

	>>>.input-new-tag .el-input__inner {
		height: 100%;
	}

	.el-button--small {
		border: 1px solid #dcdfe6;
	}
	>>>.el-upload-list {
		display: none;
	}
</style>
