<?php
/**
 * 进销存账单
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaol lss <xiaol@sina.cn>
 */
namespace Common\Model;
use Think\Model;
class InvoicingOrderModel extends Model{

    /*进销存操作start*/
    /**
     * 添加进货，订货，出库，调货操作
     * @param $postdata
     * @return array
     */
    public function order_in_insert($postdata){
        $return=array('status'=>0,'msg'=>'');
        $goodslist=$postdata['infos'];
        if(empty($goodslist)){$return['msg']='请选择商品';return $return;}
        $supplier_id=intval($postdata['supplier_id']);
        $shop_id_in=intval($postdata['shop_id_in']);
        $shop_id_out=intval($postdata['shop_id_out']);
        if($shop_id_in<=0 && $shop_id_out<=0){$return['msg']='请选择仓库';return $return;}
        $now_time=NOW_TIME;
        $type=empty($postdata['type'])?0:intval($postdata['type']);//货单类型（0仓库订货.1进货.2普通出库.3仓库退货.4仓库调货-出）
        $status=empty($postdata['status'])?0:intval($postdata['status']);//状态（0待审核.1配货中.2待入库.3已完成4.已拒绝5已作废.）
        $mtype=empty($postdata['mtype'])?0:intval($postdata['mtype']);//操作人类型（0后台1仓库）
        /*新增订货是否开启支付方式判断start*/
        if($type==0 && $mtype==1){
            $s_map=array();
            $s_map['id']=$shop_id_in;
            $s_map['status']=1;
            $online_type=M('Shops')->where($s_map)->getField('online_type');
            if($online_type!=0){$return['msg']='请选择支付方式'; return $return;}
        }
        /*新增订货是否开启支付方式判断end*/
        $cashier_id=empty($postdata['cashier_id'])?0:intval($postdata['cashier_id']);//如果是仓库操作需要记录操作员id
        $all_money=$all_count=$goods_allmoney=$discount=0;
        //foreach($goodslist['all_money'] as $k => $v){$all_money+=$v;}//计算订单的总价格
        $request_num=empty($goodslist['request_num'])?$goodslist['freight_num']:$goodslist['request_num'];//请求量
        foreach($request_num as $k => $v){
            $all_count+=$v;
            if($type==0){
                $goods_price=array();
                $in_shop_id=$shop_id_in;
                $goods_price=D('Pad/InvoicingOrder')->get_min_price($in_shop_id,$goodslist['goods_id'][$k],$goodslist['goods_attr_sn'][$k]);
                $goodslist['new_supply_price'][$k]=$goods_price['goods_price'];//折扣后
                $goodslist['price'][$k]=$goods_price['price'];//原价
                $goodslist['discount'][$k]=format_decimal($goods_price['price']-$goods_price['goods_price']);
                $all_money+=$goods_price['goods_price']*$v;
                $discount+=($goods_price['price']-$goods_price['goods_price'])*$v;
                $goods_allmoney+=$goods_price['price']*$v;
            }else{
                $goodslist['new_supply_price'][$k]=$goodslist['supply_price'][$k];//折扣后
                $goodslist['price'][$k]=$goodslist['supply_price'][$k];//原价
                $goodslist['discount'][$k]=0;
                $all_money+=$goodslist['supply_price'][$k]*$v;
                $goods_allmoney+=$goodslist['supply_price'][$k]*$v;
            }
        }//计算订单总请求量
        $best_time=empty($postdata['best_time'])?0:strtotime($postdata['best_time']);//期望发货时间
        if($type==2 || $type==3 || $type==4){//涉及仓库出货的需要验证库存
            foreach($goodslist['goods_id'] as $k => $v){
                $num = D('Common/Cart')->shopgoodsstock($v,$postdata['shop_id_out'],$goodslist['goods_attr_sn'][$k]);
                if($num['goods_number'] <= 0 || $num['goods_number'] < $goodslist['freight_num'][$k]){
                    $return['msg'] = '库存不足！';
                    return $return;
                }
            }
        }
        $order_info=array(
            'type'=>$type,
            'mtype'=>$mtype,
            'pre_money'=>format_decimal($postdata['all_pre_money']),//预付款
            'count'=>floatval($all_count),//货流量
            'all_money'=>format_decimal($all_money),//订单折扣后
            'goods_allmoney'=>format_decimal($goods_allmoney),//订单总金额
            'discount'=>format_decimal($discount),
            'shop_id_in'=>$shop_id_in,//入库仓库id
            'shop_id_out'=>$shop_id_out,//出库仓库id
            'cashier_id'=>$cashier_id,//操作人
            'add_time'=>$now_time,
            'status'=>$status,
            'remarks'=>$postdata['remarks'],
            'update_time'=>$now_time,
            'best_time'=>$best_time,
            'supplier_id'=>$supplier_id,
        );
        //是否生成订单号，订货之外的订单下单有订单号
        //if(($type>0 && $status>0)) $order_info['sn']=$this->invoicing_sn();
        if($type==1||$type==5){
            $qianzhui='RK';
        }elseif ($type==2 || $type==3 || $type==4 ||$type==6) {
            $qianzhui='CK';
        }elseif ($type==0){
            $qianzhui='CG';
        }
        if($postdata['is_sn']==1){
            $order_info['sn']=$this->invoicing_sn($qianzhui);
        }else{
            if(($type>0 && $status>0)) $order_info['sn']=$this->invoicing_sn($qianzhui);
        }
        if($postdata['admin_jin']==1 && $mtype==0){ //后台进货订单状态为已完成
            $order_info['status'] = 3;
        }
        $id=M('InvoicingOrder')->add($order_info);
        if($id<=0){$return['msg']='添加货单失败';return $return;}

        //加入InvoicingGoods表
        $goods_list=array();
        $goods_status=empty($postdata['goods_status'])?0:intval($postdata['goods_status']);
        foreach($goodslist['goods_name'] as $k=>$v){
            $goods_list['order_id']=$id;
            $goods_list['goods_id']=$goodslist['goods_id'][$k];
            $goods_list['goods_name']=$v;
            $goods_list['goods_sn']=$goodslist['goods_sn'][$k];//商品编号
            $goods_list['goods_attr_sn']=(empty($goodslist['goods_attr_sn'][$k]) || $goodslist['goods_attr_sn'][$k]=='null')?'':$goodslist['goods_attr_sn'][$k];
            $goods_list['supply_price']=$goodslist['new_supply_price'][$k];
            $goods_list['price']=$goodslist['price'][$k];
            $goods_list['discount_extra']=$goodslist['discount'][$k];
            $goods_list['shop_id']=empty($shop_id_in)?$shop_id_out:$shop_id_in;
            $goods_list['supplier_id']=empty($goodslist['supplier_id'][$k])?0:$goodslist['supplier_id'][$k];
            $goods_list['storage_id']=empty($goodslist['storage_id'][$k])?1:$goodslist['storage_id'][$k];
            $goods_list['order_cashier_id']=$cashier_id;
            $goods_list['pre_money']=format_decimal($postdata['all_pre_money']);
            $goods_list['all_money']=empty($goodslist['all_money'][$k])?0:$goodslist['all_money'][$k];
            $goods_list['request_num']=empty($goodslist['request_num'][$k])?0:floatval($goodslist['request_num'][$k]);
            if($type==2 || $type==3){//出库
                $goods_list['freight_num']=empty($goodslist['freight_num'][$k])?0:floatval($goodslist['freight_num'][$k]);
                $goods_list['fact_num']=empty($goodslist['fact_num'][$k])?$goods_list['freight_num']:floatval($goodslist['fact_num'][$k]);
            }elseif($type==4){
                $goods_list['request_num']=$goodslist['freight_num'][$k];
                $goods_list['freight_num']=$goodslist['freight_num'][$k];
                $goods_list['freight_num']=$goodslist['freight_num'][$k];
                $goods_list['fact_num']=empty($goodslist['fact_num'][$k])?$goods_list['freight_num']:floatval($goodslist['fact_num'][$k]);
            }else {
                $goods_list['freight_num'] = empty($goodslist['freight_num'][$k]) ? 0 : floatval($goodslist['freight_num'][$k]);
                $goods_list['fact_num'] = empty($goodslist['fact_num'][$k]) ? 0 : floatval($goodslist['fact_num'][$k]);
            }
            $goods_list['status']=$goods_status;
            $goods_list['order_time']=$now_time;
            $goods_list['update_time']=$now_time;
            if($postdata['admin_jin']==1 && $mtype==0){ //后台进货 直接入库
                $goods_list['status'] = 3;
                $goods_list['send_time'] = $now_time;
                $goods_list['fact_num'] = $goods_list['freight_num'];
            }
            if($type==1 && $mtype==1) $goods_list['send_time']=$now_time;//仓库进货，直接填写发货时间
            $result=M('InvoicingGoods')->add($goods_list);
        }
        if($result!=false){
            $return=array('status'=>1,'msg'=>'已成功为仓库进货','id'=>$id);
            //加入订单对账表
            if($type==1 && $mtype==1){
                //仓库进货添加供货商对账状态为待对账
                $this->add_invoicing_detail($id,1,0,$postdata['pre_money']);//添加供货商对账单
                $this->add_storage($id);//添加库存
            }elseif($type==1 && $mtype==0){//后台进货
                if($postdata['admin_jin']==1){
                    $this->add_invoicing_detail($id,1,0,$postdata['pre_money']);//添加供货商对账单
                    $this->add_storage($id);//添加库存
                    action_log('audit_ru_order', 'Admin', $id, UID);//操作日志
                }else{
                    $this->add_invoicing_detail($id,0,0,$postdata['pre_money']);//添加供货商对账单
                    FrieghtPushSend($shop_id_in);//极光推送（app/pad）
                }
            }elseif($type==2 || $type==3 || $type==6){//后台出库2普通出库3仓库退货
                if($type==2 || $type==6){
                    $this->reduce_storage($id);
                }//减少库存并记录出库记录
                //$this->reduce_storage($id);//减少库存并记录出库记录
                //if($type==3 && $mtype==0) $this->add_invoicing_detail($id,1,0,array(),1);//减少供货商对账单
                $return=array('status'=>1,'msg'=>'已成功为仓库出货','id'=>$id);
            }elseif($type==4){//调货
                if($mtype==0){
                    if($postdata['admin_diao']==1){ //后台操作调货
                        $shop_in_name=idtoname($shop_id_in,'Shops');
                        $return=array('status'=>1,'msg'=>'成功给仓库'.$shop_in_name.'调货');
                        $this->reduce_storage($id);//减少库存
                        action_log('audit_diao_order', 'Admin', $id, UID);//操作日志
                    }else{
                        FrieghtPushSend($shop_id_out);
                        $return=array('status'=>1,'msg'=>'已成功向仓库发起调货通知','id'=>$id);
                    }
                }elseif($mtype==1){
                    FrieghtPushSend($shop_id_in);
                    $return=array('status'=>1,'msg'=>'成功给仓库'.$shop_id_in.'调货');
                    $this->reduce_storage($id);//减少库存
                }
            }else{
                $return=array('status'=>1,'msg'=>'已成功为仓库订货','id'=>$id);
            }
        }else{
            $return['msg']='添加商品失败';
        }
        return $return;
    }

    /**
     * 随机生成货流单号
     */
    public function invoicing_sn($type='I'){
        // return 'I'.base_order();
        return $type.base_order();
    }

    /**
     * 加入，修改账单明细（用于进货，订货，普通出库，仓库退货，仓库调货-出）
     * @param $id  订单id
     * @param $status  对账状态0待确认，1待对账，2待结算，3已结算，4作废
     * @param $is_re  是否为修改 1修改0添加
     * @param $pre_money  array  预付款数组(键值是供货商)
     * @param $is_reduce int 是否为出库（仓库退货）
     */
    public function add_invoicing_detail($id,$status=0,$is_re=0,$pre_money=array(),$is_reduce=0){
        $map=array();
        $map['id']=$id;
        $order_status=M('InvoicingOrder')->where($map)->getField('status');//获取订单状态
        $map=array();
        $map=array('order_id'=>$id);
        if($order_status<2){//0待审核.1配货中
            $field='sum(request_num) as count_num,sum(all_money) as sum_money,supplier_id';
        }
        if($order_status==2){//待入库
            $field='sum(freight_num) as count_num,sum(all_money) as sum_money,supplier_id';
        }
        if($order_status==3){//已完成
            $field='sum(fact_num) as count_num,sum(all_money) as sum_money,supplier_id';
        }
        $info=M('InvoicingGoods')->where($map)->field($field)->group('supplier_id')->select();//按照供货商
        if(!empty($info)) {
            $savedata = array();
            if($is_re==1){
                foreach($info as $k => $v){
                    $savedata['fact_num'] = $v['count_num'];
                    $savedata['all_price'] = $v['sum_money'];
                    $savedata['status'] = $status;
                    $map['supplier_id']=$v['supplier_id'];
                    M('InvoicingDetail')->where($map)->save($savedata);
                }
            }else{
                $now_time=NOW_TIME;
                foreach ($info as $k => $v) {
                    $savedata[$k]['supplier_id'] = $v['supplier_id'];
                    $savedata[$k]['order_id'] = $id;
                    if($is_reduce==1) {//出库（仓库退货）
                        $savedata[$k]['fact_num'] = -$v['count_num'];
                        $savedata[$k]['all_price'] = -$v['sum_money'];
                    }else {
                        $savedata[$k]['fact_num'] = $v['count_num'];
                        $savedata[$k]['all_price'] = $v['sum_money'];
                    }
                    $savedata[$k]['status'] = $status;
                    $savedata[$k]['pre_money'] = empty($pre_money)?0:$pre_money[$v['supplier_id']];
                    $savedata[$k]['already_money'] = $savedata[$k]['pre_money'];
                    $savedata[$k]['add_time'] = $now_time;
                }
                $res=M('InvoicingDetail')->addAll($savedata);
                if($res){
                    $return['status']=1;return $return;
                }else{
                    $return['status']=0; $return['msg']='失败'; return $return;
                }
            }
        }
    }

    /**
     * 计算平均价格
     */
    public function count_price($id){
        //查找商品id
        $map=array();
        $map['order_id']=$id;
        $goods_info=M('InvoicingGoods')->where($map)->field('id,shop_id,goods_id,goods_sn,goods_attr_sn,supplier_id,supply_price,fact_num')->select();
        if(!empty($goods_info)){
            foreach($goods_info as $k => $v){
                $map=array();
                $map['goods_id']=$v['goods_id'];
                $map['shop_id']=$v['shop_id'];
                $map['goods_stock']=empty($v['goods_attr_sn'])?0:$v['goods_attr_sn'];//属性值
                $goods_number=abs(M('ShopsGoodsStock')->where($map)->getField('goods_number'));
                $map=array();
                $map['shop_id']=$v['shop_id'];
                $map['goods_id']=$v['goods_id'];
                $map['goods_sn']=$v['goods_sn'];//商品编号
                $map['is_delete']=0;
                $count=M('ShopsGoods')->where($map)->count();
                $shop_goods=M('ShopsGoods')->where($map)->field('avg_price,stock_count')->find();
                if(floatval($shop_goods['avg_price'])<=0){$shop_goods['avg_price']=$v['supply_price'];}
                //计算平均价的公式
                $count_avg_price=($shop_goods['avg_price']*$goods_number+$v['supply_price']*$v['fact_num'])/($goods_number+$v['fact_num']);
                $savedata=array();
                if($count>0){
                    $savedata['avg_price']=$count_avg_price;//平均进货价
                    $savedata['stock_count']=$shop_goods['stock_count']+1;//进货次数
                    $savedata['suppliers_id']=$v['supplier_id'];//供货商id
                    M('ShopsGoods')->where($map)->save($savedata);
                }else{
                    $savedata['goods_id']=$v['goods_id'];
                    $savedata['goods_sn']=$v['goods_sn'];
                    $savedata['suppliers_id']=$v['supplier_id'];
                    $savedata['shop_id']=$v['shop_id'];
                    $savedata['addtime']=NOW_TIME;
                    $savedata['status']=1;
                    $savedata['goods_type']=1;
                    $savedata['avg_price']=$count_avg_price;
                    $savedata['stock_count']=1;
                    M('ShopsGoods')->add($savedata);
                }
            }
        }
    }

    /**
     * 确认收货增加库存
     * @param $id
     * @param $type 0给入库仓库加库存 1给出库仓库加库存
     */
    public function add_storage($id,$type=0){
        $map=array();
        $map['id']=$id;
        $order_info=M('InvoicingOrder')->where($map)->field('shop_id_in,shop_id_out,sn,type')->find();
        if(!empty($order_info)) {
            $map=array();
            $map['order_id']=$id;
            $info=M('InvoicingGoods')->where($map)->field('goods_id,goods_sn,goods_attr_sn,freight_num,fact_num,shop_id,supplier_id')->select();
            if($type!=1) {
                $this->count_price($id);//计算平均价格修改shopsgoods表
                foreach ($info as $k => $v) {
                    //存商品库存表
                    $map = array();
                    $map['goods_id'] = $v['goods_id'];
                    $map['shop_id'] = $order_info['shop_id_in'];//给入库仓库增加库存
                    $map['goods_stock'] = empty($v['goods_attr_sn']) ? 0 : $v['goods_attr_sn'];
                    $count = M('ShopsGoodsStock')->where($map)->count();//查询店铺库存表是否有库存
                    if ($count > 0) {//有库存，直接增加库存
                        $stock_cfg = M('ShopsGoodsStock')->where($map)->getField('goods_number');
                        $savedata = array();
                        $savedata['goods_number'] = $stock_cfg + $v['fact_num'];
                        M('ShopsGoodsStock')->where($map)->save($savedata);
                    } else {//没有库存添加一条新的数据存储
                        $savedata = array();
                        $savedata['goods_number'] = $v['fact_num'];
                        $savedata['goods_id'] = $v['goods_id'];
                        $savedata['goods_stock'] = empty($v['goods_attr_sn']) ? 0 : $v['goods_attr_sn'];
                        $savedata['shop_id'] = $order_info['shop_id_in'];
                        $savedata['suppliers_id'] = $v['supplier_id'];
                        $savedata['addtime'] = NOW_TIME;
                        $savedata['updatetime'] = NOW_TIME;
                        M('ShopsGoodsStock')->add($savedata);
                    }
                    $shop_name=idtoname($order_info['shop_id_in'],'Shops','name');
                    $desc = '货单号' . $order_info['sn'] . '店铺' . $shop_name . '确认收货增加库存';
                    $attr_key = $v['goods_attr_sn'];
                    change_stock_log($order_info['shop_id_in'], $id, ($stock_cfg ? $stock_cfg : 0), $v['goods_id'], $v['fact_num'], 0, $desc, 3, $attr_key);
                    if ($order_info['type'] == 4 && $order_info['shop_id_out']) {
                        $act_num = $v['fact_num'] - $v['freight_num'];
                        $map = array();
                        $map['goods_id'] = $v['goods_id'];
                        $map['shop_id'] = $order_info['shop_id_out'];
                        $map['goods_stock'] = empty($v['goods_attr_sn']) ? 0 : $v['goods_attr_sn'];
                        $goods_number = M('ShopsGoodsStock')->where($map)->getField('goods_number');
                        $save = array();
                        $save['goods_number'] = $goods_number - $act_num;
                        M('ShopsGoodsStock')->where($map)->save($save);
                        $shop_out_name=idtoname($order_info['shop_id_out'],'Shops','name');
                        if ($act_num > 0) {
                            $reduce_desc = '货单号' . $order_info['sn'] . '店铺' . $shop_out_name . '货流调出仓库减少库存';
                            change_stock_log($order_info['shop_id_out'], $id, ($goods_number ? $goods_number : 0), $v['goods_id'], $act_num, 1, $reduce_desc, 4, $attr_key);
                        } elseif ($act_num < 0) {
                            $reduce_desc = '货单号' . $order_info['sn'] . '店铺' . $shop_out_name . '货流调出仓库增加库存';
                            $act_num = $v['freight_num'] - $v['fact_num'];
                            change_stock_log($order_info['shop_id_out'], $id, ($goods_number ? $goods_number : 0), $v['goods_id'], $act_num, 0, $reduce_desc, 4, $attr_key);
                        }
                    }
                }
            }else{
                if ($order_info['type'] == 4 && $order_info['shop_id_out']) {
                    foreach ($info as $k => $v) {
                    //存商品库存表
                        $map = array();
                        $map['goods_id'] = $v['goods_id'];
                        $map['shop_id'] = $order_info['shop_id_out'];//给出库仓库增加库存
                        $map['goods_stock'] = empty($v['goods_attr_sn']) ? 0 : $v['goods_attr_sn'];
                        $stock_cfg = M('ShopsGoodsStock')->where($map)->getField('goods_number');
                        $savedata = array();
                        $savedata['goods_number'] = $stock_cfg + $v['fact_num'];
                        M('ShopsGoodsStock')->where($map)->save($savedata);
                        $shop_out_name=idtoname($order_info['shop_id_out'],'Shops','name');
                        $desc = '货单号' . $order_info['sn'].'拒绝收货出库仓库'.$shop_out_name.'增加库存';
                        $attr_key = $v['goods_attr_sn'];
                        change_stock_log($order_info['shop_id_out'], $id, ($stock_cfg ? $stock_cfg : 0), $v['goods_id'], $v['fact_num'], 0, $desc, 4, $attr_key);
                    }
                }
            }
        }
    }

    /**
     * 减少仓库库存（用于调货，出库）
     * @param $id
     * @param $type //出库类型，0普通出库1仓库退货
     */
    public function reduce_storage($id){
        $map=array();
        $map['id']=$id;
        $order=M('InvoicingOrder')->where($map)->field('shop_id_in,shop_id_out,sn,type,is_transfer')->find();
        if(!empty($order)) {
            $map=array();
            $map['order_id']=$id;
            $info=M('InvoicingGoods')->where($map)->field('goods_id,goods_sn,freight_num,fact_num,shop_id,supplier_id,goods_attr_sn')->select();
            foreach ($info as $k => $v) {
                //存商品库存表
                $map=array();
                $map['goods_id']=$v['goods_id'];
                $map['shop_id']=$order['shop_id_out'];
                $map['goods_stock']=empty($v['goods_attr_sn'])?0:$v['goods_attr_sn'];
                $goods_number= M('ShopsGoodsStock')->where($map)->getField('goods_number');
                if($order['is_transfer']==1 || $order['type']==4){
                    M('ShopsGoodsStock')->where($map)->setDec('goods_number',$v['freight_num']);
                }else{
                    M('ShopsGoodsStock')->where($map)->setDec('goods_number',$v['fact_num']);
                }
                $type=5;
                $shop_name=idtoname($order['shop_id_out'],'Shops','name');
                if($order['type'] == 2) {
                    $desc = '货单号' . $order['sn'] . '店铺'.$shop_name.'普通出库减少库存';
                }elseif($order['type'] == 3){
                    $desc = '货单号' . $order['sn'] .'店铺'.$shop_name. '仓库退货减少库存';
                    $type=6;
                }elseif($order['type'] == 4){
                    $desc = '货单号' . $order['sn'] .'店铺'.$shop_name. '货流调出减少库存';
                    $type=4;
                }
                $attr_key=$v['goods_attr_sn'];
                if($order['is_transfer']==1 || $order['type']==4){
                    change_stock_log($order['shop_id_out'],$id,$goods_number,$v['goods_id'],$v['freight_num'],1,$desc,$type,$attr_key);
                }else{
                    change_stock_log($order['shop_id_out'],$id,$goods_number,$v['goods_id'],$v['fact_num'],1,$desc,$type,$attr_key);
                }
            }
        }
    }

    /**
     * 供货商分单
     * @param $id
     * @param array $supplier_id
     * @return array
     */
    public function separate($id,$supplier_id=array()){
        $return=array('status'=>0,'msg'=>'');
        if(empty($id)){$return['msg']='参数错误'; return $return;}
        $map=array();
        $map['id']=$id;
        $map['status']=array('in','0,1');
        $order_info=M('InvoicingOrder')->where($map)->field(true)->find();
        if($order_info) {
            $map = array();
            $map['order_id'] = $id;
            $now_info=M('InvoicingGoods')->where($map)->field(true)->select();
            foreach ($now_info as $key => $value) {
                $now_save['id']=$value['id'];
                $now_save['supplier_id']=$supplier_id[$key];
                M('InvoicingGoods')->save($now_save);
            }
            $info = M('InvoicingGoods')->where($map)->field('sum(fact_num) as count_num,sum(all_money) as sum_money,supplier_id')->group('supplier_id')->select();
            foreach ($info as $k => $v) {
                $savedata = array();
                $savedata['type'] = $order_info['type'];
                $savedata['mtype'] = $order_info['mtype'];
                $savedata['all_money'] = $v['sum_money'];
                $savedata['shop_id_in'] = $order_info['shop_id_in'];
                $savedata['supplier_id'] = $v['supplier_id'];
                $savedata['count'] = $v['count_num'];
                $savedata['add_time'] = $order_info['add_time'];
                $savedata['best_time'] = $order_info['best_time'];
                $savedata['update_time'] = $order_info['update_time'];
                $savedata['status'] = $order_info['status'];
                $savedata['remarks'] = $order_info['remarks'];
                $savedata['is_separate'] = 1;
                $res=M('InvoicingOrder')->add($savedata);
                if($res){
                    $data=array();
                    $map=array();
                    $map['order_id']=$order_info['id'];
                    $map['supplier_id']=$v['supplier_id'];
                    $data['order_id']=$res;
                    M('InvoicingGoods')->where($map)->save($data);
                    M('InvoicingDetail')->where($map)->save($data);
                }
            }
            if($res){
                $map=array();
                $map['id']=$id;
                $result=M('InvoicingOrder')->where($map)->delete();
            }
            if($res && $result){
                $return['msg']='分单成功';
                $return['status']=1;
                return $return;
            }else{
                $return['msg']='分单失败';
                return $return;
            }
        }
    }

    /**
     * 作废订单或拒绝订单操作
     * @param $id 订单id
     * @param int $type 0拒绝收货 1作废订单
     * @return array
     */
    public function cancel_order($id,$type=0){
        $return=array('status'=>0,'msg'=>'');
        if(empty($id)){$return['msg']='参数错误'; return $return;}
        $map=array();$map['id']=$id;
        $order_info=M('InvoicingOrder')->where($map)->field('id,type,shop_id_in,pay_code,is_pay,pay_status')->find();
        if(empty($order_info)){$return['msg']='订单不存在'; return $return;}
        if($type==1){
            if($order_info['type']==0) $map['status']=array('in','0,1');
            if($order_info['type']==1) $map['status']=0;
            if($order_info['type']==4) $map['status']=1;
        }else{
            $map['status']=2;
        }
        $count=M('InvoicingOrder')->where($map)->count();
        if($count>0){
            $savedata=array();
            if($type==1){$savedata['status']=5;}
            else{$savedata['status']=4;}
            $res=M('InvoicingOrder')->where($map)->save($savedata);
            if($res){
                $map=array();
                $savedata=array();
                $map['order_id']=$id;
                if($type==1){
                    if($order_info['type']==1) $map['status']=0;
                    if($order_info['type']==4) $map['status']=1;
                    $savedata['status']=5;
                } else{
                    $map['status']=2;
                    $s_map=array();$s_map['id']=$order_info['shop_id_in'];
                    $transfer_type=M('Shops')->where($s_map)->getField('transfer_type');
                    if($transfer_type==1) $savedata['audit_status']=0;
                    $savedata['status']=4;
                }
                M('InvoicingGoods')->where($map)->save($savedata);
                if($type==0){
                    if($order_info['type']==4){
                        $this->add_storage($id,1);
                    }
                    $map=array();
                    $map['order_id']=$id;
                    $map['status']=0;
                    $savedata=array();
                    $savedata['status']=4;
                    M('InvoicingDetail')->where($map)->save($savedata);
                }
                if($order_info['pay_code']!='HANCHAO_DAOFU' && $order_info['is_pay']==1 && $order_info['pay_status']==3) {
                    if ($type == 1) $this->return_shop_money($order_info['shop_id_in'], $order_info['id'], 1);
                    else {
                        if ($transfer_type != 1) {
                            $this->return_shop_money($order_info['shop_id_in'], $order_info['id'], 2);
                        }
                    }
                }
                $return['status']=1;
                $return['msg']='操作成功';
                return $return;
            }else{
                $return['msg']='操作失败';
                return $return;
            }
        }else{
            if($type==1){$return['msg']='此订单不允许作废';}
            else{$return['msg']='此订单不符合拒绝收货的条件';}
            return $return;
        }
    }

    /**
     * 确认收货、确认配货更改订单
     * @param $postdata
     * @param int $is_prepare 0确认收货 1确认配货
     * @return mixed
     */
    public function update_order($postdata,$is_prepare=0){
        $map=array();
        $map['id']=$postdata['id'];
        if($is_prepare==1){
            $map['shop_id_out']=$postdata['shop_id'];
            $map['status']=1;
        }else{
            $map['shop_id_in']=$postdata['shop_id'];
            $map['status']=2;
        }        
        $count=M('InvoicingOrder')->where($map)->count();
        if($count==0){$return['msg']='订单不满足条件'; $return['status']=0;return $return;}
        $map=array();$map['id']=$postdata['shop_id'];
        $transfer_type=M('Shops')->where($map)->getField('transfer_type');
        $map=array();$savedata=array();
        $count_total=$total_money=0;
        $map['id']=$postdata['id'];
        if($is_prepare==1){
            $map['status']=1;
            $savedata['status']=2;
        } else {
            $map['status']=2;
            $savedata['status']=3;
            //差异库存审核状态和时间
            if($transfer_type==1){
                $savedata['audit_status']=0;
            }else{
                $savedata['audit_status']=1;
                $savedata['audit_time']=NOW_TIME;
            }
        }
        $savedata['update_time']=NOW_TIME;
        if($postdata['fact_num']){
            foreach($postdata['fact_num'] as $k =>$v){
                $count_total+=$v;
                $total_money+=format_decimal($v*$postdata['supply_price'][$k]);
            }
        }
        $savedata['count']=$count_total;
        $savedata['all_money']=$total_money;
        $res=M('InvoicingOrder')->where($map)->save($savedata);
        if($res){
            foreach($postdata['fact_num'] as $k => $v){
                $map=array();
                $map['order_id'] = $postdata['id'];
                $savedata = array();
                if($is_prepare==1) $savedata['status']=2;
                else $savedata['status'] = 3;
                $savedata['update_time']=NOW_TIME;
                $map['goods_id']=$postdata['goods_id'][$k];
                $map['goods_attr_sn']=empty($postdata['goods_attr_sn'][$k])?'':$postdata['goods_attr_sn'][$k];
                if($is_prepare==1){
                    $savedata['freight_num']=$v;
                }else{
                    $savedata['fact_num']=$v;
                    $freight_num=M('InvoicingGoods')->where($map)->getField('freight_num');
                    $savedata['differ_num']=floatval($v)-floatval($freight_num);
                }
                $savedata['all_money']=format_decimal($v*$postdata['supply_price'][$k]);
                if($transfer_type==1) $savedata['audit_status']=0;
                else $savedata['audit_status']=1;
                M('InvoicingGoods')->where($map)->save($savedata);
                $map=array();
                $map['id']=$postdata['id'];
                $map['shop_id_in']=$postdata['shop_id'];
                $map['status']=3;
                $info=M('InvoicingOrder')->where($map)->field('type,shop_id_out,is_transfer,all_money,pay_code,is_pay,pay_status')->find();
                /*是否需要退款start*/
                if($is_prepare==0 && $info['pay_code']!='HANCHAO_DAOFU' && $info['is_pay']==1 && $info['pay_status']==3) {
                    if($info['type']==4 && $info['is_transfer']==1){
                        $money=$info['all_money'];
                        $change_desc_out='订货订单确认收货，出库店铺'.idtoname($info['shop_id_out'],'Shops','name').'余额增加';
                        shop_balance_log($info['shop_id_out'],$money,1,10,$change_desc_out,'');
                    }
                    if ($transfer_type != 1) {
                        $this->return_shop_money($postdata['shop_id'], $postdata['id']);
                    }
                }
                /*是否需要退款end*/
            }
            if($is_prepare==1){
                $shop_id=M('InvoicingOrder')->where('id='.$postdata['id'])->getField('shop_id_in');
                FrieghtPushSend($shop_id);
            }
            $return['status']=1;
            return $return;
        }else{
            if($is_prepare==1) $return['msg']='配货失败';
            else $return['msg']='入库失败';
            $return['status']=0;
            return $return;
        }
    }

    /**
     * 订货订单退款
     * @param $shop_id 订货仓库id
     * @param $order_id 订货订单id
     * @param int $is_return 订单订单状态 0确认收货 1作废 2拒绝
     * @param int $money 指定退款金额
     * @return bool
     */
    public function return_shop_money($shop_id,$order_id,$is_return=0,$money=0,$is_refuse=0){
        if(empty($shop_id) || empty($order_id)) return false;
        $map=array();
        $map['id']=$order_id;
        $map['shop_id']=$shop_id;
        if($is_return==0) $map['status']=3;//确认收货
        elseif($is_return==1) $map['status']=5;//作废
        elseif($is_return==2) $map['status']=4;//拒绝
        $map['_string'] = "type=0 OR (type=4 AND is_transfer=1)";
        $map['is_pay']=1;
        $map['pay_code']=array('neq','HANCHAO_DAOFU');
        $map['pay_status']=3;
        $order_info=M('InvoicingOrder')->where($map)->field('id,audit_status,shop_id_in,shop_id_out')->find();//查询满足退款条件的订单
        if(empty($order_info)) return false;
        $map=array();
        $map['order_id']=$order_info['id'];
        $order_goods=M('InvoicingGoods')->where($map)->field('price,supply_price,discount_extra,differ_num,request_num,freight_num,fact_num,audit_status')->select();
        $all_return_money=0;$differ_money=0;
        foreach($order_goods as $k => $v){
            $return_price=0;$return_num=0;
            $return_price=$v['price']-$v['discount_extra'];
            if($is_return==0){
                if($is_refuse==0) $return_num=$v['fact_num']-$v['request_num'];
                else $return_num=$v['freight_num']-$v['request_num'];
            }
            if($is_return==1 || $is_return==2){
                if($is_refuse==0)$return_num=$v['request_num'];
                else {
                    $return_num=$v['freight_num'];
                    $differ_num=$v['freight_num']-$v['request_num'];
                }
            }
            $differ_money+=format_decimal($differ_num*$return_price);
            $all_return_money+=format_decimal($return_price*$return_num);
        }
        if($money>0) $all_return_money=$money;
        if($is_return==1){
            $change_desc='订货订单作废,店铺'.idtoname($shop_id,'Shops','name').'余额增加';
            if($all_return_money!=0)shop_balance_log($shop_id,$all_return_money,1,10,$change_desc,'');
        }elseif( $is_return==2){
            if($is_refuse==0){
                $change_desc='订货订单拒绝,店铺'.idtoname($shop_id,'Shops','name').'余额增加';
                if($all_return_money!=0)shop_balance_log($shop_id,$all_return_money,1,10,$change_desc,'');
            }
            if ($is_refuse==1) {//订货转调货需要增加出库仓库金额
                if($differ_money<0){
                    $change_desc='订货订单拒绝,店铺'.idtoname($shop_id,'Shops','name').'余额增加';
                }
                if($differ_money>0){
                    $change_desc='订货订单拒绝,店铺'.idtoname($shop_id,'Shops','name').'余额减少';
                }
                if($all_return_money!=0)shop_balance_log($shop_id,$all_return_money,1,10,$change_desc,'');
                if ($order_info['shop_id_out']) {
                    $change_desc_out = '订货订单拒绝收货，店铺' . idtoname($order_info['shop_id_out'], 'Shops', 'name') . '余额增加';
                    shop_balance_log($order_info['shop_id_out'], $all_return_money, 1, 10, $change_desc_out, '');
                }
            }
        }else{
            if ($all_return_money < 0) {
                $change_desc = '订货订单确认收货库存差异，店铺' . idtoname($shop_id, 'Shops', 'name') . '余额增加';
                shop_balance_log($shop_id, abs($all_return_money), 1, 10, $change_desc, '');
                if ($order_info['shop_id_out']) {//订货转调货需要减少出库仓库金额
                    $change_desc_out = '订货订单确认收货库存差异，店铺' . idtoname($order_info['shop_id_out'], 'Shops', 'name') . '余额减少';
                    shop_balance_log($order_info['shop_id_out'], $all_return_money, 1, 10, $change_desc_out, '');
                }
            }
            if ($all_return_money > 0) {
                $change_desc = '订货订单确认收货库存差异，店铺' . idtoname($shop_id, 'Shops', 'name') . '余额减少';
                shop_balance_log($shop_id, -$all_return_money, 1, 10, $change_desc, '');
                if ($order_info['shop_id_out']) {//订货转调货需要增加出库仓库金额
                    $change_desc_out = '订货订单确认收货库存差异，店铺' . idtoname($order_info['shop_id_out'], 'Shops', 'name') . '余额增加';
                    shop_balance_log($order_info['shop_id_out'], $all_return_money, 1, 10, $change_desc_out, '');
                }
            }
        }
        return true;
    }

    /**
     * 更改账单明细（用于后台供货商对账时供货商对账操作）
     * @param $id 对账单id
     * @param int $status 对账状态0待确认，1待对账，2待结算，3已结算
     */
    public function update_invoicing_detail($postdata){
        $return=array('status'=>0,'msg'=>'');
        $id=$postdata['id'];
        $status=intval($postdata['status']);
        if(empty($id)){$return['msg']='未选中对账单';return $return;}
        $map=array('id'=>array('in',$id),'status'=>array('neq',$status));
        $count=M('InvoicingDetail')->where($map)->count();
        if($count>0){$return['msg']='选中对账单有非法数据';return $return;}
        $map=array('status'=>$status);
        $remarks=$postdata['remarks'];
        $now_time=NOW_TIME;
        $status=$status+1;
        $data=array('status'=>$status,'remarks'=>$remarks);
        if($status==2){$data['check_time']=$now_time;}
        elseif($status==3){$data['balance_time']=$now_time;}
        $pre_money_out=$fact_money=format_decimal($postdata['pre_money_out']);//剩余付款 /实际支付(结算加入日志才用)
        $all_money=0;//货流总价(结算加入日志才用)
        $supplier_id=0;//供货商id(结算加入日志才用)
        foreach($id as $v){
            $where=array('id'=>$v);
            $pre_money=M('InvoicingDetail')->where($where)->field('supplier_id,already_money,all_price')->find();
            $supplier_id=$pre_money['supplier_id'];
            $map['id']=$v;
            $all_money=$all_money+format_decimal($pre_money['all_price']);
            $money=format_decimal($pre_money['all_price'])-format_decimal($pre_money['already_money']);
            $data['already_money']=$money+format_decimal($pre_money['already_money']);
            $res=M('InvoicingDetail')->where($map)->save($data);
            if($res==false){break;}
            $pre_money_out=$pre_money_out-$money;
        }
        if($res!==false){
            if($status==3) {
                $data = array(
                    'supplier_id' => $supplier_id,
                    'all_money' => $all_money,
                    'fact_money' => $fact_money,
                    'add_time' => $now_time,
                    'remarks' => $remarks
                );
                M('InvoicingSupplierLog')->add($data);
            }
            $return=array('status'=>1);
        }else{
            $return['msg']='对账失败';
        }
        return $return;
    }
    /*进销存操作end*/

    /*搜索选择商品start*/
    /**
     * 精准搜索按照输入的编号搜索
     * @param $postdata
     * @return array|mixed
     */
    public function search_by_sn($postdata){
        $return=array('status'=>0,'msg'=>'');
        $sn=trim($postdata['sn']);
        if(empty($sn)){$return['msg']='请输入商品条形码';return $return;}
        if(empty($postdata['cate_id'])){$cate_id=0;}
        else{$cate_id=$postdata['cate_id'];}
        //是否是收银商品
        if(empty($postdata['is_cashier'])){$is_cashier=0;}
        else{$is_cashier=$postdata['is_cashier'];}
        if(empty($postdata['is_return_goods'])) $is_return_goods=0;
        else $is_return_goods=$postdata['is_return_goods'];
        $jizhong_config=$this->get_jizhong($postdata['shop_id']);
        if($postdata['is_shop']==1){
            if(substr($sn,0,2)==$jizhong_config['code']){
                $data=$this->search_jizhong($sn,$postdata['shop_id']);
                return $data;
            }else{
                $data=$this->only_select($sn,$cate_id,$postdata['shop_id'],$postdata['out_price'],$is_cashier,$is_return_goods,$postdata['is_shop']);
                return $data;
            }
        }else{
            $data=$this->only_select($sn,$cate_id,$postdata['shop_id'],$postdata['out_price'],$is_cashier,$is_return_goods,$postdata['is_shop']);
            //$data=$this->only_select($sn,$cate_id,$postdata['shop_id'],$postdata['out_price'],$is_cashier,$is_return_goods,$postdata['is_shop'],$postdata['suppliers_id']);
            return $data;
        }
    }

    /**
     * 模糊搜索
     * @param $postdata
     * @return mixed
     */
    public function search_by_keyword($postdata){
        $return=array('status'=>0,'msg'=>'');
        if($postdata['is_shop']==1){
            $result=$this->get_shop_goods($postdata,1);
            return $result;
        }else{
            $result=$this->get_goods($postdata,1);
            return $result;
        }
    }
    public function get_jizhong($shop_id=0){
        $return['code']=C('CASHIER_CODE');
        $return['jizhong']=C('CASHIER_JIZHONG');
        $return['jizhong_code']=C('CASHIER_JIZHONGCODE');
        if(!empty($shop_id)){
            $map=array();
            $map['id']=$shop_id;
            $map['status']=1;
            $jizhong_config=M('Shops')->where($map)->field('cashier_code,cashier_jizhong')->cache('ShopJizhong'.$shop_id)->find();
            if(!empty($jizhong_config['cashier_code'])) $return['code']=$jizhong_config['cashier_code'];
            if(!empty($jizhong_config['cashier_jizhong'])) $return['jizhong']=$jizhong_config['cashier_jizhong'];
        }
        return $return;
    }
    /**
     * 搜索计重商品
     * @param $sn
     */
    public function search_jizhong($sn,$shop_id){
        $return=array('status'=>0,'msg'=>'');
        if(empty($sn)) {$return['msg']='商品条码不能为空'; return $return;}
        $jizhong_config=$this->get_jizhong($shop_id);
        $cashier_code=$jizhong_config['code'];
        $cashier_jizhong=$jizhong_config['jizhong'];
        if(substr($sn,0,2)!=$cashier_code){$return['msg']='输入商品条码格式不正确'; return $return;}
        $new_sn=substr($sn,2,5);
        if($cashier_jizhong=='2-5-5z-1'){
            $goods_weight=substr($sn,7,5);
            $length=13;
        }
        if($cashier_jizhong=='2-5-5j-5z-1'){
            $goods_weight=substr($sn,12,5);
            $length=18;
        }
        if($cashier_jizhong=='2-5-5z-5j-1'){
            $goods_weight=substr($sn,7,5);
            $length=18;
        }
        if(strlen($sn)!=$length || CheckBarCode($sn)!=substr($sn,-1,1)){$return['msg']='输入商品条码格式不正确'; return $return;}
        $goods_number=$goods_weight/1000;
        $map=array();
        $map['a.goods_sn']=$new_sn;
        $map['a.is_type']=1;
        $map['a.publish_wait']=1;
        $map['a.is_delete']=0;
        $map['a.status']=1;
        $map['sg.shop_id']=$shop_id;
        $map['sgs.shop_id']=$shop_id;
        $map['sg.goods_type']=1;
        $map['sg.is_delete']=0;
        $map['sg.status']=1;
		$field='a.id,a.goods_sn,a.goods_name,a.market_price,a.shop_price,a.limit_count,a.lower_count,a.supply_price,sgs.goods_number';
        $join='';
        $join.=' LEFT JOIN __SHOPS_GOODS__ sg ON sg.goods_id=a.id';
        $join.=' LEFT JOIN __SHOPS_GOODS_STOCK__ sgs ON sgs.goods_id=sg.goods_id';
        $goods_info=M('Goods')->alias('a')->where($map)->join($join)->field($field)->find();
        if(empty($goods_info)){$return['msg']='无此商品或无库存'; return $return;}
        $goods_info['index']=$goods_info['id'].'-';
        $goods_info['jz_number']=floatval($goods_number);
        $goods_info['is_type']=1;
        $goods_info['stock']=floatval($goods_info['goods_number']);
        $goods_info['shop_name']=idtoname($shop_id,'Shops');
        $goods_info['active_id']=D('Pad/Cashier')->get_goods_activeid($goods_info['id'],$shop_id);
        $return['status']=1;
        $return['data']['count']=1;
        $return['data']['list']=$goods_info;
        return $return;
    }

    /**
     * 根据商品编号进行唯一查询
     * @param $sn
     * @param $cate_id
     * @param int $shop_id
     * @return array
     */
    //public function only_select($sn,$cate_id,$shop_id=0,$out_price='',$is_cashier=0,$is_return_goods=0,$is_shop=0,$suppliers_id=0){
    public function only_select($sn,$cate_id,$shop_id=0,$out_price='',$is_cashier=0,$is_return_goods=0,$is_shop=0){
        $return=array('status'=>0,'msg'=>'商品不存在！');
        $is_check_stock=C('SHOUYIN_JINSHOU');
        $map=array();
        $map['goods_attr_sn']=$sn;
        $count=M('GoodsAttrStock')->where($map)->count();
        if($count>1){$return['data']['count']=$count; $return['status']=1;return $return;}//如果没有输入的编号或是查询出来的数量大于1就返回走下边的流程
        if($count==1) {
            $attr_info = M('GoodsAttrStock')->where($map)->field('goods_id,attr_key,goods_attr_sn,attr_price')->find();
            $goods_id = $attr_info['goods_id'];
        }else{//精准搜索商品表
            $map=array();
            if($is_return_goods!=1) {
                $map['publish_wait'] = 1;
                $map['is_delete'] = 0;
                $map['status'] = 1;
            }
            if($is_cashier!=1) $map['sale_type'] = 0;
            else $map['is_offline']=1;
            if($is_shop==0) $map['is_dinghuo']=1;
            $map['goods_type']=5;
            $map['goods_sn']=$sn;
            //if(intval($suppliers_id)>0) $map['suppliers_id']=$suppliers_id;
            $goods_id = M('Goods')->where($map)->getField('id');
            if(empty($goods_id)){
                $map=array();
                $map['goods_sn']=$sn;
                $goods_id = M('GoodsMorecode')->where($map)->getField('goods_id');
            }
            //模糊搜索商品
            if(empty($goods_id)) {
                $map=array();
                if($is_return_goods!=1) {
                    $map['publish_wait'] = 1;
                    $map['is_delete'] = 0;
                    $map['status'] = 1;
                }
                if($is_cashier!=1) $map['sale_type'] = 0;
                $map['goods_type']=5;
                $map['goods_sn|goods_name|goods_code|goods_zhuji'] = array('like', '%' . (string)$sn . '%');
                $goods_ids=M('Goods')->where($map)->getField('id',true);
                $goods_count=count($goods_ids);
                if($goods_count>1){$return['data']['count']=$goods_count; $return['status']=1;return $return;}
                elseif($goods_count==0){return $return;}
                $goods_id=$goods_ids[0];
            }
            if(empty($goods_id)) {return $return;}
        }
        if(empty($attr_info['attr_key'])) $attr_info['attr_key']='';
        $map=array();
        $map['id']=$goods_id;
        if($is_return_goods!=1) {
            $map['publish_wait'] = 1;
            $map['is_delete'] = 0;
            $map['status'] = 1;
        }
        if($is_cashier!=1) $map['sale_type'] = 0;
        $map['goods_type']=5;
        if($is_shop==0) $map['is_dinghuo']=1;
        $field='id,cat_id,goods_sn,goods_name,supply_price,shop_price,suppliers_id,img,is_promote,promote_price,promote_id,is_type,limit_count,lower_count';
        $goods_info=M('Goods')->where($map)->field($field)->find();
        if(empty($goods_info))return $return;
        //查询店铺商品
        if($shop_id>0 && $is_shop==1){
            $map = array();
            $map['goods_id'] = $goods_id;
            $map['shop_id'] = $shop_id;
            if (!empty($attr_info['attr_key'])) $map['goods_stock'] = $attr_info['attr_key'];
            else $map['goods_stock'] = 0;
            $shop_goods = M('ShopsGoodsStock')->where($map)->field('goods_stock,goods_id')->find();
            //没有搜索到商品直接添加一条商品库存为0
            if(empty($shop_goods)){
                $map=array();
                $map['goods_id'] = $goods_id;
                $map['shop_id'] = $shop_id;
                $shop_goods = M('ShopsGoods')->where($map)->field(true)->find();
            }
            if(empty($shop_goods) && $is_cashier==0){$return['msg']='请先初始化库存'; return $return;}
            if(empty($shop_goods) && $is_cashier==1){
                $add=array();
                $add['goods_id'] = $goods_id;
                $add['goods_sn'] = $goods_info['goods_sn'];
                $add['suppliers_id'] = $goods_info['suppliers_id'];
                $add['shop_id'] = $shop_id;
                $add['addtime'] = NOW_TIME;
                $add['status'] = 1;
                $add['goods_type'] = 1;
                M('ShopsGoods')->add($add);
                $shop_goods=array();
                $shop_goods['goods_id'] = $goods_id;
                $shop_goods['goods_stock'] = empty($attr_info['attr_key'])?0:$attr_info['attr_key'];
                $shop_goods['suppliers_id'] = $goods_info['suppliers_id'];
                $shop_goods['shop_id'] = $shop_id;
                $shop_goods['goods_number'] = 0;
                $shop_goods['sell_count'] = 0;
                $shop_goods['addtime'] = NOW_TIME;
                $shop_goods['updatetime'] = NOW_TIME;
                $shop_goods['status'] = 1;
                M('ShopsGoodsStock')->add($add);
            }
            if($shop_goods['goods_stock']!=0){$goods_info['index'] = $shop_goods['goods_id'] . '-' . $shop_goods['goods_stock'];}
            else $goods_info['index'] = $shop_goods['goods_id'] . '-';
            $goods_info['attr_key']=$shop_goods['goods_stock'];
            $goods_info['name']=attr_key2name($shop_goods['goods_stock'],$goods_info['id']);
            $goods_number=D('Common/Cart')->shopgoodsstock($goods_info['id'],$shop_id,$shop_goods['goods_stock']);
            if($is_check_stock==1 && $goods_number['goods_number']<=0 ){ $return['msg']='商品库存不足'; return $return;}
            $goods_info['stock']=floatval($goods_number['goods_number']);
        }else{
            $goods_info['index'] = $goods_info['id'] . '-' . $attr_info['attr_key'];
            $goods_info['attr_key']=$attr_info['attr_key'];
            $goods_info['name']=attr_key2name($attr_info['attr_key'],$goods_info['id']);
        }
        //收银功能返回
        if($is_cashier){
            $memberinfo=array();
            $memberinfo['is_tmp']=0;
            $memberinfo['id']=0;
            $discount_price=D('Pad/Cashier')->get_min_price($shop_id,$goods_info['id'],$memberinfo);
            if($discount_price['price_type']!=3){
                $goods_info['is_promote']=0;
                $goods_info['promote_price']=0;
                $goods_info['promote_id']=0;
            }
            $map = array();
            $map['goods_id'] = $goods_info['id'];
            $user_price = M('MemberPrice')->where($map)->field('user_price,user_rank')->cache(true)->select();
            if(!empty($user_price)){
                $goods_info['member_price']=array();
                foreach($user_price as $k => $v){
                    $goods_info['member_price'][$v['user_rank']]=$v['user_price'];
                }
            }
            $goods_info['active_id']=D('Pad/Cashier')->get_goods_activeid($goods_info['id'],$shop_id);
        }
        if($goods_info['suppliers_id']) $goods_info['suppliers_name'] = idtoname($goods_info['suppliers_id'], 'Suppliers', 'name');
        else $goods_info['suppliers_name']='';
        if($attr_info['goods_attr_sn'])$goods_info['goods_attr_sn']=$attr_info['goods_attr_sn'];
        else $goods_info['goods_attr_sn']=0;
        if(!empty($attr_info['attr_price'])){
            $goods_info['shop_price']=$attr_info['attr_price'];
        }
        if(!empty($out_price) && is_numeric($out_price)){
            $postdata=array(
                'out_price'=>$out_price,
                'goods_id'=>$goods_info['id'],
                'shop_id'=>$shop_id,
                'attr_key'=>$goods_info['attr_key']
            );
            $goods_info['supply_price']=$this->count_goods_price($postdata);
        }else{
            $postdata=array(
                'goods_id'=>$goods_info['id'],
                'shop_id'=>$shop_id,
                'attr_key'=>$goods_info['attr_key']
            );
            $goods_info['supply_price']=$this->new_count_goods_price($postdata);
        }
        $unit=$goods_info['unit_id'];
        if($unit){
            $goods_info['unit_name']=idtoname($unit,'GoodsUnit','name');
        }else{
            $goods_info['unit_name']='无';
        }
        $goods_info['checked_goods']=0;
        $goods_info['shop_name']=idtoname($shop_id,'Shops');
        $return['data']['list'] = $goods_info;
        $return['data']['count']=1;
        $return['status']=1;
        return $return;
    }

    /**
     * 获取符合条件的商品
     * @param $sn 输入的商品关键字
     * @param $is_return 多条商品的时候是否返回商品列表 0 否 1是
     * @return mixed
     */
    private function get_goods($postdata,$is_return=0){
        $return=array('status'=>0,'msg'=>'');
        if($postdata['sn']=='undefined'){unset($postdata['sn']);}
        else{$sn=trim($postdata['sn']);}
        if(empty($postdata['cate_id'])){$cate_id=0;}
        else{$cate_id=$postdata['cate_id'];}
        if(empty($postdata['p']) || $postdata['p']<=0)$postdata['p']=1;
        $map=array();
        $map['is_dinghuo']=1;
        $map['publish_wait']=1;
        $map['is_delete']=0;
        $map['status']=1;
        $map['goods_type']=5;
        $map['sale_type'] = 0;
        if($cate_id){
            $PurchaseCategory=getcache('PurchaseCategory');
            $allson=$PurchaseCategory[$cate_id]['allson'];
            if(empty($allson)){
                $map['cat_id']=$cate_id;
            }else{
                $map['cat_id']=str_exists($allson,',')?array('in',$allson):$allson;
            }
        }
        $snlike= array('like', '%' . $sn . '%');
        if (is_numeric($sn)){
            $map['id|goods_sn|goods_name|goods_code'] = array(intval($sn),$snlike,$snlike,$snlike, '_multi' => true);
        } else if (!empty($sn)) {
            $map['goods_sn|goods_name|goods_code|goods_zhuji'] =$snlike;
        }
        $check=M('Goods')->where($map)->count();//检查有没有符合条件的商品
        if($check==0){$return['msg']='没有商品'; return $return;}
        $return['data']['count']=$check;
        if(empty($postdata['out_price']) || $postdata['out_price']==0){
             $field='id,goods_sn,goods_name,supply_price,shop_price,suppliers_id,img,is_type';
        }else{
             $field='id,goods_sn,goods_name,supply_price,shop_price,suppliers_id,img,is_type,purchase_price';
        }

        $listRows=10;
        $list=page_list('Goods',$map,'',$field,$listRows);
        if(empty($list['list'])){
			$return['msg']='没有更多的数据了!';return $return;
		}
        $total_page=ceil($list['count']/$listRows);
        $pre_page=$postdata['p']-1;
        if($postdata['p']>=$total_page){$next_page=0;}
        else{$next_page=$postdata['p']+1;}
        $listid=array();
        if(count($list['list']) > 1){
            foreach($list['list'] as $k=>$v){
                $listid[]=$v['id'];
                if(isset($postdata['out_price'])){
                    $postdata['goods_id']=$v['id'];
                    $list['list'][$k]['supply_price']=$this->count_goods_price($postdata);
                }else{
                    $postdata['goods_id']=$v['id'];
                    $list['list'][$k]['supply_price']=$this->new_count_goods_price($postdata);
                }
                $unit=idtoname($v['id'],'Goods','unit_id');
                if($unit){
                    $list['list'][$k]['unit_name']=idtoname($unit,'GoodsUnit','name');
                }else{
                    $list['list'][$k]['unit_name']='无';
                }
            }
            $count = ceil(count($listid)/2);//产品平均数取上
            $left = array_chunk($listid, $count, true)[0];//左边产品
        }else{
            $left[]=$list['list'][0]['id'];
            foreach($list['list'] as $k=>$v){
                $listid[]=$v['id'];
                if(isset($postdata['out_price'])){
                    $postdata['goods_id']=$v['id'];
                    $list['list'][$k]['supply_price']=$this->count_goods_price($postdata);
                }else{
                    $postdata['goods_id']=$v['id'];
                    $list['list'][$k]['supply_price']=$this->new_count_goods_price($postdata);
                }
                $unit=idtoname($v['id'],'Goods','unit_id');
                if($unit){
                    $list['list'][$k]['unit_name']=idtoname($unit,'GoodsUnit','name');
                }else{
                    $list['list'][$k]['unit_name']='无';
                }
            }
        }
        $map=array();
        $map['goods_id']=array('in',$listid);
        $goods_attrs = array();//当前供应商的属性组合的商品
        $attrs=M('GoodsAttrStock')->field('goods_id,attr_key,attr_price,stock_cfg,goods_attr_sn')->where($map)->select();
        foreach ($attrs as $v) {
            $goods_attrs[$v['goods_id']][] = $v;
        }
        foreach($list['list'] as $v){
            $v['index']=$v['id'] . '-';
            $v['shop_price']=$v['shop_price'];
            $v['supplier_price']=$v['supply_price'];
            $v['img']=thumb($v['img']);
            if($v['suppliers_id']) $v['suppliers_name']=idtoname($v['suppliers_id'],'Suppliers','name');
            else $v['suppliers_name']='无';
            $v['checked_goods']=0;
            $attr_arr=$attr_arrs=array();
            foreach($goods_attrs[$v['id']] as $vo) {
                $attr_arr=$v;
                $attr_arr['index']=$v['id'] . '-' . $vo['attr_key'];
                $attr_arr['goods_id']=$v['id'];
                if(isset($postdata['out_price'])) {
                    $postdata['goods_id']=$v['id'];
                    $postdata['attr_key']=$vo['attr_key'];
                    $attr_arr['supply_price']=$this->count_goods_price($postdata);
                }else{
                    $postdata['goods_id']=$v['id'];
                    $postdata['attr_key']=$vo['attr_key'];
                    $attr_arr['supply_price']=$this->new_count_goods_price($postdata);
                }
                if(!empty($vo['attr_price'])){
                    $attr_arr['shop_price']=$vo['attr_price'];
                }
                $attr_arr['name']=attr_key2name($vo['attr_key'],$v['id']);
                $attr_arr['goods_attr_sn']=$vo['goods_attr_sn']?$vo['goods_attr_sn']:'';
                $attr_arr['attr_key']=$vo['attr_key'];
                $attr_arr['checked_goods']=0;
                if($vo['attr_key'] && $attr_arr['name'])$attr_arrs[]=$attr_arr;
                if(!empty($attr_arrs)) $v['goods_attrs']=$attr_arrs;
            }
            if(in_array($v['id'],$left)){
                $left_list[]=$v;
            }else{
                $right_list[]=$v;
            }
        }
        $return['status']=1;
        $return['data']['page']=$list['page'];
        $return['data']['total_page']=$total_page;
        $return['data']['pre_page']=$pre_page;
        $return['data']['next_page']=$next_page;
        $return['data']['left_list']=$left_list;
        $return['data']['right_list']=$right_list;
        return $return;
    }

    /**
     * 获取符合条件的店铺商品
     * @param $sn 输入的商品关键字
     * @param $is_return 多条商品的时候是否返回商品列表 0 否 1是
     * @return mixed
     */
    private function get_shop_goods($postdata,$is_return=0){
        $return=array('status'=>0,'msg'=>'');
        $sn=$postdata['sn'];
        if(empty($postdata['cate_id'])){$cate_id=0;}
        else{$cate_id=$postdata['cate_id'];}
        if(empty($postdata['p']) || $postdata['p']<=0)$postdata['p']=1;
        $shop_id=$postdata['shop_id'];
		$map=array();$map['id']=$shop_id;
        $shop_name = idtoname($shop_id,'Shops','name');
        $map=array();
        $map['status']=1;
        $map['shop_id']=$shop_id;
        $shopgoodsids=M('ShopsGoodsStock')->where($map)->getField('goods_id',true);
        if(empty($shopgoodsids)){
            $return['msg']='没有查询到商品';
            return $return;
        }
        $map=array();
        if($postdata['is_return_goods']!=1) {//不是退货商品需要查询
            $map['publish_wait'] = 1;
            $map['is_delete'] = 0;
            $map['status'] = 1;
        }
        if($postdata['is_cashier']!=1) $map['sale_type'] = 0;
        else $map['is_offline']=1;
        $map['goods_type']=5;
        $map['id']=array('in',$shopgoodsids);
        if($cate_id){
            $PurchaseCategory=getcache('PurchaseCategory');
            $allson=$PurchaseCategory[$cate_id]['allson'];
            if(empty($allson)){
                $map['cat_id']=$cate_id;
            }else{
                $map['cat_id']=str_exists($allson,',')?array('in',$allson):$allson;
            }
        }
        $snlike= array('like', '%' . $sn . '%');
        if (is_numeric($sn)) {
            $map['id|goods_sn|goods_name|goods_code'] = array(intval($sn),$snlike,$snlike,$snlike, '_multi' => true);
        } else if (!empty($sn)) {
            $map['goods_sn|goods_name|goods_code|goods_zhuji'] =$snlike;
        }
        $check=M('Goods')->where($map)->count();//检查有没有符合条件的商品
        if($check==0){$return['msg']='没有商品'; return $return;}
        $return['data']['count']=$check;
        $field='id,cat_id,goods_sn,goods_name,supply_price,shop_price,suppliers_id,img,is_promote,promote_price,promote_id,limit_count,lower_count,is_type';
        $listRows=10;
        $list=page_list('Goods',$map,'',$field,$listRows);
        if(empty($list['list'])){
			$return['msg']='没有更多的数据了!';return $return;
		}
        $total_page=ceil($list['count']/$listRows);
        $pre_page=$postdata['p']-1;
        if($postdata['p']>=$total_page){$next_page=0;}
        else{$next_page=$postdata['p']+1;}
        $listid=array();
        if(count($list['list']) > 1){
            foreach($list['list'] as $k=>$v){
                $listid[]=$v['id'];
                if(isset($postdata['out_price'])){
                    $postdata['goods_id']=$v['id'];
                    $list['list'][$k]['supply_price']=$this->count_goods_price($postdata);
                }else{
                    $postdata['goods_id']=$v['id'];
                    $list['list'][$k]['supply_price']=$this->new_count_goods_price($postdata);
                }
                $unit=idtoname($v['id'],'Goods','unit_id');
                if($unit){
                    $list['list'][$k]['unit_name']=idtoname($unit,'GoodsUnit','name');
                }else{
                    $list['list'][$k]['unit_name']='无';
                }
            }
            $count = ceil(count($listid)/2);//产品平均数取上
            $left = array_chunk($listid, $count, true)[0];//左边产品
        }else{
            $left[]=$list['list'][0]['id'];
            foreach($list['list'] as $k=>$v){
                $listid[]=$v['id'];
                if(isset($postdata['out_price'])){
                    $postdata['goods_id']=$v['id'];
                    $list['list'][$k]['supply_price']=$this->count_goods_price($postdata);
                }else{
                    $postdata['goods_id']=$v['id'];
                    $list['list'][$k]['supply_price']=$this->new_count_goods_price($postdata);
                }
                $unit=idtoname($v['id'],'Goods','unit_id');
                if($unit){
                    $list['list'][$k]['unit_name']=idtoname($unit,'GoodsUnit','name');
                }else{
                    $list['list'][$k]['unit_name']='无';
                }
            }
        }
        $map=array();
        $map['goods_id']=array('in',$listid);
        $map['shop_id']=$shop_id;
        $attrs=M('ShopsGoodsStock')->field('goods_id,goods_stock,goods_number')->where($map)->select();
        $stock_ids=$stock_id_number=array();
        foreach ($attrs as $v) {
            if($v['goods_stock']!=0)$stock_ids[]=$v['goods_id'];
            if($v['goods_number']>0)$stock_id_number[$v['goods_id']]=floatval($v['goods_number']);
        }
        foreach($list['list'] as $v){
            $v['goods_id']=$v['id'];
            $v['index']=$v['id'] . '-';
            $v['img']=thumb($v['img']);
            if($v['suppliers_id']) $v['suppliers_name']=idtoname($v['suppliers_id'],'Suppliers','name');
            else $v['suppliers_name']='无';
            if($postdata['is_cashier']){//收银返回
                $memberinfo=array();
                $memberinfo['is_tmp']=0;
                $memberinfo['id']=0;
                $discount_price=D('Pad/Cashier')->get_min_price($shop_id,$v['id'],$memberinfo);
                if($discount_price['price_type']!=3){
                    $v['is_promote']=0;
                    $v['promote_price']=0;
                    $v['promote_id']=0;
                }
                $map = array();
                $map['goods_id'] = $v['id'];
                $user_price = M('MemberPrice')->where($map)->field('user_price,user_rank')->cache(true)->select();
                if(!empty($user_price)){
                    $v['member_price']=array();
                    foreach($user_price as $key => $val){
                        $v['member_price'][$val['user_rank']]=$val['user_price'];
                    }
                }
                $v['active_id']=D('Pad/Cashier')->get_goods_activeid($v['id'],$shop_id);
            }
            $v['checked_goods']=0;
            if(in_array($v['id'],$stock_ids)){
                $map=array();
                $map['goods_id']=$v['id'];
                $map['shop_id']=$shop_id;
                $goods_huopin=M('ShopsGoodsStock')->where($map)->field(true)->select();
                $attr_arr=$attr_arrs=array();
                foreach($goods_huopin as $vo) {
                    $attr_arr=$v;
                    $attr_arr['index'] = $v['id'] . '-' . $vo['goods_stock'];
                    $attr_arr['goods_id']=$v['id'];
                    $attr_arr['name'] = attr_key2name($vo['goods_stock'],$v['id']);
                    $goods_number=D('Common/Cart')->shopgoodsstock($v['id'],$shop_id,$vo['goods_stock']);
                    //if($goods_number['goods_number'] < 0) $goods_number['goods_number']=0;
                    if($postdata['is_cashier']) $attr_arr['stock']=floatval($goods_number['goods_number']);
                    else $attr_arr['stock']=floatval($vo['goods_number']);
                    $attr_arr['attr_key']=$vo['goods_stock'];
                    if(isset($postdata['out_price'])) {
                        $postdata['goods_id'] = $v['id'];
                        $postdata['attr_key'] = $vo['goods_stock'];
                        $attr_arr['supply_price'] = $this->count_goods_price($postdata);
                    }else{
                        $postdata['goods_id']=$v['id'];
                        $postdata['attr_key'] = $vo['goods_stock'];
                        $attr_arr['supply_price']=$this->new_count_goods_price($postdata);
                    }
                    $map=array();
                    $map['goods_id']=$v['id'];
                    if($vo['goods_stock']==0) $map['attr_key']='';
                    else $map['attr_key']=$vo['goods_stock'];
                    $goods_attr=M('GoodsAttrStock')->where($map)->field('goods_attr_sn,attr_price')->find();
                    if($goods_attr['goods_attr_sn'])$attr_arr['goods_attr_sn']=$goods_attr['goods_attr_sn'];
                    if($goods_attr['attr_price']){
                        $attr_arr['shop_price']=$goods_attr['attr_price'];
                    }
                    $attr_arr['attr_price']=0;
                    $attr_arr['checked_goods']=0;

                    if($v['limit_count'] && ($attr_arr['stock'] > $v['limit_count'])){$v['is_red']=1;
                    }else if($v['lower_count'] && ($attr_arr['stock'] < $v['lower_count'])){$attr_arr['is_red']=1;
                    }else{$attr_arr['is_red']=0;}
                    $attr_arr['shop_name']=$shop_name;

                    if($vo['goods_stock']!=0 && $attr_arr['name']) $attr_arrs[] = $attr_arr;

                }  if(!empty($attr_arrs))$v['goods_attrs'] = $attr_arrs;
            }elseif($stock_id_number[$v['id']]){
                $v['stock']=floatval($stock_id_number[$v['id']]);
            }else{
                $goods_number=D('Common/Cart')->shopgoodsstock($v['id'],$shop_id);
                //if($goods_number['goods_number'] < 0) $goods_number['goods_number']=0;
                $v['stock']=floatval($goods_number['goods_number']);
            }
            if($v['limit_count'] && ($v['stock'] > $v['limit_count'])){
                $v['is_red']=1;
            }else if($v['lower_count'] && ($v['stock'] < $v['lower_count'])){
                $v['is_red']=1;
            }else{
                $v['is_red']=0;
            }
            $map_sg=array();
            $map_sg['goods_id']=$v['id'];
            $map_sg['shop_id']=$shop_id;
            $supply_price=M('ShopsGoods')->where($map_sg)->getField('avg_price');
            $v['avg_price'] = $supply_price>0?$supply_price:$v['supply_price'];
            $v['shop_name']=$shop_name;
            if(in_array($v['id'],$left)){
                $left_list[]=$v;
            }else{
                $right_list[]=$v;
            }
        }
        $return['status']=1;
        $return['data']['page']=$list['page'];
        $return['data']['total_page']=$total_page;
        $return['data']['pre_page']=$pre_page;
        $return['data']['next_page']=$next_page;
        $return['data']['left_list']=$left_list;
        $return['data']['right_list']=$right_list;
        return $return;
    }

    /**
     * 计算商品出货时的某种价格
     */
    public function count_goods_price($postdata){
        $out_price=$postdata['out_price'];//1成本价,2进货价,3销售价
        $goods_id=$postdata['goods_id'];
        $shop_id=$postdata['shop_id'];
        $attr_key=$postdata['attr_key'];
        $map=$data=array();
        switch($out_price){
            case 1://以最近进货价出库
                $map=array();
                $map['goods_id']=$goods_id;
                $map['shop_id']=$shop_id;
                $map['goods_attr_sn']=$attr_key?$attr_key:'';
                $price=M('InvoicingGoods')->where($map)->order('id desc')->getField('supply_price');
                if(empty($price)) $price=format_decimal(0);
                break;
            case 2://以平均进货价出库
                if($attr_key) {
                    $map = array();
                    $map['goods_id'] = $goods_id;
                    $map['attr_key'] = $attr_key ? $attr_key : '';
                    $goods_attr_sn = M('GoodsAttrStock')->where($map)->getField('goods_attr_sn');
                }else{
                    $map = array();
                    $map['id'] = $goods_id;
                    $goods_attr_sn = M('Goods')->where($map)->getField('goods_sn');
                }
                $map=array();
                $map['goods_id']=$goods_id;
                $map['shop_id']=$shop_id;
                $map['goods_sn']=$goods_attr_sn;
                $price=M('ShopsGoods')->where($map)->getField('avg_price');
                if(empty($price)) $price=format_decimal(0);
                break;
            case 3://以进货价调货
                $map=array();
                $map['id']=$goods_id;
                $price=M('Goods')->where($map)->getField('purchase_price');
                if(empty($price)) $price=format_decimal(0);
                break;
            case 4://以商品销售价出库、调货
                $map=array();
                $map['goods_id']=$goods_id;
                $map['attr_key']=$attr_key?$attr_key:'';
                $price=M('GoodsAttrStock')->where($map)->getField('attr_price');
                if(empty($price) || $price<=0) {
                    $map = array();
                    $map['id'] = $goods_id;
                    $price = M('Goods')->where($map)->getField('shop_price');
                }
                if(empty($price)) $price=format_decimal(0);
                break;
            case 5://以商品销售价价出库、调货
                $map=array();
                $map['id']=$goods_id;
                $price=M('Goods')->where($map)->getField('supply_price');
                if(empty($price)) $price=format_decimal(0);
                break;
            default:
                break;
        }
        return $price;
    }

    /**
     * 新的计算进价方法
     * @param $postdata
     * @return array
     */
    public function new_count_goods_price($postdata){
        $shop_id=$postdata['shop_id'];
        $goods_id=$postdata['goods_id'];
        $attr_key=$postdata['attr_key'];
        $map=array();
        $map['id']=$shop_id;
        $send_price=M('Shops')->where($map)->getField('send_price');
        switch($send_price){
            /*case 0://成本价
                $map['id']=$goods_id;
                $price=M('Goods')->where($map)->getField('supply_price');
                break;*/
            case 1://进货价
                $map=array();
                $map['id']=$goods_id;
                $price=M('Goods')->where($map)->getField('purchase_price');
                break;
            case 2://售价
                break;
            default:
                $map=array();
                $map['id']=$goods_id;
                $price=M('Goods')->where($map)->getField('supply_price');
                break;
        }
        if(empty($price) || $price<=0){
            $map=array();
            $map['goods_id']=$goods_id;
            $map['attr_key']=$attr_key?$attr_key:'';
            $price=M('GoodsAttrStock')->where($map)->getField('attr_price');
            if(empty($price) || $price<=0) {
                $map = array();
                $map['id'] = $goods_id;
                $price = M('Goods')->where($map)->getField('shop_price');
            }
        }
        return $price;
    }

    /*需要去掉的start*/
    /*
     * 出库操作目前只有shop文件夹再用
     * @param $postdata=array(
     * out_type; //出库类型，0普通出库1仓库退货
     * out_price; //出库价格，'0'=>'以最近进货价出库','1'=>'以平均进货价出库','2'=>'以商品销售价出库','3'=>'以商品批发价出库'
     * shop_id; //从某仓库出库
     * infos; //提交的数据
     * )
     */
    public function order_shipment_insert($postdata){
        $return=array('status'=>0,'msg'=>'');
        $goodslist=$postdata['infos'];
        if(empty($goodslist)){$return['msg']='请选择商品出货';return $return;}
        $shop_id=intval($postdata['shop_id']);
        if($shop_id<=0){$return['msg']='请选择出货仓库';return $return;}
        $now_time=NOW_TIME;
        $type=empty($postdata['out_type'])?2:3;
        $status=empty($postdata['status'])?0:intval($postdata['status']);
        $mtype=empty($postdata['mtype'])?0:intval($postdata['mtype']);
        $cashier_id=empty($postdata['cashier_id'])?0:intval($postdata['cashier_id']);
        $all_money=$all_count=0;
        foreach($goodslist['all_money'] as $k => $v){$all_money+=$v;}//计算订单的总价格
        $request_num=$goodslist['request_num']?$goodslist['request_num']:$goodslist['freight_num'];
        foreach($request_num as $k => $v){$all_count+=$v;}//计算订单总请求量
        $order_data=array(
            'sn'=>$this->invoicing_sn(),
            'update_time'=>$now_time,
            'type'=>$type,
            'mtype'=>$mtype,
            'pre_money'=>format_decimal(0),
            'count'=>floatval($all_count),
            'all_money'=>format_decimal($all_money),
            'shop_id_out'=>$shop_id,
            'cashier_id'=>$cashier_id,
            'add_time'=>$now_time,
            'status'=>$status,
            'remarks'=>$postdata['remarks']
        );
        $id=M('InvoicingOrder')->add($order_data);
        if($id<=0){$return['msg']='添加出货单失败';return $return;}

        //加入InvoicingGoods表
        $goods_list=array();
        $goods_status=empty($postdata['goods_status'])?0:intval($postdata['goods_status']);
        foreach($goodslist['goods_name'] as $k=>$v){
            $goods_list[$k]['order_id']=$id;
            $goods_list[$k]['goods_id']=$goodslist['goods_id'][$k];
            $goods_list[$k]['goods_name']=$v;
            $goods_list[$k]['goods_sn']=$goodslist['goods_sn'][$k];
            $goods_list[$k]['goods_attr_sn']=$goodslist['goods_attr_sn'][$k]?$goodslist['goods_attr_sn'][$k]:'';
            $goods_list[$k]['supply_price']=$goodslist['supply_price'][$k];
            $goods_list[$k]['shop_id']=$shop_id;
            $goods_list[$k]['supplier_id']=empty($goodslist['supplier_id'][$k])?0:$goodslist['supplier_id'][$k];
            $goods_list[$k]['storage_id']=empty($goodslist['storage_id'][$k])?1:$goodslist['storage_id'][$k];
            $goods_list[$k]['order_cashier_id']=$cashier_id;
            $goods_list[$k]['pre_money']=format_decimal(0);
            $goods_list[$k]['all_money']=empty($goodslist['all_money'][$k])?0:$goodslist['all_money'][$k];
            $goods_list[$k]['request_num']=empty($goodslist['request_num'][$k])?0:floatval($goodslist['request_num'][$k]);
            $goods_list[$k]['freight_num']=empty($goodslist['freight_num'][$k])?floatval($goods_list[$k]['request_num']):floatval($goodslist['freight_num'][$k]);
            $goods_list[$k]['fact_num']=empty($goodslist['fact_num'][$k])?floatval($goods_list[$k]['freight_num']):floatval($goodslist['fact_num'][$k]);
            $goods_list[$k]['status']=$goods_status;
            $goods_list[$k]['order_time']=$now_time;
        }
        $result=M('InvoicingGoods')->addAll($goods_list);
        if($result!=false){
            //减少库存并记录出库记录
            $this->reduce_storage($id);
            //减少订单对账表
            if($type==3 && $mtype==0){
                $this->add_invoicing_detail($id,1,0,array(),1);//减少供货商对账单
            }
            $return=array('status'=>1,'msg'=>'已成功为仓库出货','id'=>$id);
        }else{
            $return['msg']='添加出货商品失败';
        }
        return $return;
    }

    /*
     * 调货操作目前只有shop文件夹再用
     * @param $postdata=array(
     * out_type; //出库类型，0普通出库1仓库退货
     * out_price; //出库价格，'0'=>'以最近进货价出库','1'=>'以平均进货价出库','2'=>'以商品销售价出库','3'=>'以商品批发价出库'
     * shop_id; //从某仓库出库
     * infos; //提交的数据
     * )
     */
    public function order_move_begin($postdata){
        $return=array('status'=>0,'msg'=>'');
        $goodslist=$postdata['infos'];

        if(empty($goodslist)){$return['msg']='请选择商品出货';return $return;}
        $shop_id=intval($postdata['shop_id']);
        $in_shop_id=intval($postdata['in_shop_id']);
        if($shop_id<=0){$return['msg']='请选择出货仓库';return $return;}
        if($in_shop_id<=0){$return['msg']='请选择入货仓库';return $return;}

        $now_time=NOW_TIME;
        $type=$postdata['out_type'];
        $status=empty($postdata['status'])?0:intval($postdata['status']);
        $mtype=empty($postdata['mtype'])?0:intval($postdata['mtype']);
        $cashier_id=empty($postdata['cashier_id'])?0:intval($postdata['cashier_id']);
        $all_money=$all_count=0;
        foreach($goodslist['all_money'] as $k => $v){$all_money+=$v;}//计算订单的总价格
        $request_num=$goodslist['request_num']?$goodslist['request_num']:$goodslist['freight_num'];
        foreach($request_num as $k => $v){$all_count+=$v;}//计算订单总请求量
        $order_data=array(
            'sn'=>$this->invoicing_sn(),
            'update_time'=>$now_time,
            'type'=>$type,
            'mtype'=>$mtype,
            'pre_money'=>format_decimal(0),
            'count'=>floatval($all_count),
            'all_money'=>format_decimal($all_money),
            'shop_id_out'=>$shop_id,
            'shop_id_in'=>$in_shop_id,
            'cashier_id'=>$cashier_id,
            'add_time'=>$now_time,
            'status'=>1,
            'type'=>4,
            'remarks'=>$postdata['remarks']
        );
        $id=M('InvoicingOrder')->add($order_data);
        if($id<=0){$return['msg']='添加出货单失败';return $return;}

        //加入InvoicingGoods表
        $goods_list=array();
        $goods_status=empty($postdata['goods_status'])?0:intval($postdata['goods_status']);
        foreach($goodslist['goods_name'] as $k=>$v){
            $goods_list[$k]['order_id']=$id;
            $goods_list[$k]['goods_id']=$goodslist['goods_id'][$k];
            $goods_list[$k]['goods_name']=$v;
            $goods_list[$k]['goods_sn']=$goodslist['goods_sn'][$k];
            $goods_list[$k]['goods_attr_sn']=$goodslist['goods_attr_sn'][$k]?$goodslist['goods_attr_sn'][$k]:'';
            $goods_list[$k]['supply_price']=$goodslist['supply_price'][$k];
            $goods_list[$k]['shop_id']=$shop_id;
            $goods_list[$k]['supplier_id']=empty($goodslist['supplier_id'][$k])?0:$goodslist['supplier_id'][$k];
            $goods_list[$k]['storage_id']=empty($goodslist['storage_id'][$k])?1:$goodslist['storage_id'][$k];
            $goods_list[$k]['order_cashier_id']=$cashier_id;
            $goods_list[$k]['pre_money']=format_decimal(0);
            $goods_list[$k]['all_money']=empty($goodslist['all_money'][$k])?0:$goodslist['all_money'][$k];
            $goods_list[$k]['request_num']=floatval($goodslist['freight_num'][$k]);
            $goods_list[$k]['freight_num']=floatval($goodslist['freight_num'][$k]);
            $goods_list[$k]['fact_num']=empty($goodslist['fact_num'][$k])?floatval($goods_list[$k]['freight_num']):floatval($goodslist['fact_num'][$k]);
            $goods_list[$k]['status']=$goods_status;
            $goods_list[$k]['order_time']=$now_time;
        }
        $result=M('InvoicingGoods')->addAll($goods_list);
        if($result!=false){
            FrieghtPushSend($shop_id);
            $return=array('status'=>1,'msg'=>'已成功向仓库发起调货通知','id'=>$id);
        }else{
            $return['msg']='添加出货商品失败';
        }
        return $return;
    }
    /*需要去掉的end*/

    /*打印start*/
    /**
     *打印设置（订货调货进货，货流通知）
     */
    public function invoicing_print_info($post){
        $return = array('status' => 1);
        $set=array();
        $shop_id=$post['shop_id'];
        $result = D('Shop/InvoicingOrder')->order_info($post);//查询订单以及商品信息
        if($result['status']==0){return $result;}
        //得到需要的商品信息
        foreach($result['data']['order_goods'] as $key=>$val){
            $attr_name='';
            $attr_name=attr_key2name($val['goods_attr_sn'],$val['goods_id']);
            $val['goods_name']=str_replace("•","·",$val['goods_name']);
            $goods_list[$key]['goods_name']=$val['goods_name'].$attr_name."(".$val['goods_sn'].")";
            $goods_list[$key]['goods_price']=$val['supply_price'];
            if(floatval($val['request_num'])) {$goods_list[$key]['goods_number']=floatval($val['request_num']);}
            if(floatval($val['freight_num'])){$goods_list[$key]['goods_number']=floatval($val['freight_num']);}
            if(floatval($val['fact_num'])){$goods_list[$key]['goods_number']=floatval($val['fact_num']);}
            //$goods_list[$key]['goods_number']=floatval(empty($val['freight_num'])?$val['request_num']:$val['freight_num']);
            $goods_list[$key]['all_price']=format_decimal($goods_list[$key]['goods_number']*$val['supply_price']);
        }
        //查询店铺的打印配置
        $map=array();
        $map['id']=$shop_id;
        $shop_info=M("Shops")->where($map)->field('printer_type,machine_code,print_template,print_tpl_id')->find();
        if(!empty($post['deviceId'])){
            $mod=M('PrintDevice');
            $map=array();
            $map['deviceid']=$post['deviceId'];
            $check=$mod->where($map)->count("id");
            if($check) {
                $print_arr=array();
                $print_arr=$mod->where($map)->field(true)->find();
                if(!empty($print_arr)){
                    if(!empty($print_arr['printer_type']))$shop_info['printer_type']=$print_arr['printer_type'];
                    if(!empty($print_arr['machine_code']))$shop_info['machine_code']=$print_arr['machine_code'];
                    if(!empty($print_arr['printer_ip']))$shop_info['printer_ip']=$print_arr['printer_ip'];
                    if(!empty($print_arr['port']))$shop_info['port']=$print_arr['port'];
                    if(!empty($print_arr['print_tpl_id']))$shop_info['print_tpl_id']=$print_arr['print_tpl_id'];
                    if(!empty($print_arr['print_template']))$shop_info['print_template']=$print_arr['print_template'];
                }
            }
        }else{
            if(str_exists($shop_info['printer_type'],'Jiabo')) $shop_info['printer_ip']=$shop_info['machine_code'];
        }
        $map = array();
        $map['id'] = 5;
        $info = M('TplReceipt')->where($map)->field(true)->find();//获取充值订单的打印模板
        if(empty($info)) {$return['msg']='小票模板错误'; $return['status']=0; return $return;}
        $tpl = json_decode($info['tpl_info'], true);
        //打印设置项，如果店铺有单独打印设置按照店铺的。没有单独打印设置就按照公共打印设置
        if($shop_info['print_template']){
            $set=json_decode($shop_info['print_template'], true);
        }else{
            $set = json_decode($info['set_info'], true);
        }
        if (!empty($set)) {
            foreach ($tpl as $k => $v) {
                if ($set['is_show'] == 0) {
                    if ($v['type'] == 'qrcode') {
                        unset($tpl[$k]);
                    }
                }
            }
        }
        $set['print_tpl_id']=1;
        if($post['type_id']==1){$set['type_id']=1;}
        if(empty($shop_info['printer_type'])){$shop_info['printer_type']='Shangmi';}
        $new_printer_type=explode("(", $shop_info['printer_type']);
        $printer_type=$new_printer_type[0];
        if($printer_type=='usb-Xprinter')$printer_type='Jiabo';
        $print = new \Common\Vendor\Printtpl($printer_type);//Local Yilianyun Shangmi
        $cashier_name='';
        if($result['data']['cashier_id']) $cashier_name=idtoname($result['data']['cashier_id'],'ShopsAccount','login_name');
        //获取小票底部二维码
        if(C('WEIXIN_PUBLIC_NUMBER_URL')){
            $qrcode_url=C('WEIXIN_PUBLIC_NUMBER_URL');
        }else{
            $wx = new \Common\Vendor\Weixinopen;
            $res_wx=$wx->get_authorizer_info();
            if(!empty($res_wx['authorizer_info']['user_name'])){
                $qrcode=$wx->get_wxqrcode($res_wx['authorizer_info']['user_name']);
                if(!empty($qrcode) && str_exists($qrcode,'weixin.qq.com'))$qrcode_url=$qrcode;
                if(C('WEIXIN_PUBLIC_NUMBER_URL') != $qrcode_url && strlen($qrcode_url)<=80){
                    $map = $save = array();
                    $map['name'] = 'WEIXIN_PUBLIC_NUMBER_URL';
                    $save['value'] = $qrcode_url;
                    M('Config')->where($map)->save($save);
                }
            }
        }
        if($result['data']['type']==0){$type='订货';}
        if($result['data']['type']==1){$type='进货';}
        if($result['data']['type']==2){$type='出库';}
        if($result['data']['type']==3){$type='退货';}
        if($result['data']['type']==4){$type='调货';}
        $map=array();
        $map['order_id']=$result['data']['id'];
        $pre_money=M('InvoicingDetail')->where($map)->sum('pre_money	');
        if($set['is_show']==0) $set['description']='';
        //生成打印模板需要的数据
        if(empty($result['data']['sn']))$result['data']['sn']=$result['data']['id'];
        $data = array(
            'shopname' => empty($set['shopname'])?idtoname($shop_id, "Shops", 'name'):$set['shopname'],//店铺名称
            'ordertype' => $type,
            'ordersn' => $result['data']['sn'],//订单号
            'addtime' => time_format($result['data']['add_time']),//交易时间
            'cashier' => $cashier_name,//收银员名字
            'goodslist' => $goods_list,//商品列表
            'zongji' => format_decimal($result['data']['all_money']),//总计
            'all_num' => floatval($result['data']['count']),//总数量
            'best_time' => time_format($result['data']['best_time'],'Y-m-d'),
            'pre_money' => format_decimal($pre_money),
            'temp' => $result['data']['remarks'] ? $result['data']['remarks'] : "",//备注
            'bottom_temp' => $set['temp'] ? $set['temp'] : '',//小票底部文案
            'description' => $set['description'],
            'qrcode_url' => $qrcode_url,//二维码
        );
        $print->setConfig($set);
        $text = $print->fetch($tpl, $data);
        //易连云小票需要添加终端号
        if ($printer_type == 'Yilianyun') {
            if (empty($shop_info['machine_code'])) {
                $return['status'] = 0;
                $return['msg'] = '添加打印机终端号';
                return $return;
            }
            $print = doPrint($shop_info['machine_code'], $text, $result['data']['sn']);
            $print['status'] = $print['status'] == 0 ? 3 : $print['status'];
            $print['msg'] = empty($print['msg']) ? $print['info'] : $print['msg'];
            return $print;
            //$this->ajaxReturn($print);
            //$return['data'] = $text;
        } else {
            $return['data'] = json_decode($text,true);
            return $return;
        }
    }
    /**
     * 报损打印
     */
    public function bad_print_info($getdata){
        $return=array('status'=>1,'msg'=>'');
        //$getdata=I('post.');
        $id=intval($getdata['id']);
        if(empty($id)){$return['msg']='参数错误';$return['status']=0;return $return;}
        $map=array('id'=>$id,'info_type'=>1);
        $field='bad_all_money,remarks,addtime,type_id,id';
        $badinfo=M('StocktakingInfo')->where($map)->field($field)->find();//查询报损记录
        if(empty($badinfo)){$return['msg']='无报损记录';$return['status']=0;return $return;}
        $map=array('stocktaking_id'=>$id,'info_type'=>1);
        $field='goods_id,cate_id,supplier_id,shop_id,goods_name,goods_sn,goods_attr_sn,bad_money,bad_num';
        $list=M('StocktakingGoods')->where($map)->field($field)->select();
        $goods_list=array();
        foreach($list as $key=>$val){
            $attr_name=attr_key2name($val['goods_attr_sn'],$val['goods_id']);
            $val['goods_name']=str_replace("•","·",$val['goods_name']);
            $goods_list[$key]['goods_name']=$val['goods_name'].$attr_name."(".$val['goods_sn'].")";
            $goods_list[$key]['goods_price']=format_decimal($val['bad_money']);
            $goods_list[$key]['goods_number']=floatval($val['bad_num']);
            $goods_list[$key]['all_price']=format_decimal($val['bad_money']*$val['bad_num']);
        }
        $map=array();
        $map['id']=$badinfo['type_id'];
        $shop_info=M("Shops")->where($map)->field('printer_type,machine_code,print_template,print_tpl_id')->find();
        if(!empty($getdata['deviceId'])){
            $mod=M('PrintDevice');
            $map=array();
            $map['deviceid']=$getdata['deviceId'];
            $check=$mod->where($map)->count("id");
            if($check) {
                $print_arr=array();
                $print_arr=$mod->where($map)->field(true)->find();
                if(!empty($print_arr)){
                    if(!empty($print_arr['printer_type']))$shop_info['printer_type']=$print_arr['printer_type'];
                    if(!empty($print_arr['machine_code']))$shop_info['machine_code']=$print_arr['machine_code'];
                    if(!empty($print_arr['printer_ip']))$shop_info['printer_ip']=$print_arr['printer_ip'];
                    if(!empty($print_arr['port']))$shop_info['port']=$print_arr['port'];
                    if(!empty($print_arr['print_tpl_id']))$shop_info['print_tpl_id']=$print_arr['print_tpl_id'];
                    if(!empty($print_arr['print_template']))$shop_info['print_template']=$print_arr['print_template'];
                }
            }
        }else{
            if(str_exists($shop_info['printer_type'],'Jiabo')) $shop_info['printer_ip']=$shop_info['machine_code'];
        }
        $map = array();
        $map['id'] = 5;
        $info = M('TplReceipt')->where($map)->field(true)->find();//获取充值订单的打印模板
        if(empty($info)) {$return['msg']='小票模板错误'; $return['status']=0; return $return;}
        $tpl = json_decode($info['tpl_info'], true);
        if($shop_info['print_template']){
            $set=json_decode($shop_info['print_template'], true);
        }else{
            $set = json_decode($info['set_info'], true);
        }
        if (!empty($set)) {
            foreach ($tpl as $k => $v) {
                if ($set['is_show'] == 0) {
                    if ($v['type'] == 'qrcode') {
                        unset($tpl[$k]);
                    }
                }
            }
        }
        $set['print_tpl_id']=1;
        if($getdata['type_id']==1){$set['type_id']=1;}
        if(empty($shop_info['printer_type'])){$shop_info['printer_type']='Shangmi';}
        $new_printer_type=explode("(", $shop_info['printer_type']);
        $printer_type=$new_printer_type[0];
        if($printer_type=='usb-Xprinter')$printer_type='Jiabo';
        $print = new \Common\Vendor\Printtpl($printer_type);//Local Yilianyun Shangmi
        $cashier_name='';
        if($badinfo['cashier_id']) $cashier_name=idtoname($badinfo['cashier_id'],'ShopsAccount','login_name');
        if(C('WEIXIN_PUBLIC_NUMBER_URL')){
            $qrcode_url=C('WEIXIN_PUBLIC_NUMBER_URL');
        }else{
            $wx = new \Common\Vendor\Weixinopen;
            $result=$wx->get_authorizer_info();
            if(!empty($result['authorizer_info']['user_name'])){
                $qrcode=$wx->get_wxqrcode($result['authorizer_info']['user_name']);
                if(!empty($qrcode) && str_exists($qrcode,'weixin.qq.com'))$qrcode_url=$qrcode;
                if(C('WEIXIN_PUBLIC_NUMBER_URL') != $qrcode_url && strlen($qrcode_url)<=80){
                    $map = $save = array();
                    $map['name'] = 'WEIXIN_PUBLIC_NUMBER_URL';
                    $save['value'] = $qrcode_url;
                    M('Config')->where($map)->save($save);
                }
            }
        }
        if($set['is_show']==0) $set['description']='';
        $data = array(
            'shopname' => empty($set['shopname'])?idtoname($badinfo['type_id'], "Shops", 'name'):$set['shopname'],
            'ordertype' => '报损',
            'cashier' => $cashier_name,
            'addtime' => time_format($badinfo['addtime']),
            'ordersn' => $badinfo['id'],
            'goodslist' => $goods_list,
            'zongji' => format_decimal($badinfo['bad_all_money']),
            'all_num' => floatval($badinfo['bad_all_num']),
            'temp' => $badinfo['remarks']?$badinfo['remarks']:"",
            'bottom_temp' => $set['temp'] ? $set['temp'] : '',
            'description' => $set['description'],
            'qrcode_url' => $qrcode_url,
        );
        $print->setConfig($set);
        $text = $print->fetch($tpl, $data);
        if ($printer_type == 'Yilianyun') {
            if (empty($shop_info['machine_code'])) {
                $return['status'] = 0;
                $return['msg'] = '添加打印机终端号';
                return $return;
            }
            $print = doPrint($shop_info['machine_code'], $text, $badinfo['id']);
            $print['status'] = $print['status'] == 0 ? 3 : $print['status'];
            $print['msg'] = empty($print['msg']) ? $print['info'] : $print['msg'];
            return $print;
            //$this->ajaxReturn($print);
            //$return['data'] = $text;
        } else {
            $return['data'] = json_decode($text);
            return $return;
        }
    }
    /*打印end*/
}
