// 手工选择商品选中的商品列表
var product_list = {};
var search_goods_catid='';
var search_goods_keywords='';
var ob='';
var shop_id=0;
var out_price='';
var is_stock=0;
$(function(){
    $('.dialog-close').click(function(){
        close_choose();
    });    
})
//展开属性
function shrink(obj){
    if($(obj).next().next().attr('style')=="display: none;") {
        $(obj).next().next().css('display','block');
    }else{
        $(obj).next().next().css('display','none');
    }
}
//打开选择
function choose_goods(type,idinput,nameinput,inputtype,obj,keywords,stock){
    ob = obj;
    if(type)$('#choose_type').val(type);
    if(idinput)$('#idinput').val(idinput);
    if(nameinput)$('#nameinput').val(nameinput);
    if(inputtype)$('#inputtype').val(inputtype);
    keywords=keywords?keywords:'null';
    $('.choose_goods').show();
    $('.choose_goods_maks').show();
    get_goods_list(0,keywords,1,1);//显示商品
    if(stock==1) is_stock =1;
}
//关闭选择
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_l=$('.goods_i.f_l').html().trim();
    //var goods_html_r=$('.goods_i.f_r').html().trim();
    //if(cache){
    //    if(goods_html_l || goods_html_r){format_search_select();return false;}
    //}else{
        $('.goods_i').html('');
        $('.pages_hanchao').html('');
    //}
    $('#loading_goods').show();
    var query= new Object();
    var type=$('#choose_type').val();
    query.cate_id = search_catid; //置空搜索框
    query.sn = keywords; //置空搜索框
    query.type =type;
    if(shop_id>0){query.shop_id=shop_id; query.is_shop=1;}
    if(out_price==1 || out_price==2 || out_price==3 || out_price==4 || out_price==5) {//出货且不是以商品批发价出库
        query.out_price=out_price;
    }
    var url;
    if(page!=1 && page){
        url=page;
    }else{
        url=APP + "Ajax/search_goods_list";
    }
    $.ajax({
        type: "POST",
        url: url,
        data: query,
        dataType: "JSON",
        success: function(ret){
            $('#loading_goods').hide();
            if(ret.status == 1){
                $('.goods_i.f_l').html(ret.data.left_html);
                $('.goods_i.f_r').html(ret.data.right_html);
                var html='';
                if(ret.page){html+=ret.page;}
                html+='<button class="btn btn-primary f_r sureChoose mt15" type="button">确认</button>';
                $('.pages_hanchao').html(html);

                // 产品恢复已经选中、数量、库存等信息
		        format_search_select();
                bind_select_goods();
            }else{
                $.showErr(ret.msg);
            }
        }
    });
}
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(){
    //product_list=[];防止数量重复添加
    $("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).attr('title');
            var attr_key=$(this).attr('attr_data');
            var attr_name=$(this).attr('attr_name');
            var supplier_id=$(this).attr('supplier_id');
            var goods_id=$(this).attr('goods_id');
            var unit_name=$(this).attr('unit_name');
            var supply_price=$(this).attr('supply_price');
            var goods_sn=$(this).attr('goods_sn');
            var goods_attr_sn=$(this).attr('goods_attr_sn');
            var stock=$(this).attr('stock');
            var suppliers_name = $(this).attr('suppliers_name');
            var product = {};
			product.goods_index = goods_index;
			product.goods_name = goods_name;
            product.attr_key = attr_key;
            product.attr_name = attr_name?attr_name:'无';
            product.supplier_id = supplier_id;
            product.goods_id = goods_id;
            product.unit_name = unit_name;
            product.supply_price = supply_price;
            product.goods_sn = goods_sn;
            product.stock = stock;
            product.suppliers_name = suppliers_name;
            if(is_stock==1) {
                if (product.stock <= 0) {
                    product.profit_num = 1;
                    product.loss_num = 0;
                    product.profit_price = parseFloat(product.supply_price*product.profit_num).toFixed(2);
                    product.loss_price = parseFloat(0).toFixed(2);
                } else {
                    product.loss_num = parseFloat(product.stock-1);
                    product.profit_num = 0;
                    product.loss_price = parseFloat(product.supply_price*product.loss_num).toFixed(2);
                    product.profit_price = parseFloat(0).toFixed(2);
                }
            }
            if(goods_attr_sn) {
                product.goods_attr_sn = goods_attr_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]);
                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 name_search_select(index){
    $("input[name='choose_goods']").each(function () {
        var obj = $(this);      
        var goods_index = obj.data('id');
        if(index==goods_index){
            if($(this).prop('checked')){
                $(this).prop('checked',false);
            }else{
                $(this).prop('checked',true);
            }
            var choose_type =$('#choose_type').val();
            if(choose_type==1)product_list=[]; 
            if($(this).prop('checked')){// 选中状态     
                var goods_name=$(this).attr('title');
                var attr_key=$(this).attr('attr_data');
                var attr_name=$(this).attr('attr_name');
                var supplier_id=$(this).attr('supplier_id');
                var goods_id=$(this).attr('goods_id');
                var unit_name=$(this).attr('unit_name');
                var supply_price=$(this).attr('supply_price');
                var goods_sn=$(this).attr('goods_sn');
                var stock=$(this).attr('stock');
                var shop_price=$(this).attr('shop_price');
                var goods_attr_sn=$(this).attr('goods_attr_sn');
                var stock=$(this).attr('stock');
                var suppliers_name = $(this).attr('suppliers_name'); //jxr 2019.02.16
                var product = {};
                product.goods_index = goods_index;
                product.goods_name = goods_name;
                product.attr_key = attr_key;
                product.attr_name = attr_name?attr_name:'无';
                product.supplier_id = supplier_id;
                product.goods_id = goods_id;
                product.unit_name = unit_name;
                product.supply_price = supply_price;
                product.shop_price = shop_price;
                product.goods_sn = goods_sn;
                product.stock = stock;
                product.suppliers_name = suppliers_name;
                if(is_stock==1) {
                    if (product.stock <= 0) {
                        product.profit_num = 1;
                        product.loss_num = 0;
                        product.profit_price = parseFloat(product.supply_price*product.profit_num).toFixed(2);
                        product.loss_price = parseFloat(0).toFixed(2);
                    } else {
                        product.loss_num = parseFloat(product.stock-1);
                        product.profit_num = 0;
                        product.loss_price = parseFloat(product.supply_price*product.loss_num).toFixed(2);
                        product.profit_price = parseFloat(0).toFixed(2);
                    }
                }
                if(goods_attr_sn) {
                    product.goods_attr_sn = goods_attr_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; 
            }

        }
    });
}
//根据返回数据添加到表格中
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;
        }


        //$('#'+goodssn).html(info.goodssn);

    }else{//多选
        switch(inputtype){
            case 'tab_d':
                sgoods(info.goods_index);
            break;
            default:
            $('#'+idinput).append('<input type="checkbox" value="'+info.goods_index+'" name="'+idinput+'[]" checked="checked"/> '+info.goods_name);
            break;
        }
    }
}
//获取商品信息
function change_goods(info){
    var query = new Object();
    query.id = info.goods_index;
    $.ajax({
        type: "POST",
        url: APP + "Goods/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);
                }
                $(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.supply_price);
                $(ob).parent().next().next().next().children().html(ret.info.shop_price);
                $(ob).parent().next().next().next().next().children().html(ret.info.unit_name);
                $(ob).parent().next().next().next().next().next().next().val(ret.info.is_type);

                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().next().children().html(shoprice);
    $(obj).parent().parent().next().children().html(goodssn);
}