<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-button v-if="skuGroups.length<2 && switch_sku" class="button-new-tag" size="small"
						@click="addSKU" style="margin:0 80px 20px;">添加SKU</el-button>
					<div v-for="(item,index) in skuGroups">

						<el-form-item :label="`编辑SKU${index+1}`" v-if="switch_sku">
							<div>
								<!-- <el-checkbox @change="open_spec" class="margin_r_10"
									v-model="checked_spec"></el-checkbox> -->
								<el-input v-model="item.attrName" placeholder="编辑SKU"></el-input>

							</div>
							<div class="dflex margin_t_20">
								<el-tag type="info" class="tag-new-tag" :key="idx" v-for="(tag, idx) in item.attrValues"
									:closable="checked_spec" :disable-transitions="false"
									@close="handleClose_spec(tag,index,idx)">
									{{ tag.attrValue }}
								</el-tag>
								<el-input class="input-new-tag" v-if="tagindex == item.attrName && inputVisible_spec"
									v-model="inputValue_spec" ref="saveTagInput_spec"
									@keyup.enter.native="handleInputConfirm_spec(item,index)"
									@blur="handleInputConfirm_spec(item,index)"></el-input>
								<el-button :disabled="!checked_spec" v-else class="button-new-tag" size="small"
									@click="showInput_spec(item,index)">添加</el-button>
							</div>
						</el-form-item>
					</div>
					<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="
										(file) => {
											return handleChange(file, scope.row);
										}
										" :http-request="
										(file) => {
											return handleUpload(file, scope.row);
										}
									">
										<template #trigger>
											<view>+</view>
										</template>
									</el-upload>
								</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-for="(item, index) in skuGroups" :key="index"
							   :label="item.attrName" align="center">
								<!-- 分行显示 -->
								<div v-for="(item2, index2) in item.attrValues" :key="index2">22
									<template slot-scope="scope">{{item2.attrValue}}
										<!-- <div v-if="scope.row.saleAttrs[index2]">{{ scope.row.saleAttrs[index2].attrValue }}</div> -->
									</template>
								</div>
							</el-table-column>
														
							<!-- <template v-if="skuGroups.length==1">
								<el-table-column prop="spec" :label="skuGroups[0].attrName" align="center">
								</el-table-column>
							</template>
							<template v-if="skuGroups.length==2">
								<el-table-column prop="spec" :label="skuGroups[0].attrName" align="center">
								</el-table-column>
								<el-table-column prop="spec2" :label="skuGroups[1].attrName" align="center">
								</el-table-column>
							</template> -->

						</el-table>
					</el-form-item>
				</div>
			</div>
		</el-form>
	</div>
</template>

<script>
	import { cos } from '@/util/cos.js'
	export default {
		data() {
			return {
				switch_sku: true,
				skus: [],
				goods: {},
				skuGroups: [],
				tagindex: "", // 点击那个规格
				inputVisible_spec: false,
				inputValue_spec: '',
				checked_spec: true,
				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({
						})
					);
				}
			},
			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')
				this.form.skuGroups.forEach(item => {
					item.attrValues.forEach(i => {
						if (item.attrName) {
							i.attrName = item.attrName
						}
					})
				})
				this.skuGroups = this.form.skuGroups

				console.log(this.skuGroups, "skuGroups数据");
				let skus = this.form.skuGroups
				this.tableSkuData = res.skus;
				console.log(skus, 'skus', skus[0].attrName)

				for (var i = 0; i < this.tableSkuData.length; i++) {
					if (this.tableSkuData[i].saleAttrs.length == 1) {
						this.tableSkuData[i].spec = this.tableSkuData[i].saleAttrs[0].attrValue
					} else if (this.tableSkuData[i].saleAttrs.length == 2) {
						this.tableSkuData[i].spec = this.tableSkuData[i].saleAttrs[0].attrValue
						this.tableSkuData[i].spec2 = this.tableSkuData[i].saleAttrs[1].attrValue
					} else if (this.tableSkuData[i].saleAttrs.length == 0) {
						this.tableSkuData[i].spec = ''
					}

				}
				console.log(this.tableSkuData)

				var dynamicTags_spec=[]
				skus[0].attrValues.forEach(data => {
					dynamicTags_spec.push(data.attrValue)
				})

				this.checked_spec = 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 = []
					let arr1 = this.skuGroups[0].attrValues;
					let arr2 = this.skuGroups[1].attrValues;
					if (arr1.length > 0) {
						if (arr2.length > 0) {
							arr1.forEach((item, index) => {
								arr2.forEach((i, ind) => {
									this.tableSkuData.push({
										skuId: '',
										skuName: item.attrValue + '+' + i.attrValue,
										skuDesc: '',
										skuImg: imgsku,
										price: this.goods.price,
										marketPrice: this.goods.marketPrice,
										stockNum: this.goods.stockNum,
										spec: item.attrValue,
										spec_s: index,
										spec2: i.attrValue,
										spec_s2: ind,
										state: '1',
										saleAttrs: [],
									});
									var shuju1=[]
									shuju1=this.tableSkuData[index].saleAttrs
									shuju1.push({
											attrId: '',
											skuId: '',
											attrName: item.attrName,
											attrValue: item.attrValue,
									})
									var shuju2=[]
									shuju2=this.tableSkuData[ind].saleAttrs
									shuju2.push({
											attrId: '',
											skuId: '',
											attrName: i.attrName,
											attrValue: i.attrValue,
									})
								})
							})
						} else {
							arr1.forEach((item, index) => {
								this.tableSkuData.push({
									skuId: '',
									skuName: item.attrValue,
									skuDesc: '',
									skuImg: imgsku,
									price: this.goods.price,
									marketPrice: this.goods.marketPrice,
									stockNum: this.goods.stockNum,
									spec: item.attrValue,
									spec_s: index,
									spec2: "",
									spec_s2: "",
									state: '1',
									saleAttrs: [],
								});
								var shuju1=[]
								shuju1=this.tableSkuData[index].saleAttrs
								shuju1.push({
										attrId: '',
										skuId: '',
										attrName: item.attrName,
										attrValue: item.attrValue,
								})
							})
						}
					} else {
						if (arr2.length > 0) {
							arr2.forEach((i, ind) => {
								this.tableSkuData.push({
									skuId: '',
									skuName: i.attrValue,
									skuDesc: '',
									skuImg: imgsku,
									price: this.goods.price,
									marketPrice: this.goods.marketPrice,
									stockNum: this.goods.stockNum,
									spec: "",
									spec_s: "",
									spec2: i.attrValue,
									spec_s2: ind,
									state: '1',
									saleAttrs: [],
								})
								var shuju2=[]
								shuju2=this.tableSkuData[ind].saleAttrs
								shuju2.push({
										attrId: '',
										skuId: '',
										attrName: i.attrName,
										attrValue: i.attrValue,
								})
							})
						} else {
							this.tableSkuData = []
						}

					}
					console.log(this.tableSkuData)
			},
			// 添加SKU
			addSKU() {
				this.skuGroups.push({
					attrName: "",
					attrValues: []
				})
			},

			//规格
			handleClose_spec(tag, index,idx) {
				console.log(tag.attrValue,index,idx);
				console.log(this.skuGroups);
				console.log(this.skuGroups[index].attrValues.indexOf(tag.attrValue))
				this.skuGroups[index].attrValues=this.skuGroups[index].attrValues.filter((item,index)=>{
					return item.attrValue!=tag.attrValue
				}),
				this.affirm()
			},
			showInput_spec(item, index) {
				this.inputVisible_spec = true;
				this.tagindex = item.attrName;
				this.$nextTick(() => {
					// console.log(this.$refs.saveTagInput_spec);
					this.$refs.saveTagInput_spec[0].focus();
				});
			},
			handleInputConfirm_spec(item) {
				console.log(item);
				if (this.inputValue_spec) {
					if (item.attrValues.find(x => x.attrValue == this.inputValue_spec)) {
						this.$message({
							message: this.inputValue_spec + '已存在',
							type: 'warning'
						});
						return;
					}
					let arr = {
						attrValue: this.inputValue_spec,
						skuIds: "",
						attrName: item.attrName,
					}

					item.attrValues.push(arr);
					this.affirm();
					console.log(this.skuGroups, "skuGroups数据");
				}
				this.inputVisible_spec = false;
				this.inputValue_spec = '';
			},
			open_spec() {
				if (this.checked_spec) {
					return;
				};
				this.$confirm(`此操作将清除【${this.spec_s}】数据, 是否继续?`, '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					})
					.then(() => {
						this.$message({
							type: 'success',
							message: '清除成功!'
						});
						this.tableSkuData = [];
					})
					.catch(() => {
						this.checked_spec = true;
					});
			},
			open_switch_sku() {
				console.log(this.switch_sku,'是否')
				if (this.switch_sku) {
					this.setData()
					return;
				};
				this.$confirm(`此操作将清除数据, 是否继续?`, '提示', {
						confirmButtonText: '确定',
						cancelButtonText: '取消',
						type: 'warning'
					})
					.then(() => {
						this.$message({
							type: 'success',
							message: '清除成功!'
						});
					})
					.catch(() => {
						this.switch_sku = true;
					});
			},
			handleChange(file, fileLists) {
				const file2 = file.url;
				const Key = file.name
				cos.postObject(
					{
						Bucket: 'jinganminsu-1320402385',
						Region: 'ap-nanjing',
						Key: Key,
						FilePath: file2,
						onProgress: (info) => {
							// console.log(info)
						}
					},
					(err, data) => {
						if (err) {
							console.log('上传失败', err)
						} else {
							console.log('上传成功', data)
				
							uni.hideLoading()
							let imgUrl = 'https://' + data.Location
							fileLists.skuImg =imgUrl
							
						}
					}
				)
			},
			// 可以获取图片参数(封面图上传图片)
			handleUpload(file2, row) {
				
			},
			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>