$(function(){

	var ue = UE.getEditor('editor');

	onloadurl();

	fetchChildType = function(_target,_supId){// 提取下级板块分类
		var _httpURL = HttpRest+"/prod/type/child/"+_supId+".shtml";
		$.ajax({
			url: _httpURL, 
			type: "get", 
			contentType:"application/json",
			success: function(resp) {
				var data = resp.content;
				if (data != null) {
					var h = "<option value='0'>请选择</option>";
					for ( var i = 0; i < data.length; i++) {
						h+="<option value='" + data[i].typeId + "'>"+ data[i].name + "</option>";
					}
					$(_target).html(h);
				} else {
					layer.msg("获取分类信息错误，请联系管理员！",{icon: 5});
				}
			}
		});
	}

	fetchChildType("#mainType",1);

	$("#mainType").change(function(){
		var supId = $("#mainType").val();
		//fetchChildType("#secondType",supId);
		fetchChildType("#typeId",supId);
	});

	/*$("#secondType").change(function(){
		var supId = $("#secondType").val();
		fetchChildType("#typeId",supId);
	});*/

	showThumPic = function(){
		var pic = $.trim($("#pic").val());
		$("#picshow").attr("src",pic);
	};

	$("#submitBtn").click(function(){

		var prodId = $("#prodId").val();
		var merchId = $("#merchId").val();
		var merch = $("#merch").val();

		var name = $("#name").val();
		var sku = $("#sku").val();
		var price = $("#price").val();
		var orig = $("#orig").val();
		var status =$("#status").val();
		var pic = $("#pic").val();
		var img = $("#img").val();
		var state =$("#state").val();
		var typeId = $("#typeId").val();

		var content= UE.getEditor('editor').getContent();

		if(prodId == ''||prodId=='0'){
			if(typeId==''||typeId=='0'){
				var stype = $("#secondType").val();
				if(stype!=''){
					typeId = stype;
				}else{
					typeId = $("#mainType").val();
				}
			}
			if(typeId==''||typeId=='0'){
				layer.msg('请选择商品分类',{icon: 5});
				return;
			}
		}
		var _method = "post";

		if(prodId=='' || prodId ==0){
			if(name==''||sku==''){
				layer.msg('产品名称和SKU编码为空',{icon: 5});
				return;
			}
			if(pic==''){
				layer.msg('请填写商品图片',{icon: 5});
				return;
			}
			_method = "put";
		}
		if(price=='' || price==0){
			layer.msg('请填写商品价格',{icon: 5});
			return;
		}
		if(orig ==''){
			orig = price;
		}else{
			if(price>orig){
				layer.msg('价格不合理 ,销售价<=市场价',{icon: 5});
				return;
			}
		}
		var params = {
				prodId:prodId,
				merchId:merchId,
				merch:merch,
				typeId:typeId,
				name:name,
				sku:sku,
				price:price,
				orig:orig,
				status:status,
				state:state,
				pic:pic,
				img:img,
				info:content
		};

		$.ajax({
			url: HttpRest+"/prod.shtml", 
			type: _method, 
			dataType: "json",
			data:$.toJSON(params),   
			contentType:"application/json",
			success: function(data) { 
				if(data.code=='01'){
					layer.confirm('保存成功！是否关闭窗口?', function(index) {
						parent.grid.loadData();
						parent.layer.close(parent.pageii);
						return false;
					});
				}else{
					layer.msg('保存失败！',{icon: 5});
				}
			}
		});
	});

});