// 手工选择商品选中的商品列表
var product_list = [];
var search_goods_catid='';
var search_goods_keywords='';
var ob='';
$(function(){
    $('.dialog-close').click(function(){
        close_choose();
    });    
})
//打开选择
function choose_goods(type,idinput,nameinput,inputtype,obj,cache){
    ob = obj;
    if(type)$('#choose_type').val(type);
    if(idinput)$('#idinput').val(idinput);
    if(nameinput)$('#nameinput').val(nameinput);
    if(inputtype)$('#inputtype').val(inputtype);
    $('.choose_goods').show();
    $('.choose_goods_maks').show();
    get_goods_list(0,'null',1,cache);//显示商品
}
//关闭选择
function close_choose(){
    $('.choose_goods').hide();
    $('.choose_goods_maks').hide();
}
//搜索商品
function get_goods_list(search_catid,keywords,page,cache){
    search_goods_catid=search_catid;
    if(keywords!='null'){
        if(keywords)search_goods_keywords=keywords;
        else keywords=search_goods_keywords;
    }else keywords='';
    if(!keywords)keywords=$('#search_keywords').val();
    var goods_html=$('.choose_goods_main').html();
    if(cache){
        if(goods_html){format_search_select();return false;}
    }else{
        $('.choose_goods_main').html('');
        $('.pages_hanchao').html('');
    }
    $('#loading_goods').show();
    var query= new Object();
    var type=$('#choose_type').val();
    query.search_catid = search_catid; //置空搜索框
    query.keywords = keywords; //置空搜索框
    query.type =type;
    var url;
    if(page!=1 && page){
        url=page;
    }else{
        var package=$('#unit_page').val();//判断是否为 添加包装页选择商品
        var is_pt = $('#is_pt').val();
        var is_limit_time = $("input[name='is_limit_time']").val();
        if(package==1){
            url=APP + "PromotAct/choose_goodsp";
        }else if(is_limit_time==1 || is_pt==0 || is_pt==1){
            url=APP + "PromotAct/choose_goods";
        }else{
            url=APP + "PromotAct/choose_goodsg";
        }
    }
    $.ajax({
        type: "POST",
        url: url,
        data: query,
        dataType: "JSON",
        success: function(ret){
            $('#loading_goods').hide();
            if(ret.status == 1){
                $('.choose_goods_main').html(ret.data);
                $('.pages_hanchao').html(ret.page+'<button class="btn btn-primary f_r sureChoose" type="button">确认</button>');
                
                // 产品恢复已经选中、数量、库存等信息
		        format_search_select();
                bind_select_goods();
            }else{
                $.showErr(ret.info);
            }
        }
    });
}
function search_goods(){
    var search_catid = $('#search_catid').val();
    var search_keywords = $('#search_keywords').val();
    search_goods_keywords=search_keywords;
    get_goods_list(search_catid,search_keywords);//显示商品
}
//弹出商品选择框绑定事件
function bind_select_goods(){
	var choose_type =$('#choose_type').val();
    $("input[name='choose_goods']").change(function(){//商品选择
        var goods_index = $(this).data('id');
        var choose_type =$('#choose_type').val();
        if(choose_type==1)product_list=[];	
        if($(this).prop('checked')){// 选中状态		
            var goods_name=$(this).parent().parent().attr('title');
            //var attr_key=$(this).parent().parent().attr('attr_data');
            var attr_name=$(this).parent().parent().attr('attr_name');
            var goods_sn=$(this).parent().parent().attr('goods_sn');
            var product = {};
			product.goods_index = goods_index;
			product.goods_name = goods_name;
            //product.attr_key = attr_key;
            product.attr_name = attr_name;
			product.goods_sn = goods_sn;
			product_list[goods_index] = product;
	  	}else{// 取消选中状态
            var product_list_tmp = [];
			for (var i in product_list) {
				if (i != goods_index) {
					product_list_tmp[i] = product_list[i];
				}
			}
			product_list = product_list_tmp;
	  	}
	})
    //选择商品
    $('.sureChoose').click(function(){
        if($.isEmptyObject(product_list)) {
			    $.showErr('请先选择商品再提交');return false;
		} else {
			if ($(this).hasClass('submitting')) {
			    $.showErr('数据提交中，请勿重复提交');
				return;
			}			
			$(this).addClass('submitting');
			var product_arr = [];
			for (var i in product_list) {
			    addtrtotable(product_list[i]);
				if(choose_type == 1){
					change_goods(product_list[i]);
				}
			}
            close_choose();
           // product_list=[];
            $(this).removeClass('submitting');
		}
    });   
    // 产品搜索分页
    $('.pages_hanchao .pagination a').each(function(){
        var url=$(this).attr('href');
        $(this).attr('href','javascript:void(0)');
        $(this).click(function(){
            get_goods_list(search_goods_catid,search_goods_keywords,url);
        })
    });
}
//产品恢复已经选中、数量、库存等信息
function format_search_select(){
    $("input[name='choose_goods']").each(function () {
		var obj = $(this);		
	    var goods_index = obj.data('id');
        $(this).prop('checked',false);
		// 无多规格情况
		for (var i in product_list) {
			if (i == goods_index) {
                $(this).prop('checked',true);
				break;
			}
		}
	});
}
//根据返回数据添加到表格中
function addtrtotable(info,obj){
    if(!info)return false;
    var type=$('#choose_type').val();   
    var idinput=$('#idinput').val();
    var nameinput=$('#nameinput').val();
    var inputtype=$('#inputtype').val(); 
    if(!idinput)return false;
    if(type==1){//单选
        switch(inputtype){
            case 'select':
            $('#'+idinput).append('<option value="'+info.goods_index+'">'+info.goods_name+'</option>');
            $('#'+idinput).val(info.goods_index);
            break;
            case 'div':
            if(!nameinput)return false;
            $('#'+idinput).val(info.goods_index);
            $('#'+nameinput).html(info.goods_name);
            break;
            default:
            if(!nameinput)return false;   
            $('#'+idinput).val(info.goods_index);
            $('#'+nameinput).val(info.goods_name);
            break;
        }
    }else{//多选
        switch(inputtype){
            default:
			exists = false;
			var selectbox = document.getElementsByName(idinput +"[]");
			for (i = 0; i < selectbox.length; i++){
				if (selectbox[i].type=="checkbox"){
					if (selectbox[i].value == info.goods_index){
						exists = true;
						$.showConfirm('选定的选项已经存在','','hc')
					}
				}
			}
			if (!exists){
			$('#'+idinput).append("<div class='ml10'><label class='checkbox-inline'><input type='checkbox' name='"+ idinput +"[]' value='" + info.goods_index + "' checked='true' /> " + info.goods_name + "【"+ info.goods_sn +"】</label></div>");
			}
            break;
        }
    }
}


// $('#'+inputtype).append('<input type="checkbox" value="'+info.goods_index+'" name="'+idinput+'[]" checked="checked"/> '+info.goods_name);
// for (i = 0; i < selectbox.children().find("input[name='"+ idinput +"[]']").length; i++){
	// if (document.forms['myform'].elements[i].type=="checkbox"){
		// if (document.forms['myform'].elements[i].value == info.goods_index){
			// exists = true;
			// $.showConfirm('选定的选项已经存在','','hc')
		// }
	// }
// }


//获取商品信息
function change_goods(info){
    var query = new Object();
    query.id = info.goods_index;
    $.ajax({
        type: "POST",
        url: APP + "PromotAct/get_goods",
        data: query,
        dataType: "JSON",
        success: function(ret){
            if(ret.status == 1){
                if(info.attr_name){
                    $(ob).val(ret.info.goods_name);
                }else{
                    $(ob).val(ret.info.goods_name);
                }
				var is_pt = $('#is_pt').val();
				var is_limit_time = $("input[name='is_limit_time']").val();
                var package=$('#unit_page').val();//判断是否为 添加包装页选择商品
				if(is_pt == 1 || is_limit_time == 1){
					$(ob).next().val(ret.info.id);
					
					$(ob).parent().next().children().html(ret.info.goods_sn);
					$(ob).parent().next().next().children().html(ret.info.shop_price);
				}else if(package==1){
                    $(ob).next().next().val(ret.info.id);
                    if(ret.info.attr_keys){
                        $(ob).next().html(ret.info.attr_keys);
                    }else{
                        $(ob).next().html("<input type='hidden' name='attr_key[]' value=''>");
                    }
                }else{
					$(ob).next().next().val(ret.info.id);

					$(ob).next().html(ret.info.attr_keys);
					if(ret.info.attr_keys){
						$(ob).next().html(ret.info.attr_keys);
					}else{
						$(ob).next().html("<input type='hidden' name='attr_key[]' value=''>");
					}
					
					$(ob).parent().next().children().html(ret.info.goods_sn);
					$(ob).parent().next().next().children().html(ret.info.shop_price);
					$(ob).parent().next().next().next().children().html(ret.info.unit_name);
				}
                return false;
            }else{
                $.showErr(ret.info);
                return false;
            }
        }
    });
}
function shopprice(obj){
    var shoprice=$(obj).find("option:selected").attr('attrprice');
    var goodssn=$(obj).find("option:selected").attr('goodssn');
    $(obj).parent().parent().next().next().children().html(shoprice);
    $(obj).parent().parent().next().children().html(goodssn);
}
