mui.init({
	beforeback: function() { //获得父页面的webview
		var list = plus.webview.currentWebview().opener(); //触发父页面的自定义事件(refresh),从而进行刷新
		mui.fire(list, 'reload');
		//返回true,继续页面关闭逻辑
		return true;
	}
});

mui.plusReady(function() {

	var self = plus.webview.currentWebview();
	//console.log(self);
	var shopId = self.id;
	var goodsId = self.goodsId;
	// //console.log(shopId);
	//     var  isSale = typeof(self.isSale)!= 'undefined' ? self.isSale : "";
	//     var  isSpec = typeof(self.isSpec)!= 'undefined' ? self.isSpec : "";
	if (goodsId > 0) {
		$(".title").text("编辑商品")

		JZL.ajax(qlgUrl("app/shops/getGoodsInfo"), {
			shopId: shopId,
			goodsId: goodsId
		}, function(data) {
			//console.log(data);
			if (data.status == 1) {
				var html1 = '';
				var data = data.data;
				var i = 0,
					j = 0;
				var res = '';
				var id = data.setNameId;
				if (1 == data.isSpec) {
					getRecommend(page, pageSize, id)
					JZL.ajax(qlgUrl('app/shops/getGoodsSpecCats'), {
						shopId: shopId,
						id: id
					}, function(datas) {
                          setSpec(data.spec, specList)
					});

				}
				if (1 == data.isSale) {
					$('#isSale').prop("checked", "checked");
				}
				mui.each(data, function(index, element) {
					if ($('#' + index).attr("type") == "hidden" & $('#' + index).hasClass('inp')) {
						var imgindex = index.substring(0, index.length - 3);
						var obj = '#' + imgindex;
						// //console.log(obj);
						// if ($(obj)!= "") {
						if ($(obj).is('img')) {
							// //console.log(element);
							$(obj).attr("src", hyhImgUrl(element))
							$('#' + index).val(element)
							// }
						} else if ($('#' + index).hasClass('gallery')) {
							var html = ''
							// //console.log(element.length);
							if (element.length > 0) {
								var imgurls = element.split(",") ? imgurls = element.split(",") : imgurls = element;
								//console.log("test");

								html = ''
								for (var i = 0; i < imgurls.length; i++) {
									html += '<div data-id="' + i +
										'"  data-src="" class="galleryImg photo"><div class="delete"><img src="../img/close.png" alt=""></div><img src=' +
										hyhImgUrl(imgurls[i]) + ' class="ossfile" id="galleryImg[' + i +
										']" alt=""><input type="hidden" value="' + imgurls[i] +
										'" name="gallery[]" class="gallery" id="gallery[' + i + ']"><span class=""></span></div>'
									// $('#' + index+'Img['+i+']').val(hyhImgUrl(imgurls[i]))
								}
								var maxNum = +$('.galleryImg').last().attr('data-id') + 1; //$('.batchImg').children('.galleryImg').length - 1;
								html += '<div class="galleryImg photo" data-id="' + maxNum +
									'" ><img src="../img/pjimg.png" class="ossfile" id="galleryImg[' +
									maxNum + ']" alt=""><input type="hidden" name="gallery[]" value="" class="gallery" id="gallery[' +
									maxNum +
									']"><span class=""></span></div>';
								$(".batchImg").html(html)
							} else {
								html = "";
								html =
									'<div class="galleryImg photo" data-id="0" ><img src="../img/pjimg.png" class="ossfile" id="galleryImg[0]" alt=""><input type="hidden" name="gallery[]" value="" class="gallery" id="gallery[0]"><span class=""></span></div>';
								$(".batchImg").html(html)
							}
						}
					} else if (index == 'goodsCatIdPath') {
						// data.goodsCatIdPath  三级目录
						var goodsCatIdPathArr = [];
						var pathArr = ["largeCat", "mediumCat", "smallCat"]
						// //console.log(data.goodsCatIdPath);
						goodsCatIdPathArr = data.goodsCatIdPath.split('_')
						goodsCatIdPathArr.pop()
						// //console.log(goodsCatIdPathArr);
						mui.each(pathArr, function(idx, ele) {
							// //console.log(idx);
							switch (ele) {
								case 'largeCat':
									getCatIdPathName(goodsCatIdPathArr[0], function(data) {
										// //console.log(data);
										getGoodsCats('largeCat', 0, goodsCatIdPathArr[0]);
									})
									break;
								case 'mediumCat':
									getCatIdPathName(goodsCatIdPathArr[1], function(data) {
										$('#mediumCat').html('<option selected value="' + goodsCatIdPathArr[1] + '">' + data.data.catName +
											'</option>')
									});
									break;
								case 'smallCat':
									getCatIdPathName(goodsCatIdPathArr[2], function(data) {
										$('#smallCat').html('<option selected value="' + goodsCatIdPathArr[2] + '">' + data.data.catName +
											'</option>')
									});
									break;
							}
						})

					} else {
						$('#' + index).val(element)
					}
				})
			}
		})

	} else {
		getGoodsCats("largeCat", 0)
		getRecommend(page, pageSize);

		$(".title").text("添加商品")
	}

	function setSpec(goodsSpec, specList) {
		var html1 = '',
			res = '',
			goodsRes = ''

		var arr = [];
		var arr2 = {};
		for (var i = 0; i < specList.length; i++) {
			arr.push(specList[i].list);
			arr2[specList[i].catId] = specList[i].list;
		}
		var a = combins(arr);
		var cLength = 0;
		var catId = 0;
		var showSpecNames = [];
		while (c = a.next()) {
			res = c.join(' ');
			cLength = c.length;
			for (i = 0; i < cLength; i++) {
				$.each(arr2, function(ind, val) {
					$.each(val, function(index, value) {
						if (value == c[i]) {
							catId = ind;
							return;
						}
					});
				})
				html1 += '<input type="hidden" name="specItemIds[]" id="specItemIds[' + j + '][' + i +
					']" class="inp" value="0" />' +
					'<input type="hidden" name="specNamesId[]" id="specNamesId[' + j + '][' + i + ']" class="inp" value="' +
					catId + '" />' +
					'<input type="hidden" name="specItems[]" id="specItems[' + j + '][' + i + ']" class="inp" value="' + c[
						i] +
					'" />';
			}
			html1 += '<input type="hidden" name="specIds[]" id="specIds[' + j + ']" class="inp" value=\'0\' />' +
				'<div class="addcon_con shadown_wai"><label for="" data-id = "'+j+'" name="showSpecNames[]" class=""><input name="defultType" type="radio" value="" />' + res +
				'</label><input type="text" name="specPrice[]" id="specPrice[' + j +
				']" class="inp label-t" value="" /><input type="text" name="specStock[]" id="specStock[' + j +
				']" class="inp label-t" value=""/></div>'
			j++;
		}
		$('.pricset_con_con').html(html1);
		mui.each(goodsSpec, function(idx, val) {
			goodsRes = '';
			i = 0;
			mui.each(val.names, function(index, value) {
				goodsRes += value.itemName + ' '; //hongse 39ma
			})
			var showSpecNames = $('label[name="showSpecNames[]"]');
			
			var specNameArr=[];
			for(var k=0;k<showSpecNames.length;k++){
				specNameArr[$(showSpecNames[k]).attr('data-id')]= $(showSpecNames[k]).text();
			}
			$.each(specNameArr,function(sitem,sval){
				if (goodsSpec == sval) {
					i=0;
					//find
					mui.each(val.names, function(index, value) {												
						$('#specItemIds[' + sitem + '][' + i +
					']').val(value.itemId);
						i++;	
					});
					$('#specIds[' + sitem + ']').val(val.id);
					$('#specPrice[' + sitem + ']').val(val.specPrice);
	        $('#specStock[' + sitem + ']').val(val.specStock);

				}
			})
			
// 			mui.each(val.names, function(index, value) {
// 				html1 += '<input type="hidden" name="specItemIds[]" id="specItemIds[' + j + '][' + i +
// 					']" class="inp" value="' + value.itemId + '" />' +
// 					'<input type="hidden" name="specNamesId[]" id="specNamesId[' + j + '][' + i +
// 					']" class="inp" value="' +
// 					value.catId + '" />' +
// 					'<input type="hidden" name="specItems[]" id="specItems[' + j + '][' + i + ']" class="inp" value="' +
// 					value.itemName +
// 					'" />';
// 				goodsRes += value.itemName + ' ';
// 				i++;
// 			})
// 			html1 += '<input type="hidden" name="specIds[]" id="specIds[' + j + ']" class="inp" value="' + val.id +
// 				'" />' +
// 				'<div class="addcon_con shadown_wai"><label for="" class="">' + goodsRes +
// 				'</label><input type="text" name="specPrice[]" id="specPrice[' + j +
// 				']" class="inp label-t" value="' + val.specPrice +
// 				'" /><input type="text" name="specStock[]" id="specStock[' + j +
// 				']" class="inp label-t" value="' + val.specStock + '"/></div>';
			// j++;
		})

































		// $('.pricset_con_con').html(html1);
	}

})
}

function getCatIdPathName(catId, callback) {
	JZL.ajax(qlgUrl("app/goodscats/getCatName"), {
		catId: catId
	}, function(data) {
		callback(data);
	})
}

//获取商品总规格列表
var page = 1;
var pageSize = 100;
var isjiazai = 1;

function getRecommend(page, pageSize, defaultVal) {

	var recommenddata = {
		page: page ? page : 1,
		pageSize: pageSize ? pageSize : 100
	}
	recommenddata.shopId = shopId
	if (isjiazai == 0) {
		return;
	} else {
		isjiazai = 0;
	}
	JZL.ajax(qlgUrl('app/shops/getSpecs'), recommenddata, function(data) {


		// //console.log(data);
		data = toJson(data);
		if (data.status == 1) {
			data = data.data;
			var html = '<option value="0">选择属性</option>';
			if (typeof(defaultVal) == "undefined") {
				// //console.log(1);
				$.each(data.Rows, function() {
					html += '<option data-id="' + this.id + ' "value="' + this.id + '">' + this.setName + '</option>'
				});
				if (page == 1) {
					$('#setNameId').html(html);

				} else {
					$('#setNameId').append(html);

				}
			} else {
				// //console.log(defaultVal);
				$.each(data.Rows, function() {
					if (this.id = defaultVal) {
						selected = 'selected';
					} else {
						selected = '';
					}
					html = '<option value="' + defaultVal + '"' + selected + '>' + this.setName + '</option>';
					if (page == 1) {
						$('#setNameId').html(html);

					} else {
						$('#setNameId').append(html);

					}
				});


			}

		} else {
			mui.alert('发生错误请刷新后重试！');
			//							location.reload();
		}
		isjiazai = 1;
	})
}

//获取商品规格

combins = function(args) {

	if (args.length < 2) return args[0] || [];
	// if (arguments.length < 2) return arguments[0] || [];
	//var args = Array.prototype.slice.call(arguments);
	var that = {
		index: 0,
		nth: function(n) {
			var result = [],
				d = 0;
			for (; d < this.dim; d++) {
				var l = this[d].length;
				var i = n % l;
				result.push(this[d][i]);
				n -= i;
				n /= l;
			}
			return result;
		},
		next: function() {
			if (this.index >= size) return;
			var result = this.nth(this.index);
			this.index++;
			return result;
		}
	};
	var size = 1;
	for (var i = 0; i < args.length; i++) {
		size = size * args[i].length;
		that[i] = args[i];
	}
	that.size = size;
	that.dim = args.length;
	return that;
}

// 判断是否上架
var isSale = "",
	setNameId,
	isSpec;
if ($("#isSale").prop("checked")) {
	isSale = "1";
} else {
	isSale = "0";
}
// 判断有没有商品属性

if ($("#setNameId option:selected").val() != "") {
	isSpec = 1;
} else {
	isSpec = 0;
}

$('#setNameId').change(function() {
	var id = $('#setNameId option:selected').val()

	var html1 = "";
	JZL.ajax(qlgUrl('app/shops/getGoodsSpecCats'), {
		shopId: shopId,
		id: id
	}, function(data) {

		// //console.log(data);
		if (1 == data.status) {

			var arr = [];
			var arr2 = {};
			for (var i = 0; i < data.data.length; i++) {
				arr.push(data.data[i].list);
				arr2[data.data[i].catId] = data.data[i].list;
			}
			var a = combins(arr);
			var j = 0;
			var res = '';
			var cLength = 0;
			var catId = 0;
			while (c = a.next()) {
				res = c.join(',');
				cLength = c.length;
				for (i = 0; i < cLength; i++) {
					$.each(arr2, function(ind, val) {
						$.each(val, function(index, value) {
							if (value == c[i]) {
								catId = ind;
								return;
							}
						});

					})
					html1 += '<input type="hidden" name="specItemIds[]" id="specItemIds[' + j + '][' + i +
						']" class="inp" value="0" />' +
						'<input type="hidden" name="specNamesId[]" id="specNamesId[' + j + '][' + i + ']" class="inp" value="' +
						catId + '" />' +
						'<input type="hidden" name="specItems[]" id="specItems[' + j + '][' + i + ']" class="inp" value="' + c[i] +
						'" />';

				}
				html1 += '<input type="hidden" name="specIds[]" id="specIds[' + j + ']" class="inp" value=\'0\' />' +
					'<div class="addcon_con shadown_wai"><label for="" class="">' + res +
					'</label><input type="text" name="specPrice[]" id="specPrice[' + j +
					']" class="inp label-t" value="" /><input type="text" name="specStock[]" id="specStock[' + j +
					']" class="inp label-t" value=""/></div>'
				j++;
			}
			$('.pricset_con_con').html(html1);
		}
	})
})

// 下一页
var check = true;
mui("body").on('tap', '.next_btn', function() {
	check = true;
	$('.isemptyinp').each(function() {
		// //console.log(this);

		if (!this.value || "" == $.trim(this.value)) {
			var label = this.previousElementSibling;
			//console.log(label);
			mui.alert(label.innerText + "不允许为空")
			check = false;
			return false;
		}
	})

	if ($("#shopPrice").val() == "" & $("#setNameId option:selected").val() == "0" & check == true) {
		mui.alert("商品没有属性必须输入商品价格")
		check = false;
		return false;
	}

	if ($("#setNameId option:selected").val() != "" & check == true) {
		$('.pricset_con_con input').each(function() {
			if ((!this.value || "" == $.trim(this.value))) {
				mui.alert("请输入数据")
				check = false;
				return false;
			}
		})
	}


	if (check == true) {
		$(".addcon").css("display", "none")
		$(".pre").css("display", "block");
		backTop();
		let E = window.wangEditor;

		let editor = new E('#goodsDesc');
		editor.customConfig.uploadImgShowBase64 = true;
		editor.create();
	}


})
//预览
mui("body").on('tap', '.prelook', function() {



})



// 上一页
mui('body').on('tap', '.pre_btn', function() {
	$(".addcon").css("display", "block")
	$(".pre").css("display", "none")
})
// //console.log($("#goodsDesc").text());

//提交
var click = false;
mui('.btn').on('tap', '.submit_btn ', function() {
	if (click == true) {
		return
	}

	var imgs = '';
	var data = $('input[name="gallery[]"]');
	// //console.log(data);
	$.each(data, function() {
		if ('' != $(this).val())
			imgs = $(this).val() + ',' + imgs;

	})


	imgs = imgs.substring(0, imgs.lastIndexOf(','));


	$('#gallery').val(imgs);
	// //console.log($('#gallery').val());

	var params = JZL.getParams(".inp");
	params.shopId = shopId;
	params.isSale = isSale;
	params.isSpec = isSpec;
	params.goodsDesc = $("#goodsDesc").text();
	params.setNameId = $('#setNameId option:selected').val()
	click = true;
	if (goodsId > 0) {
		params.goodsId = goodsId;

	}
	JZL.ajax(qlgUrl('app/shops/addGoods'), params, function(data) {
		// //console.log(data);
		if (data.status == 1) {
			mui.back();
		} else {
			mui.alert('发生错误请刷新后重试！');
			//							location.reload();
		}

	})


})

//获取类目
$('.selectarea').on("change", ".area", function() {
	var objs = ['largeCat', 'mediumCat', 'smallCat'];
	// var areaStr = ['请选择', '请选择', '请选择'];
	var level = +$(this).attr('data-level') + 1; //0
	pid = $('#' + objs[level - 1] + ' option:selected').val();
	getGoodsCats(objs[level], pid);

})

//三级类目
function getGoodsCats(obj, pid, defaultId) {
	JZL.ajax(qlgUrl('app/shops/getGoodsCats'), {
			pid: pid
		},
		function(data) {
			// //console.log(data);
			if (data.status == 1) {
				data = data.data;
				var html = '<option value="">' + "请选择" + '</option>';
				if ('undefined' == typeof(defaultId)) {
					$.each(data, function() {
						// //console.log(this);
						html += '<option value="' + this.catId + '">' + this.catName + '</option>'
					});
				} else {
					$.each(data, function() {
						if (this.catId == defaultId) {
							selected = 'selected';
						} else {
							selected = '';
						}
						html += '<option value="' + this.catId + '" ' + selected + '>' + this.catName + '</option>'
					});
				}
				$('#' + obj).html(html);
			}
		})
}

// 上传图片
$(".batchImg").on("tap", '.galleryImg', function() {
	var num = $(this).attr('data-id');
	UP.init("gallery[" + num + "]", "test", "galleryImg[" + num + "]", 1);
	var that = $(this);
	openCamera(function(t, status, fileName, serverName) {
		var html = '<div class="delete" data-id="' + num + '"><img src="../img/close.png" alt=""></div><img src="' +
			serverName + '" class="ossfile" data-src="' + fileName + '" data-id="' + num + '" id="galleryImg[' + num +
			']" alt=""><input type="hidden" name="gallery[]" value="' + fileName +
			'" class="gallery" id="gallery[' + num + ']"><span class=""></span>';
		//	//console.log($('#galleryImg[' + num + ']'));
		//if ($('#galleryImg[' + num + ']').length > 0) {
		that.html(html);
		//} else {
		//	$(".batchImg").append(html);
		//}

		var maxNum = $('.galleryImg').last().attr('data-id'); //$('.batchImg').children('.galleryImg').length - 1;
		if (num == maxNum) {
			maxNum++;
			html = '<div class="galleryImg photo" data-id="' + maxNum +
				'" ><img src="../img/pjimg.png" class="ossfile" id="galleryImg[' +
				maxNum + ']" alt=""><input type="hidden" name="gallery[]" value="" class="gallery" id="gallery[' + maxNum +
				']"><span class=""></span></div>';
			$(".batchImg").append(html);
		}
	});
})

$(".oneImg").on("tap", '#goods', function() {
	// UP.init("accountBookImg", "test", "accountBookImgTag")

	UP.init("goodsImg", "test", "goods")
	openCamera(function(t, status, fileName, serverName) {
		var html = '<img src="' + serverName + '" class="ossfile" data-src="' + fileName +
			'" id="goods" alt=""><input type="hidden" value="' + fileName +
			'" class="goodsImg inp" id="goodsImg"><span class=""></span>';

		$(".goods").html(html);

	})
})
// 删除图片
$(".batchImg").on('tap', '.delete', function(e) {

e.preventDefault();
e.stopPropagation()

// //console.log(this);
var that = $(this)
//var idx = that.parent().attr('data-id');
//var maxNum = $('.galleryImg').last().attr('data-id'); //$('.batchImg').children('.galleryImg').length - 1;
if (confirm('确认删除图片？')) {
	that.parent().remove()
	//delete galleryarr[idx];
}
})

})
