<?php
/**
 * 进销存账单
 * @Copyright (C) 2017 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaol <xiaol@sina.cn>
 */

namespace Admin\Controller;
class InvoicingOrderController extends BaseController
{	
    public function _initialize(){
        parent::_initialize ();
       /* $is_auth=check_use_auth("Invoice");
        if($is_auth['status']==0){
            $this->error('该版本没有此权限',$is_auth['url']);return;
        }*/
        $this->order_status=array('0'=>'所有状态','1'=>'待审核','2'=>'配货中','3'=>'待入库','4'=>'已完成','5'=>'已拒绝','6'=>'已作废');//跟数据库里的差1
        $this->assign('order_status',$this->order_status);
        $this->order_type=array('0'=>'全部货单','1'=>'仓库采购','2'=>'其他入库','3'=>'其他出库','4'=>'供货商退货','5'=>'仓库调货','6'=>'销售出库','7'=>'报损出库');
        $this->assign('order_type',$this->order_type);
        $this->pay_type=array('0'=>'支付状态','1'=>'未支付','2'=>'已支付');
        $this->assign('pay_type',$this->pay_type);
        $this->out_price=array('1'=>'以最近进货价出库','2'=>'以平均进货价出库','4'=>'以商品销售价出库','5'=>'以商品成本价出库');
		//$this->move_price=array('3'=>'以进货价调货','4'=>'以商品销售价调货','5'=>'以商品成本价调货');
        $this->move_price=array('4'=>'以商品销售价调货','5'=>'以商品成本价调货');//jxr 2019.02.22
        $this->stock_status=array('0'=>'未审核','1'=>'审核通过','2'=>'拒绝','3'=>'作废');
        $this->chu_ortype=array('0'=>'全部货单','4'=>'调货出库','2'=>'其他出库','3'=>'供货商退货','6'=>'销售出库','7'=>'报损出库');
        $this->chu_status=array('0'=>'所有状态','1'=>'待审核','2'=>'配货中','4'=>'已完成','5'=>'已拒绝','6'=>'已作废');//跟数据库里的差1
        $this->assign('chu_ortype',$this->chu_ortype);
        $this->ru_ortype=array('20'=>'全部货单','21'=>'采购入库','1'=>'其他入库','4'=>'调货入库','5'=>'退货入库','8'=>'报溢入库');
        $this->ru_status=array('0'=>'所有状态','3'=>'待入库','4'=>'已完成','5'=>'已拒绝','6'=>'已作废');//跟数据库里的差1
        $this->assign('ru_ortype',$this->ru_ortype);
    }
    public function _before_delete(){exit;}
    /**
     * 货流管理列表
     */
    public function index(){
        $postdata = I('param.');
        $sn = $postdata['sn'];
        $status = $postdata['status'];
        $type = $postdata['type'];
        $shopid=$postdata['shopid'];
        $pay_type=$postdata['pay_status'];
        $is_balance=$postdata['is_balance'];
        $this->get_shops_list();
        if($sn){$map['sn'] = array('like','%'.$sn.'%');}
        if($status){$map['status'] = $status-1;}
        if($type){$map['type'] = $type-1;}
        if($pay_type==1) {$map['is_pay']=1;$map['pay_status']=array('elt',2);}
        if($pay_type==2) {$map['_string']="is_pay =0 OR pay_status = 3";}
        if($shopid && empty($is_balance)){$map_or=array('shop_id_in'=>$shopid,'shop_id_out'=>$shopid,'_logic'=>'or');$map['_complex']=$map_or;}
        if($shopid && $is_balance==1){$map['shop_id_in']=$shopid;}
        if($shopid && $is_balance==2){$map['shop_id_out']=$shopid;}
        if($postdata['data_from']){$map['add_time'][] = array('egt',strtotime($postdata['data_from']));}
        if($postdata['data_to']){$map['add_time'][] = array('elt',strtotime($postdata['data_to']));}
        $list = $this->lists('InvoicingOrder',$map);
        $goods_count=M('InvoicingOrder')->where($map)->count();
        $this->assign('list',$list);
        $this->assign('goods_count',$goods_count);
        $this->assign($postdata);
        $this->assign('out_price',$this->out_price);
        $this->display();
    }

    /**
     * 货流管理导出
     */
    public function export(){
        $id=I('get.id');if(empty($id)){return;}
        $map=array('id'=>$id);$field='count,all_money,type';
        $info=M('InvoicingOrder')->where($map)->field($field)->find();
        $map=array('order_id'=>$id);
        $field='goods_name,goods_sn,supplier_id,request_num,freight_num,fact_num,supply_price,all_money';
        $list=M('InvoicingGoods')->where($map)->field($field)->select();
        if($info['type'] == 2 || $info['type'] == 3){
            $title = array('商品名称', '商品编号', '供货商', '单位', '请求量', '出货量', '实收量', '出货价（元）', '小计（元）');
        }else {
            $title = array('商品名称', '商品编号', '供货商', '单位', '请求量', '进货量', '实收量', '进货价（元）', '小计（元）');
        }
        $data = array();
        foreach ($list as $k => $v) {
            $data[$k][] = $v['goods_name'];
            $data[$k][] = $v['goods_sn'];
            $data[$k][] = idtoname($v['supplier_id'], 'Suppliers');
            $data[$k][] = '无';
            $data[$k][] = floatval($v['request_num']);
            $data[$k][] = floatval($v['freight_num']);
            $data[$k][] = floatval($v['fact_num']);
            $data[$k][] = format_price($v['supply_price']);
            $data[$k][] = format_price($v['all_money']);
        }
        $data[]=array(
            '总计：'.($k+1).'种商品',
            '-',
            '-',
            '-',
            '-',
            floatval($info['count']),
            '-',
            '-',
            $info['all_money'],
        );
        export_csv('货流管理.csv',$title,$data);
        unset($title, $data);
        exit;
    }

    /**
     * 货流管理打印
     */
    public function order_print(){
        $id = I('get.id');
        $template = 'CARGO_LIST';
        $map=array('id'=>$id);
        $order_type=array('0'=>'订货单','1'=>'进货单','2'=>'出库单','3'=>'退货单','4'=>'调货单');
        $field='count,all_money,pre_money,add_time,sn,shop_id_in,type';
        $order_info = M('InvoicingOrder')->where($map)->field($field)->find();
        $order_info['type_name']=$order_type[$order_info['type']];
        $order_info['count']=floatval($order_info['count']);
        $map=array('order_id'=>$id);
        $field='goods_name,goods_sn,freight_num,supply_price,all_money,fact_num';
        $order_goods = M('InvoicingGoods')->where($map)->field($field)->select();
        foreach($order_goods as $k => $v){
            $order_goods[$k]['freight_num']=floatval($v['freight_num']);
            $order_goods[$k]['fact_num']=floatval($v['fact_num']);
        }
        $pre_money=M('InvoicingDetail')->where($map)->sum('pre_money	');
        $order_info['pre_money']=$pre_money;
        $url = C('WEB_URL');
        $phone = C('WEB_SITE_PHONE');
        $name = C('WEB_SITE_TITLE');
        $admin = idtoname(UID,'admin','username');
        $time = date('Y-m-d H:i:s',NOW_TIME);
        $this->assign('url',$url);
        $this->assign('phone',$phone);
        $this->assign('name',$name);
        $this->assign('admin',$admin);
        $this->assign('print_time',$time);
        $this->assign('order_info',$order_info);
        $this->assign('order_goods',$order_goods);
        if($template){
            $map = array();
            $map['code'] = $template;
            $content = M('PrintTemplate')->where($map)->getField('content');
            $content1 = $this->fetch('',htmlspecialchars_decode($content));
            $this->assign('info',$content1);
        }
        $this->display();
    }

    /**
     * 进货准备
     */
    public function order_in_add(){
        $this->get_shops_list();
        $this->get_supplier_list();
        $this->getcateTree();
        $this->assign('shopid',1);
        $this->display();
    }
    /**
     * 进货操作
     */
    public function order_in_insert(){
        $postdata=I('post.');
        if(empty($postdata['shop_id_in'])){$return=array('status'=>0,'msg'=>'请选择仓库'); $this->ajaxReturn($return);}
        if(empty($postdata['infos'])){$return=array('status'=>0,'msg'=>'请选择商品'); $this->ajaxReturn($return);}
        $supplier_array=array_unique($postdata['infos']['supplier_id']);
        $supplier=array_filter($supplier_array);
        if(empty($supplier) || count($supplier_array)!=count($supplier)){$return=array('status'=>0,'msg'=>'请选择供货商');$this->ajaxReturn($return);}
        $data = D('Common/InvoicingOrder')->order_in_insert($postdata);
        if($data['status']==1){$data['url']=U('InvoicingOrder/order_print',array('id'=>$data['id']));}
        $this->ajaxReturn($data);
    }
    /**
     * 出库准备
     */
    public function order_shipment(){
        $getdata=I('get.');
        $getdata['shop_name']=idtoname($getdata['shop_id'],'Shops');
        $getdata['out_price_name']=$this->out_price[$getdata['out_price']];
        $this->assign($getdata);
        $this->get_supplier_list();
        $this->getcateTree();
        $this->display();
    }
    /**
     * 出库操作
     */
    public function order_shipment_insert(){
        $postdata=I('post.');
        $attr_key='';
        foreach($postdata['freight_num'] as $k => $v){
            $attr_key=empty($postdata['goods_attr_sn'][$k])?0:intval($postdata['goods_attr_sn'][$k]);
            $num = D('Common/Cart')->shopgoodsstock($postdata['goods_id'][$k],$postdata['shop_id_out'],$attr_key);
            if($num['goods_number'] <= 0 || $num['goods_number'] < $v){$return['status']=0;$return['msg'] = '库存不足！';$this->ajaxReturn($return);}
        }
        $postdata['type']=empty($postdata['out_type'])?2:3;//如果out_type为空订单的货单类型为2普通出库 为1订单的货单类型为3仓库退货
        $postdata['status']=empty($postdata['out_type'])?3:0;
        $postdata['goods_status']=empty($postdata['out_type'])?3:0;
        $postdata['is_sn']=1;
        $data = D('Common/InvoicingOrder')->order_in_insert($postdata);
        $this->ajaxReturn($data);
    }

    /**
     * 调货准备
     */
    public function order_move_in(){
        $getdata=I('get.');
		$getdata['out_type']=0;
		$getdata['in_shop_name']=idtoname($getdata['in_shop_id'],'Shops');
        $getdata['out_shop_name']=idtoname($getdata['out_shop_id'],'Shops');
		$getdata['out_price'] =$getdata['move_price'];
        $getdata['out_price_name']=$this->out_price[$getdata['out_price']];
        $this->assign($getdata);
        $this->get_supplier_list();
        $this->getcateTree();
        $this->display();
    }

    public function order_move_begin(){
        $postdata=I('post.');
        $postdata['type']=4;
        $attr_key='';
        $postdata['status']=$postdata['goods_status']=2;
        foreach($postdata['freight_num'] as $k => $v){
            $attr_key=empty($postdata['goods_attr_sn'][$k])?0:intval($postdata['goods_attr_sn'][$k]);
            $num = D('Common/Cart')->shopgoodsstock($postdata['goods_id'][$k],$postdata['shop_id_out'],$attr_key);
            if($num['goods_number'] <= 0 || $num['goods_number'] < $v){$return['status']=0;$return['msg'] = '库存不足！';$this->ajaxReturn($return);}
        }
        $data = D('Common/InvoicingOrder')->order_in_insert($postdata);
        $this->ajaxReturn($data);
    }
    /**
     * 详情
     */
    public function detail(){
        $id=I('id');
        $map=array();
        $map['id']=$id;
        $order_info=M('InvoicingOrder')->where($map)->field(true)->find();
        $map=array();
        $map['order_id']=$id;
        $order_info['order_goods']=M('InvoicingGoods')->where($map)->field(true)->select();
        $i=0;
        foreach($order_info['order_goods'] as $k=>$v){
            $order_info['order_goods'][$k]['attr_name']=attr_key2name($v['goods_attr_sn'],$v['goods_id']);
            $unit=idtoname($v['goods_id'],'Goods','unit_id');
            if($unit){
                $order_info['order_goods'][$k]['unit_name']=idtoname($unit,'GoodsUnit','name');
            }else{
                $order_info['order_goods'][$k]['unit_name']='无';
            }
            if($v['goods_attr_sn']){
                $map=array('goods_id'=>$v['goods_id'],'attr_key'=>$v['goods_attr_sn']);
                $goods_attr_sn=M('GoodsAttrStock')->where($map)->getField('goods_attr_sn');
                $order_info['order_goods'][$k]['goods_sn']=$goods_attr_sn;
            }
            $order_info['order_goods'][$k]['fact_num']=floatval($v['fact_num']);
            $order_info['order_goods'][$k]['freight_num']=floatval($v['freight_num']);
            $order_info['order_goods'][$k]['request_num']=floatval($v['request_num']);
            if($v['supplier_id']>0) $i++;
        }
        if($order_info['is_separate']==1 && count($order_info['order_goods'])==$i){
            $send_shop_id=0;
        }else if(!empty($order_info['shop_id_out'])) {
            $send_shop_id=$order_info['shop_id_out'];
        }else if($order_info['status']==1 && $order_info['type']==0){
            $map = array();
            $map['id'] = $order_info['shop_id_in'];
            $map['status'] = 1;
            $send_shop_id = M('Shops')->where($map)->getField('send_shop_id');
        }
        $map=array();
        $map['id']=array('neq',$order_info['shop_id_in']);
        $map['status']=1;
        $shops_list=M('Shops')->where($map)->field('id,name')->select();
        $shops_list=format_array2select($shops_list);
        $this->assign('shops_list',$shops_list);
        $this->assign('send_shop_id',$send_shop_id);
        $this->assign($order_info);
        if($order_info['status']==1){$this->get_supplier_list();}
        $this->display();
    }

    public function freight_management_export(){
        $postdata=I('get.');$map=array();
        $order_type=$postdata['order_type'];//1采购2出库3入库
        $sn = $postdata['sn'];
        $status = $postdata['status'];
        $type = $postdata['type'];
        if(empty($postdata['shopid']))$postdata['shopid']=1; //默认仓库1 jxr
        $shopid=$postdata['shopid'];
        if($sn){$map['sn'] = array('like','%'.$sn.'%');}
        if($order_type==1) {
            $map['type'] = 0;    //订货单
            $map['status'] = array('elt', 1);
        }
        if($order_type==2){
            if($status){$map['status'] = $status-1;}
            else{$map['status'] = array('in','0,1,3,4,5');}
            if(intval($type) > 0){
                $map['type'] = $type;
            }else{
                $map['type'] = array('in','2,3,4,6,7');// 2普通出库 、3仓库退货、4调货出库、6销售出库、7报损出库
            }
        }
        if($order_type==3) {
            if ($status) {
                $map['status'] = $status - 1;
            } else $map['status'] = array('in', '2,3,4,5');//采购单只是查询待入库的
            if (intval($type) == 20 || !$type) {
                $map['type'] = array('in', '0,1,4,5,8');// 0采购入库、1其他入库、4调货入库、6退货入库
            } else {
                if ($type == 21) $type = 0;
                $map['type'] = $type;
            }
        }
        if($shopid){$map_or=array('shop_id_in'=>$shopid,'shop_id_out'=>$shopid,'_logic'=>'or');$map['_complex']=$map_or;}
        if($postdata['data_from']){$map['add_time'][] = array('egt',strtotime($postdata['data_from']));}
        if($postdata['data_to']){$map['add_time'][] = array('elt',strtotime($postdata['data_to']));}
        $list = M('InvoicingOrder')->where($map)->order('id desc')->field(true)->select();
        $title=array('货流单号','下单时间','货单类型','出货方','进货方','预付款','备注','商品名称','商品编号','商品属性','供货商','请求量','货流量','实收量','进货价','小计');
        if(!empty($list)){
            $data=array();$ids=array();
            foreach($list as $k => $v){
                $ids[]=$v['id'];
                $data[$v['id']] = $v;
            }
            $map=array();
            $map['order_id']=array('in',$ids);
            $invoicing_goods=M('InvoicingGoods')->where($map)->field('id,order_id,goods_id,goods_name,goods_sn,goods_attr_sn,supplier_id,supply_price,freight_num,request_num,fact_num,all_money')->select();
            foreach($invoicing_goods as $key => $val){
                $data[$val['order_id']]['goods_list'][]=$val;
            }
        }
        $export=array();
        foreach($data as $v){
            $request=$freight=$fact=0;
            foreach($v['goods_list'] as $key=> $val){
                $exdata=array();
                if($key==0){
                    $exdata[]=$v['sn'];
                    $exdata[]=time_format($v['add_time']);
                    if($order_type==1){$exdata[]='采购单';}
                    if($order_type==2){$exdata[]=$this->chu_ortype[$v['type']];}
                    if($order_type==3){$exdata[]=$this->ru_ortype[$v['type']];}
                    /*if($v['type']==0){$exdata[]='采购单';}
                    if($v['type']==1){$exdata[]='入库单';}
                    if($v['type']==2){$exdata[]='出库单';}
                    if($v['type']==3){$exdata[]='退货单';}
                    if($v['type']==4){$exdata[]='调货单';}*/
                    $exdata[]=empty($v['shop_id_out'])?'-':idtoname($v['shop_id_out'],'Shops','name');
                    $exdata[]=empty($v['shop_id_in'])?'-':idtoname($v['shop_id_in'],'Shops','name');
                    $exdata[]=$v['pre_money'];
                    $exdata[]=$v['remarks'];
                }else{
                        $exdata[] = '';
                        $exdata[] = '';
                        $exdata[] = '';
                        $exdata[] = '';
                        $exdata[] = '';
                        $exdata[] = '';
                        $exdata[] = '';
                }
                $exdata[] = $val['goods_name'];
                $exdata[] = $val['goods_sn'];
                $exdata[] = empty($val['goods_attr_sn']) ? '' : attr_key2name($val['goods_attr_sn'], $val['goods_id']);
                $exdata[] = empty($val['supplier_id']) ? '' : idtoname($val['supplier_id'], 'Suppliers', 'name');
                $exdata[] = floatval($val['request_num']);
                $exdata[] = floatval($val['freight_num']);
                $exdata[] = floatval($val['fact_num']);
                $exdata[] = format_price($val['supply_price']);
                $exdata[] = format_price($val['all_money']);
                $export[]=$exdata;
                $request+=$val['request_num'];
                $freight+=$val['freight_num'];
                $fact+=$val['fact_num'];
            }
            $exdataheji=array(
                '','','','','','','',
                '合计',
                count($v['goods_list']).'种商品',
                '-','-',
                floatval($request),floatval($freight),floatval($fact),'-',format_price($v['all_money']),
            );
            $export[]=$exdataheji;
        }
        export_csv('货流单.csv',$title, $export);
        unset($title, $data);
        exit;
    }

    /**
     * 仓库进货审核
     */
    public function audit(){
        $return=array('status'=>0,'msg'=>'');
        $id=I('id');
        if(empty($id)){$return['msg']='请选择要审核的商品';$this->ajaxReturn($return);}
        $map['id']=$id;
        $map['status']=0;
        $count=M('InvoicingOrder')->where($map)->count();
        if($count>0){
            $order_info=M('InvoicingOrder')->where($map)->field('type,mtype')->find();
            $savedata=array();
            if($order_info['type']==3) $savedata['status']=3;
            else $savedata['status']=1;
            $res=M('InvoicingOrder')->where($map)->save($savedata);
            if($res){
                $map=array();
                $map['status']=0;
                $map['order_id']=$id;
                $savedata=array();
                if($order_info['type']==3) $savedata['status']=3;
                else $savedata['status']=1;
                $result=M('InvoicingGoods')->where($map)->save($savedata);
            }
            if($res && $result){
                if($order_info['type']==3 && $order_info['mtype']==0){
                    D('Common/InvoicingOrder')->reduce_storage($id);//减少库存并记录出库记录
                    D('Common/InvoicingOrder')->add_invoicing_detail($id, 1, 0, array(), 1);//减少供货商对账单
                    $url=U('InvoicingOrder/order_chu');
                }else{
                    $url=U('InvoicingOrder/purchase_index');
                }
                $return=array('status'=>1,'msg'=>'审核成功','url'=>$url);

            }
            else{$return['msg']='审核失败';}
        }else{$return['msg']='该货流单不满足审核条件';}
        $this->ajaxReturn($return);
    }
    /**
     * 确认发货
     */
    public function confirm_order(){
        $return=array('status'=>0,'msg'=>'');
        $postdata=I('post.');$id=intval($postdata['id']);
        if(empty($id)){$return['msg']='请选择要操作的货流单';$this->ajaxReturn($return);}
        $map=array('id'=>$id,'status'=>1);
        $order_info=M('InvoicingOrder')->where($map)->field('id,shop_id_in,is_pay,pay_status')->find();
        if(empty($order_info)){$return['msg']='该货流单不满足发货条件'; $this->ajaxReturn($return);}
        if($order_info['is_pay'] ==1 && $order_info['pay_status']!=3){$return['msg']='该货流单暂未支付，请先支付'; $this->ajaxReturn($return);}
        $supplier_array=array_unique($postdata['supplier_id']);
        $supplier=array_filter($supplier_array);
        if((empty($supplier) || count($supplier_array)!=count($supplier)) && empty($postdata['send_shop_id'])){$return=array('status'=>0,'msg'=>'请选择供货商');$this->ajaxReturn($return);}
        foreach($postdata['invoicing_goods_id'] as $k=>$v) {
            $map=array('order_id'=>$id,'status'=>1);
            $map['id']=$v;
            $map['goods_attr_sn']=$postdata['invoicing_goods_attr'][$k];
            $request_num=M('InvoicingGoods')->where($map)->getField('request_num');
            if($request_num<$postdata['freight_num'][$k]){
                $return['msg']='商品配货量不能大于请求量';
                $this->ajaxReturn($return);break;
            }
        }
        /*lss 2018-9-19新加开始*/
        //订货订单配货选择仓库的时候要判断库存
        if(!empty($postdata['send_shop_id'])){
            foreach($postdata['invoicing_goods_id'] as $k=>$v) {
                $map['id']=$v;
                $map['goods_attr_sn']=$postdata['invoicing_goods_attr'][$k];
                $goods_id=M('InvoicingGoods')->where($map)->getField('goods_id');
                $goods_attr_sn=empty($postdata['invoicing_goods_attr'][$k])?0:$postdata['invoicing_goods_attr'][$k];
                $goods_number=D('Common/Cart')->shopgoodsstock($goods_id,$postdata['send_shop_id'],$goods_attr_sn);
                if($goods_number['goods_number']<=0 || $goods_number['goods_number']<$postdata['freight_num'][$k]){
                    $return['msg']='"'.idtoname($goods_id,'Goods','goods_name').'"商品库存不足';
                    $this->ajaxReturn($return);break;
                }
            }
        }
        /*lss 2018-9-19新加结束*/
        $map=array('id'=>$id,'status'=>1);
        $now_time=NOW_TIME;
        $count=floatval($postdata['count']);
        $all_money=floatval($postdata['all_money']);
        if($order_info['type']==0) $qianzhui='CG';
        if(empty($order_info['sn'])) $data['sn']=D('Common/InvoicingOrder')->invoicing_sn($qianzhui);
        $data=array(
            //'sn'=>D('Common/InvoicingOrder')->invoicing_sn(),
            'all_money'=>$all_money,
            'count'=>$count,
            'status'=>empty($postdata['send_shop_id'])?2:1,
            'update_time'=>$now_time,
            'shop_id_out' => empty($postdata['send_shop_id'])?0:$postdata['send_shop_id'],
            'is_transfer' => empty($postdata['send_shop_id'])?0:1,
        );
        if(!empty($postdata['send_shop_id'])) $data['type']=4;
        $res=M('InvoicingOrder')->where($map)->save($data);
        if($res){
            $map=array('order_id'=>$id,'status'=>1);
            foreach($postdata['invoicing_goods_id'] as $k=>$v) {
                $map['id']=$v;
                $supply_price=floatval($postdata['supply_price'][$k]);
                $supplier_id=intval($postdata['supplier_id'][$k]);
                $freight_num=floatval($postdata['freight_num'][$k]);
                $all_money=floatval($supply_price*$freight_num);
                $data = array(
                    'status' => empty($postdata['send_shop_id'])?2:1,
                    'supply_price' => $supply_price,
                    'supplier_id' => $supplier_id,
                    'all_money' => $all_money,
                    'freight_num' => floatval($freight_num),
                    'send_time' => $now_time
                );
                $result = M('InvoicingGoods')->where($map)->save($data);
                if(!$result){break;}
            }
        }
        if($res && $result){
            $return=array('status'=>1,'msg'=>'已为仓库配货');
            $map = array('id' => $id);
            $order_info = M("InvoicingOrder")->where($map)->field(true)->find();
            if(empty($postdata['send_shop_id'])) {
                D('Common/InvoicingOrder')->add_invoicing_detail($id);//仓库订货配货后添加待确认对账
                //极光推送
                if ($order_info) {
                    FrieghtPushSend($order_info['shop_id_in']);
                }
            }else{
                //极光推送
                if($order_info) FrieghtPushSend($order_info['shop_id_out']);
            }
            $this->ajaxReturn($return);
        } else{$return['msg']='配货失败';$this->ajaxReturn($return);}
    }

    /**
     * 获取下拉仓库
     */
    private function get_shops_list(){
//        $map=array('shop_type'=>1);
        $shops_list=M('Shops')->where(1)->field('id,name')->order('name')->cache(true)->select();
        $shops_list=format_array2select($shops_list);
        $this->assign('shops_list',$shops_list);
    }

    /**
     * 获取下拉供货商
     */
    private function get_supplier_list(){
        $Suppliers=M('Suppliers')->where(1)->field('id,name')->order('name')->cache(true)->select();
        $suppliers_list=format_array2select($Suppliers);
        $this->assign('suppliers_list',$suppliers_list);
    }

    /**
     * 获取分类
     */
    private function getcateTree(){
        $GoodsCategory = getcache('PurchaseCategory');
        $select_categorys=array();
        foreach($GoodsCategory as $v){
            $select_categorys[$v['id']]=$v['name'];
        }
        $this->assign('select_categorys',$select_categorys);
    }

    /**
     * 货流商品变动明细列表
     */
    public function goods_detail($is_return=false){
        $change_type=array('全部变动','商品销售','客户退货','货流进货','货流调出','货流出库','货流退货','库存盘点','商品报损','编辑库存','大件拆包','商品退货');
        $this->assign('change_type',$change_type);
        $postdata=I('param.');
        $goods_id = intval($postdata['goods_id']);
        if(!empty($goods_id)) {$map['goods_id'] = $goods_id;}
        if(!empty($postdata['type'])) {$map['type'] = intval($postdata['type']);}
        if(!empty($postdata['shop_id'])) {$map['shop_id'] = intval($postdata['shop_id']);}
        if(empty($postdata['is_first'])){
            if(empty($postdata['data_from']))$postdata['data_from'] = date('Y-m-d 00:00:00', time());
            if(empty($postdata['data_to']))$postdata['data_to'] = date('Y-m-d 23:59:59', time());
        }
        if ($postdata['data_from']) {$map['change_time'][] = array('egt', strtotime($postdata['data_from']));}
        if ($postdata['data_to']) {$map['change_time'][] = array('elt', strtotime($postdata['data_to']));}
        if($is_return==true) {
            $list = M('StockLog')->where($map)->field(true)->select();
        }else{
            $list = $this->lists('StockLog', $map);
        }
        $data['change_total_num']=M('StockLog')->where($map)->sum('change_num');
        $data['change_total_num']=floatval($data['change_total_num']);
        $data['all_num']=M('StockLog')->where($map)->sum('total_num');
        $data['all_num']=floatval($data['all_num']);
        $data['all_before_num']=floatval($data['all_num']-$data['change_total_num']);
        $goods_ids=M('StockLog')->where($map)->group('goods_id')->getField('goods_id',true);
        $data['goods_num']=count($goods_ids);
        foreach ($list as $k => $v) {
            if ($v['attr_key']) $list[$k]['attr_name'] = attr_key2name($v['attr_key'], $v['goods_id']);
            $list[$k]['goods_name'] = idtoname($v['goods_id'], "Goods", 'goods_name');
            $map=array();
            $map['id']=$v['goods_id'];
            $list[$k]['goods_attr_sn']=M('Goods')->where($map)->getField('goods_sn');
            if(!empty($v['attr_key'])){
                $map=array();
                $map['goods_id']=$v['goods_id'];
                $map['attr_key']=$v['attr_key'];
                $list[$k]['goods_attr_sn']=M('GoodsAttrStock')->where($map)->getField('goods_attr_sn');
            }
            $list[$k]['change_num']=floatval($v['change_num']);
            $list[$k]['total_num']=floatval($v['total_num']);
            $list[$k]['before_num']=floatval($v['total_num']-$v['change_num']);
        }
        if ($is_return == false) {
            $this->assign('list', $list);
            $this->assign($postdata);
            $this->assign('data', $data);
            $this->get_shops_list();
            $this->display();
        } else {
            $return = array('list' => $list, 'data' => $data);
            return $return;
        }
    }

    public function goods_detail_export(){
        $goods_detail=$this->goods_detail(true);
        $change_type=array('全部变动','商品销售','客户退货','货流进货','货流调出','货流出库','货流退货','库存盘点','商品报损','编辑库存','大件拆包');
        $title = array('仓库名称','商品名称','商品属性', '操作时间', '变动类型', '库存变动', '当前库存/盘点校正', '备注');
        $data = array();
        foreach ($goods_detail['list'] as $k => $v) {
            $data[$k][] = idtoname($v['shop_id'],'Shops','name');
            $data[$k][] = $v['goods_name'];
            $data[$k][] = empty($v['attr_name'])?'':$v['attr_name'];
            $data[$k][] = time_format($v['change_time']);
            $data[$k][] = $change_type[$v['type']];
            $data[$k][] = $v['change_num'];
            $data[$k][] = $v['total_num'];
            $data[$k][] = $v['change_desc'];
        }
        export_csv('库存明细.csv',$title,$data);
        unset($title, $data);
        exit;
    }
    /**
     * 供货商结算
     */
    public function supplier_detail($is_return=false){
        $map=array();
        $map['supplier_id']=array('neq',0);
        $postdata=I('param.');
        $supplier_id=intval($postdata['supplier_id']);
        if(!empty($supplier_id)){$map['supplier_id']=$supplier_id;}
        if($postdata['data_from']){$map['add_time'][] = array('egt',strtotime($postdata['data_from']));}
        if($postdata['data_to']){$map['add_time'][] = array('elt',strtotime($postdata['data_to']));}
        $field="supplier_id,count(order_id) as order_count,sum(fact_num) as fact_num,sum(all_price) as all_price";
        $map['status']=0;//待确认
        $info=M('InvoicingDetail')->where($map)->field($field)->group('supplier_id')->select();
        $list=array();
        foreach($info as $k=>$v){
            $list[$v['supplier_id']]['supplier_id']=$v['supplier_id'];
            $list[$v['supplier_id']]['no_commend_order_count']=$v['order_count'];
            $list[$v['supplier_id']]['no_commend_fact_num']=$v['fact_num'];
            $list[$v['supplier_id']]['no_commend_all_price']=$v['all_price'];
        }
        $map['status']=1;//待对账
        $info=M('InvoicingDetail')->where($map)->field($field)->group('supplier_id')->select();
        foreach($info as $k=>$v){
            $list[$v['supplier_id']]['supplier_id']=$v['supplier_id'];
            $list[$v['supplier_id']]['no_check_order_count']=$v['order_count'];
            $list[$v['supplier_id']]['no_check_fact_num']=$v['fact_num'];
            $list[$v['supplier_id']]['no_check_all_price']=$v['all_price'];
        }
        $map['status']=2;//待结算
        $info=M('InvoicingDetail')->where($map)->field($field)->group('supplier_id')->select();
        foreach($info as $k=>$v){
            $list[$v['supplier_id']]['supplier_id']=$v['supplier_id'];
            $list[$v['supplier_id']]['no_balance_order_count']=$v['order_count'];
            $list[$v['supplier_id']]['no_balance_fact_num']=$v['fact_num'];
            $list[$v['supplier_id']]['no_balance_all_price']=$v['all_price'];
        }
        $map['status']=3;//已结算
        $info=M('InvoicingDetail')->where($map)->field($field)->group('supplier_id')->select();
        foreach($info as $k=>$v){
            $list[$v['supplier_id']]['supplier_id']=$v['supplier_id'];
            $list[$v['supplier_id']]['balance_order_count']=$v['order_count'];
            $list[$v['supplier_id']]['balance_fact_num']=$v['fact_num'];
            $list[$v['supplier_id']]['balance_all_price']=$v['all_price'];
        }
        if(empty($list)){$data=array();}
        else{
        //保证每个供货商都是满数据
        foreach($list as $key=>$val){
            $list[$key]['id']=$val['supplier_id'];
            $list[$key]['name']=idtoname($val['supplier_id'],'Suppliers');
            $list[$key]['no_commend_order_count']=intval($val['no_commend_order_count']);
            $list[$key]['no_commend_fact_num']=floatval($val['no_commend_fact_num']);
            $list[$key]['no_commend_all_price']=format_decimal($val['no_commend_all_price']);
            $list[$key]['no_check_order_count']=intval($val['no_check_order_count']);
            $list[$key]['no_check_fact_num']=floatval($val['no_check_fact_num']);
            $list[$key]['no_check_all_price']=format_decimal($val['no_check_all_price']);
            $list[$key]['no_balance_order_count']=intval($val['no_balance_order_count']);
            $list[$key]['no_balance_fact_num']=floatval($val['no_balance_fact_num']);
            $list[$key]['no_balance_all_price']=format_decimal($val['no_balance_all_price']);
            $list[$key]['balance_order_count']=intval($val['balance_order_count']);
            $list[$key]['balance_fact_num']=floatval($val['balance_fact_num']);
            $list[$key]['balance_all_price']=format_decimal($val['balance_all_price']);
        }
            //合计
            $data=array(
                'no_commend_order_count'=>array_sum(array_map(function($val){return $val['no_commend_order_count'];},$list)),
                'no_commend_fact_num'=>array_sum(array_map(function($val){return floatval($val['no_commend_fact_num']);},$list)),
                'no_commend_all_price'=>format_decimal(array_sum(array_map(function($val){return $val['no_commend_all_price'];},$list))),
                'no_check_order_count'=>array_sum(array_map(function($val){return $val['no_check_order_count'];},$list)),
                'no_check_fact_num'=>array_sum(array_map(function($val){return floatval($val['no_check_fact_num']);},$list)),
                'no_check_all_price'=>format_decimal(array_sum(array_map(function($val){return $val['no_check_all_price'];},$list))),
                'no_balance_order_count'=>array_sum(array_map(function($val){return $val['no_balance_order_count'];},$list)),
                'no_balance_fact_num'=>array_sum(array_map(function($val){return floatval($val['no_balance_fact_num']);},$list)),
                'no_balance_all_price'=>format_decimal(array_sum(array_map(function($val){return $val['no_balance_all_price'];},$list))),
                'balance_order_count'=>array_sum(array_map(function($val){return $val['balance_order_count'];},$list)),
                'balance_fact_num'=>array_sum(array_map(function($val){return floatval($val['balance_fact_num']);},$list)),
                'balance_all_price'=>format_decimal(array_sum(array_map(function($val){return $val['balance_all_price'];},$list))),
            );
        }
        if($is_return==true){
            $return=array('data'=> $data,'list'=> $list);
            return $return;
        }else {
            $this->assign($postdata);
            $this->assign('data', $data);
            $this->assign('list', $list);
            $this->get_supplier_list();
            $this->display();
        }
    }

    /**
     * 供货商结算导出
     */
    public function supplier_detail_export(){
        $supplier_detail=$this->supplier_detail(true);
        $title = array('供货商', '待确认货单数','待确认商品数量', '待确认总价', '待对账货单数', '待对账商品数量', '待对账总价', '待结算货单数', '待结算商品数量', '待结算总价', '已结算货单数', '已结算商品数量', '已结算总价');
        $data = array();
        foreach ($supplier_detail['list'] as $k => $v) {
            $data[$k][] = $v['name'];
            $data[$k][] = $v['no_commend_order_count'];
            $data[$k][] = $v['no_commend_fact_num'];
            $data[$k][] = $v['no_commend_all_price'];
            $data[$k][] = $v['no_check_order_count'];
            $data[$k][] = $v['no_check_fact_num'];
            $data[$k][] = $v['no_check_all_price'];
            $data[$k][] = $v['no_balance_order_count'];
            $data[$k][] = $v['no_balance_fact_num'];
            $data[$k][] = $v['no_balance_all_price'];
            $data[$k][] = $v['balance_order_count'];
            $data[$k][] = $v['balance_fact_num'];
            $data[$k][] = $v['balance_all_price'];
        }
        $data[]=array(
            '总计：',
            $supplier_detail['data']['no_commend_order_count'],
            $supplier_detail['data']['no_commend_fact_num'],
            $supplier_detail['data']['no_commend_all_price'],
            $supplier_detail['data']['no_check_order_count'],
            $supplier_detail['data']['no_check_fact_num'],
            $supplier_detail['data']['no_check_all_price'],
            $supplier_detail['data']['no_balance_order_count'],
            $supplier_detail['data']['no_balance_fact_num'],
            $supplier_detail['data']['no_balance_all_price'],
            $supplier_detail['data']['balance_order_count'],
            $supplier_detail['data']['balance_fact_num'],
            $supplier_detail['data']['balance_all_price'],
        );
        export_csv('供货商结算.csv',$title,$data);
        unset($title, $data);
        exit;
    }

    /**
     * 结算记录
     */
    public function balance_list(){
        $status_list=array(
            '0'=>'全部货单',
            '1'=>'待确认货单',
            '2'=>'待对账货单',
            '3'=>'待结算货单',
            '4'=>'已结算货单',
        );
        $postdata=I('request.');
        $map=array();
        $sn=$postdata['sn'];
        if(!empty($sn)){$map['o.sn']=$sn;}
        $supplier_id=intval($postdata['supplier_id']);
        if(!empty($supplier_id)){$map['a.supplier_id']=$supplier_id;}
        $shopid=intval($postdata['shopid']);
        if($shopid){$map_or=array('o.shop_id_in'=>$shopid,'o.shop_id_out'=>$shopid,'_logic'=>'or');$map['_complex']=$map_or;}
        $status=intval($postdata['status']);
        if(!empty($status)){$map['a.status']=$status-1;}
        if($postdata['data_from']){$map['o.add_time'][] = array('egt',strtotime($postdata['data_from']));}
        if($postdata['data_to']){$map['o.add_time'][] = array('elt',strtotime($postdata['data_to']));}
        $field="a.id as id,a.order_id,a.supplier_id,a.fact_num,a.all_price,a.pre_money,a.check_time,a.balance_time,a.status,o.sn as order_sn,o.shop_id_in,o.shop_id_out,o.add_time,o.type";
        $join="LEFT JOIN __INVOICING_ORDER__ o ON a.order_id=o.id";
        $list=page_list('InvoicingDetail',$map,'',$field,20,$join);
        foreach($list['list'] as $k => $v){
            $list['list'][$k]['fact_num']=floatval($v['fact_num']);
        }
        $this->assign($list);
        $this->assign($postdata);
        $this->assign('status_list',$status_list);
        $this->get_supplier_list();
        $this->get_shops_list();
        $this->display();
    }
    /**
     * 结算记录详情
     */
    public function balance_info(){
        $order_id=intval(I('get.order_id'));
        $supplier_id=intval(I('get.supplier_id'));
        if(empty($order_id)){echo '参数错误';exit;}
        $map=array('order_id'=>$order_id,'supplier_id'=>$supplier_id);
        $field='goods_id,goods_name,goods_sn,goods_attr_sn,supply_price,all_money,freight_num,fact_num';
        $list=M('InvoicingGoods')->where($map)->field($field)->select();
        foreach($list as $k=>$v){
            $list[$k]['attr_name']=attr_key2name($v['goods_attr_sn'],$v['goods_id']);
            $unit=idtoname($v['goods_id'],'Goods','unit_id');
            if($unit){
                $list[$k]['unit_name']=idtoname($unit,'GoodsUnit','name');
            }else{
                $list[$k]['unit_name']='无';
            }
            if($v['goods_attr_sn']){
                $map=array('goods_id'=>$v['goods_id'],'attr_key'=>$v['goods_attr_sn']);
                $goods_attr_sn=M('GoodsAttrStock')->where($map)->getField('goods_attr_sn');
                $list[$k]['goods_sn']=$goods_attr_sn;
            }
            $list[$k]['freight_num']=floatval($v['freight_num']);
            $list[$k]['fact_num']=floatval($v['fact_num']);
        }
        //合计
        $data=array(
            'count'=>count($list),
            'freight_num'=>array_sum(array_map(function($val){return floatval($val['freight_num']);},$list)),
            'fact_num'=>array_sum(array_map(function($val){return floatval($val['fact_num']);},$list)),
            'all_money'=>format_decimal(array_sum(array_map(function($val){return $val['all_money'];},$list))),
        );
        $this->assign('list',$list);
        $this->assign('data',$data);
        $this->display();
    }
    /**
     * 确认对账/结算
     */
    public function confirm_balance(){
        $postdata=I('post.');
        $return=D('Common/InvoicingOrder')->update_invoicing_detail($postdata);
        $this->ajaxReturn($return);
    }
    /**
     * 进货价分析列表
     */
    public function goods_price_list(){
        $postdata=I('param.');
        $map=array('group'=>'a.goods_id');
        $map['o.type']=array('in','0,1');
        $supplier_id=intval($postdata['supplier_id']);
        if(!empty($supplier_id)){$map['a.supplier_id']=$supplier_id;}
        $shop_id=intval($postdata['shop_id']);
        if(!empty($shop_id)){$map['o.shop_id_in']=$shop_id;}
        if(!empty($postdata['keyword'])){
            $map['a.goods_sn|a.goods_name']=array('like', '%' . (string)$postdata['keyword'] . '%');
        }
        if($postdata['data_from']){$update_time[] = array('egt',strtotime($postdata['data_from']));}
        if($postdata['data_to']){$update_time[] = array('elt',strtotime($postdata['data_to']));}
        if($update_time){$map['a.update_time']=$update_time;}
        $field='a.goods_id,a.goods_name,a.goods_sn,count(a.order_id) as order_count,avg(a.supply_price) as supply_price_avg,max(a.supply_price) as supply_price_max,min(a.supply_price) as supply_price_min,max(a.update_time) as update_time_end';
        $join='LEFT JOIN __INVOICING_ORDER__ o ON o.id=a.order_id';
        $list=page_list('InvoicingGoods',$map,'',$field,20,$join);
        $fields='count( distinct a.supplier_id) as supplier_count';
        $map['a.supplier_id']=array('gt',0);
        unset($map['group']);
        foreach($list['list'] as $k => $v){
            $map['a.goods_id']=$v['goods_id'];
            $supplier_count=M('InvoicingGoods')->alias('a')->where($map)->field($fields)->join($join)->find();
            $list['list'][$k]['supplier_count']=$supplier_count['supplier_count'];
        }
        $this->assign($list);
        $this->assign($postdata);
        $this->get_supplier_list();
        $this->get_shops_list();
        $this->display();
    }

    /**
     * 进货价分析详情
     */
    public function goods_price_detail(){
        $goods_id=I('get.goods_id');
        $shop_id=I('get.shop_id');
        $supplier_id=I('get.supplier_id');
        $data_from=I('get.data_from');
        $data_to=I('get.data_to');
        if(empty($goods_id)){echo '参数错误';exit;}
        $map=array('g.goods_id'=>$goods_id,'o.type'=>array('in',array('0','1')));
        if(!empty($shop_id))$map['o.shop_id_in']=$shop_id;
        if(!empty($supplier_id))$map['g.supplier_id']=$supplier_id;
        if($data_from){$update_time[] = array('egt',strtotime($data_from));}
        if($data_to){$update_time[] = array('elt',strtotime($data_to));}
        if($update_time){$map['g.update_time']=$update_time;}
        $field='g.goods_id,g.goods_attr_sn,g.supplier_id,g.supply_price,g.update_time,g.shop_id';
        $list=M('InvoicingGoods')->alias('g')->join('LEFT JOIN __INVOICING_ORDER__ o ON o.id=g.order_id')->where($map)->field($field)->select();
        foreach($list as $k=>$v){
            $list[$k]['attr_name']=attr_key2name($v['goods_attr_sn'],$v['goods_id']);
            $unit=idtoname($v['goods_id'],'Goods','unit_id');
            if($unit){
                $list[$k]['unit_name']=idtoname($unit,'GoodsUnit','name');
            }else{
                $list[$k]['unit_name']='无';
            }
            if($v['goods_attr_sn']){
                $map=array('goods_id'=>$v['goods_id'],'attr_key'=>$v['goods_attr_sn']);
                $goods_attr_sn=M('GoodsAttrStock')->where($map)->getField('goods_attr_sn');
                $list[$k]['goods_sn']=$goods_attr_sn;
            }
        }
        $this->assign('list',$list);
        $this->display();
    }

    /**
     * 作废订单
     */
    public function cancel_order(){
        $id=I('id');
		$type=I('type');
        $result=D('Common/InvoicingOrder')->cancel_order($id,$type);
        $this->ajaxReturn($result);
    }
    public function separate(){
        $id=I('id');
        $postdata=I('post.');
        $result=D('Common/InvoicingOrder')->separate($id,$postdata['supplier_id']);
        if($result['status']==1){
            $result['url']=geturl('InvoicingOrder/index');
        }
        $this->ajaxReturn($result);
    }

    /**盘点开始**/
    /**
     * 盘点准备
     */
    public function pan_add(){
        $this->get_shops_list();
        $this->get_supplier_list();
        $this->getcateTree();
        $this->assign('shop_id',1);
        $this->display();
    }
    /**
     * 添加盘点
     */
    public function confirm_pan_add(){
        $return=array('status'=>0,'');
        $postdata=I('post.');
        if(empty($postdata['infos'])){$return=array('status'=>0,'msg'=>'请选择商品'); $this->ajaxReturn($return);}
        $all_stock=$reality_sum=0;
        $now_time=NOW_TIME;
        $shop_id=intval($postdata['shop_id']);
        $shop_account_id=intval($postdata['shop_id']);
        $remarks=empty($postdata['remarks'])?'无':$postdata['remarks'];
        $goodslist=$postdata['infos'];
        foreach($goodslist['goods_id'] as $k => $v){
            $all_stock+=$goodslist['stock'][$k];
            $reality_sum+=$goodslist['reality_num'][$k];
        }
        $data=array(
            'sn'=>D('Common/InvoicingOrder')->invoicing_sn('PD'),
            'all_stock'=>$all_stock,
            'reality_sum'=>$reality_sum,
            'profit_sum'=>$postdata['sum_profit_count'],
            'loss_sum'=>$postdata['sum_loss_count'],
            'profit_all_money'=>$postdata['sum_profit_money'],
            'loss_all_money'=>$postdata['sum_loss_money'],
            'type'=>3,
            'type_id'=>$shop_id,
            'addtime'=>$now_time,
            'admin_id'=>$shop_account_id,
            'remarks'=>$remarks,
            'info_type'=>0,
            'status'=>0,//审核状态
        );
        $id=M('StocktakingInfo')->add($data);
        if($id<=0){$return['msg']="添加盘点失败";$this->ajaxReturn($return);}
        foreach($goodslist['goods_id'] as $k => $v){
            $list_info=array(
                'stocktaking_id'=>$id,
                'goods_id'=>$v,
                'cate_id'=>0,
                'supplier_id'=>empty($goodslist['supplier_id'][$k])?0:$goodslist['supplier_id'][$k],
                'shop_id'=>$shop_id,
                'goods_name'=>$goodslist['goods_name'][$k],
                'goods_sn'=>$goodslist['goods_sn'][$k],
                'goods_attr_sn'=>empty($goodslist['goods_attr_sn'][$k])?0:$goodslist['goods_attr_sn'][$k],
                'stock'=>$goodslist['stock'][$k],
                'reality'=>$goodslist['reality_num'][$k],
                'profit_num'=>$goodslist['profit_num'][$k],
                'loss_num'=>$goodslist['loss_num'][$k],
                'remark'=>$remarks,
                'info_type'=>0,
                'status'=>0,//审核状态
            );
            if(!empty($goodslist['loss_money'][$k]) && floatval($goodslist['loss_money'][$k])>0){
                $list_info['bad_money']=$goodslist['loss_money'][$k];
            }else{
                $list_info['bad_money']=$goodslist['profit_money'][$k];
            }
            $res=M('StocktakingGoods')->add($list_info);
        }
        if($res==false){$return['msg']="添加盘点商品失败";$this->ajaxReturn($return);}
        action_log('create_pan_order', 'Admin', $id, UID);//操作日志
        $return['status']=1;
        $return['msg']='提交成功';
        $this->ajaxReturn($return);
    }
    //盘点记录
    public function stocktaking_list(){
        $postdata=I('param.');
        $map=array('type'=>3,'info_type'=>0);
        $shop_id=intval($postdata['shop_id']);
        if(!empty($shop_id)){$map['type_id']=$shop_id;}
        if($postdata['data_from']){$map['addtime'][] = array('egt',strtotime($postdata['data_from']));}
        if($postdata['data_to']){$map['addtime'][] = array('elt',strtotime($postdata['data_to']));}
        $is_gain=$postdata['is_gain'];//是否盈利1盘盈2盘亏
        if($is_gain==1){$map['profit_sum']=array('neq',0);}
        elseif($is_gain==2){$map['loss_sum']=array('neq',0);}
        $field='id,type_id,all_stock,reality_sum,profit_sum,loss_sum,addtime,admin_id,status,audit_name,audit_time,audit_remarks,loss_all_money,profit_all_money';
        $list=page_list('StocktakingInfo',$map,'addtime desc',$field);
        $goods_count=$all_stock=$all_reality_sum=$all_profit_sum=$all_loss_sum=0;
        foreach($list['list'] as $k => $v){
            $list['list'][$k]['all_stock']=floatval($v['all_stock']);
            $list['list'][$k]['reality_sum']=floatval($v['reality_sum']);
            $list['list'][$k]['profit_sum']=floatval($v['profit_sum']);
            $list['list'][$k]['loss_sum']=floatval($v['loss_sum']);
        }
        $goods_count=M('StocktakingInfo')->where($map)->count();
        $all_stock=M('StocktakingInfo')->where($map)->sum('all_stock');
        $all_reality_sum=M('StocktakingInfo')->where($map)->sum('reality_sum');
        $all_profit_sum=M('StocktakingInfo')->where($map)->sum('profit_sum');
        $all_loss_sum=M('StocktakingInfo')->where($map)->sum('loss_sum');
        $this->assign($list);
        $this->assign($postdata);
        $this->assign('goods_count',$goods_count);
        $this->assign('all_stock',$all_stock);
        $this->assign('all_reality_sum',$all_reality_sum);
        $this->assign('all_profit_sum',$all_profit_sum);
        $this->assign('all_loss_sum',$all_loss_sum);
        $this->assign('stock_status',$this->stock_status);
        $this->get_shops_list();
        $this->display();
    }
    //盘点记录商品
    public function stocktaking_info(){
        $getdata=I('get.');
        $id=intval($getdata['id']);
        if(empty($id)){echo '参数错误';exit;}
        $map=array('id'=>$id,'info_type'=>0);
        $field='id,all_stock,reality_sum,profit_sum,loss_sum,profit_all_money	,info_type,loss_all_money,remarks,status,addtime,type_id,sn,audit_time';
        $info=M('StocktakingInfo')->where($map)->field($field)->find();
        $info['all_stock']=floatval($info['all_stock']);
        $info['reality_sum']=floatval($info['reality_sum']);
        $info['profit_sum']=floatval($info['profit_sum']);
        $info['loss_sum']=floatval($info['loss_sum']);
        if(empty($info)){echo '无盘点记录';exit;}
        $map=array('stocktaking_id'=>$id);
        $field='goods_id,cate_id,supplier_id,shop_id,goods_name,goods_sn,goods_attr_sn,stock,reality,profit_num,loss_num,bad_money';
        $list=M('StocktakingGoods')->where($map)->field($field)->select();
        if(empty($list)){echo '暂无记录';exit;}
        foreach($list as $k=>$v){
            $list[$k]['attr_name']=D("Common/GoodsAttr")->goods_to_attrname($v['goods_attr_sn']);
            $list[$k]['stock']=floatval($v['stock']);
            $list[$k]['reality']=floatval($v['reality']);
            $list[$k]['profit_num']=floatval($v['profit_num']);
            $list[$k]['loss_num']=floatval($v['loss_num']);
            //$list[$k]['attr_name']=attr_key2name($v['goods_attr_sn'],$v['goods_id']);
            $list[$k]['cate_name']=idtoname($v['cate_id'],'PurchaseCategory');
            if($v['goods_attr_sn']){
                $map=array('goods_id'=>$v['goods_id'],'attr_key'=>$v['goods_attr_sn']);
                $goods_attr_sn=M('GoodsAttrStock')->where($map)->getField('goods_attr_sn');
                $list[$k]['goods_sn']=$goods_attr_sn;
            }
        }
        $data=array('info'=>$info,'list'=>$list);
        $this->assign($data);
        $this->display();
    }
    public function stocktaking_print(){
        $id = I('get.id');
        if(empty($id)){$this->error('参数错误',U('InvoicingOrder/stocktaking_list'));exit;}
        $template = 'stocktaking_goods_template';
        $map=array('id'=>$id,'info_type'=>0);
        $field='id,all_stock,reality_sum,profit_sum,loss_sum,remarks,status,addtime,audit_remarks';
        $info=M('StocktakingInfo')->where($map)->field($field)->find();
        if(empty($info)){$this->error('无盘点记录',U('InvoicingOrder/stocktaking_list'));exit;}
        $info['all_stock']=floatval($info['all_stock']);
        $info['reality_sum']=floatval($info['reality_sum']);
        $info['profit_sum']=floatval($info['profit_sum']);
        $info['loss_sum']=floatval($info['loss_sum']);
        $map=array('stocktaking_id'=>$id);
        $field='goods_id,cate_id,supplier_id,shop_id,goods_name,goods_sn,goods_attr_sn,stock,reality,profit_num,loss_num';
        $list=M('StocktakingGoods')->where($map)->field($field)->select();
        if(empty($list)){$this->error('暂无记录',U('InvoicingOrder/stocktaking_list'));exit;}
        foreach($list as $k=>$v){
            $list[$k]['attr_name']=D("Common/GoodsAttr")->goods_to_attrname($v['goods_attr_sn']);
            $list[$k]['stock']=floatval($v['stock']);
            $list[$k]['reality']=floatval($v['reality']);
            $list[$k]['profit_num']=floatval($v['profit_num']);
            $list[$k]['loss_num']=floatval($v['loss_num']);
            //$list[$k]['attr_name']=attr_key2name($v['goods_attr_sn'],$v['goods_id']);
            $list[$k]['cate_name']=idtoname($v['cate_id'],'PurchaseCategory');
            if($v['goods_attr_sn']){
                $map=array('goods_id'=>$v['goods_id'],'attr_key'=>$v['goods_attr_sn']);
                $goods_attr_sn=M('GoodsAttrStock')->where($map)->getField('goods_attr_sn');
                $list[$k]['goods_sn']=$goods_attr_sn;
            }
        }
        $url = C('WEB_URL');
        $phone = C('WEB_SITE_PHONE');
        $name = C('WEB_SITE_TITLE');
        $admin = idtoname(UID,'admin','username');
        $time = date('Y-m-d H:i:s',NOW_TIME);
        $this->assign('url',$url);
        $this->assign('phone',$phone);
        $this->assign('name',$name);
        $this->assign('admin',$admin);
        $this->assign('print_time',$time);
        $this->assign('order_info',$info);
        $this->assign('order_goods',$list);
        if($template){
            $map = array();
            $map['code'] = $template;
            $content = M('PrintTemplate')->where($map)->getField('content');
            $content1 = $this->fetch('',htmlspecialchars_decode($content));
            $this->assign('info',$content1);
        }
        $this->display('order_print');
    }
    /**盘点结束**/

    /**报损开始**/
    //报损记录
    function bad_list($is_return=false){
        $postdata=I('param.');
        $map=array();
        if($postdata['shop_id']){$map['type_id']=$postdata['shop_id'];}
        $map['type']=3;
        $map['info_type']=array('in','1,2');
        if($postdata['data_from']){$map['addtime'][] = array('egt',strtotime($postdata['data_from']));}
        if($postdata['data_to']){$map['addtime'][] = array('elt',strtotime($postdata['data_to']));}
        $field='id,type_id,addtime,admin_id,bad_all_num,bad_all_money,turnover_proportion,remarks,status,audit_name,audit_time,audit_remarks';
        if($is_return==false) {
            $list = page_list('StocktakingInfo', $map, 'addtime desc', $field);
            $goods_count=$all_bad_num=$all_bad_money=0;
            foreach ($list['list'] as $k => $v) {
                $list['list'][$k]['bad_all_num']=floatval($v['bad_all_num']);
                $list['list'][$k]['bad_all_money']=format_decimal($v['bad_all_money']);
                $all_bad_money+=$v['bad_all_money'];
            }
            $goods_count=M('StocktakingInfo')->where($map)->count();
            $all_bad_num=M('StocktakingInfo')->where($map)->sum('bad_all_num');
            $all_bad_money=M('StocktakingInfo')->where($map)->sum('bad_all_money');
            $this->assign($list);
            $this->assign($postdata);
            $this->assign('goods_count',$goods_count);
            $this->assign('all_bad_num',$all_bad_num);
            $this->assign('all_bad_money',$all_bad_money);
            $this->assign('stock_status', $this->stock_status);
            $this->get_shops_list();
            $this->display();
        }else{
            $list=M('StocktakingInfo')->where($map)->field($field)->select();
            $return=array('list'=>$list);
            return $return;
        }
    }

    public function bad_list_export(){
        $list=$this->bad_list(true);
        $title = array('报损仓库', '报损数量','报损总金额', '报损时间', '报损人', '备注', '审核状态','审核时间','审核人','审核备注');
        $data = array();
        $all_bad_num=$all_bad_money=0;
        foreach ($list['list'] as $k => $val) {
            $data[$k][] = idtoname($val['type_id'],"Shops",'name');
            $data[$k][] = floatval($val['bad_all_num']);
            $data[$k][] = format_price($val['bad_all_money']);
            $data[$k][] = time_format($val['addtime']);
            $data[$k][] = empty($val['admin_id'])?'':idtoname($val['admin_id'],'Shops','name');
            $data[$k][] = $val['remarks'];
            $data[$k][] = $this->stock_status[$val['status']];
            $data[$k][] = empty($val['audit_time'])?'':time_format($val['audit_time']);
            if ($val['status'] == 3 && $val['audit_name'] == '') {
                $data[$k][] = '自动';
            }elseif($val['audit_name']){
                $data[$k][]=$val['audit_name'];
            }else{$data[$k][]='';}
            $data[$k][] = $val['audit_remarks'];
            $all_bad_num+=$val['bad_all_num'];
            $all_bad_money+=$val['bad_all_money'];
        }
        $data[]=array('总计',floatval($all_bad_num),format_price($all_bad_money),'','','','','','','');
        export_csv('商品报损记录.csv',$title,$data);
        unset($title, $data);
        exit;
    }
    //报损信息
    function bad_info(){
        $getdata=I('get.');
        $id=intval($getdata['id']);
        if(empty($id)){echo '参数错误';exit;}
        $map=array('id'=>$id,'info_type'=>array('in','1,2'));
        $field='id,bad_all_money,remarks,status,info_type,addtime,type_id,sn,audit_time';
        $info=M('StocktakingInfo')->where($map)->field($field)->find();
        if(empty($info)){echo '无报损记录';exit;}
        $map=array('stocktaking_id'=>$id,'info_type'=>$info['info_type']);
        $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();
        if(empty($list)){echo '暂无记录';exit;}
        foreach($list as $k=>$v){
            $list[$k]['attr_name']=D("Common/GoodsAttr")->goods_to_attrname($v['goods_attr_sn']);
            $list[$k]['cate_name']=idtoname($v['cate_id'],'PurchaseCategory');
            $list[$k]['bad_num']=floatval($v['bad_num']);
            if($v['goods_attr_sn']){
                $map=array('goods_id'=>$v['goods_id'],'attr_key'=>$v['goods_attr_sn']);
                $goods_attr_sn=M('GoodsAttrStock')->where($map)->getField('goods_attr_sn');
                echo M('GoodsAttrStock')->getLastSql();
                $list[$k]['goods_sn']=$goods_attr_sn;
            }
        }
        $data=array('info'=>$info,'list'=>$list);
        $this->assign($data);
        $this->display();
    }
    /**
     * 报溢报损准备
     */
    public function bad_add(){
        $this->get_shops_list();
        $this->get_supplier_list();
        $this->getcateTree();
        $bad_type=array('1'=>'手动报损','2'=>'手动报溢');
        $this->assign('bad_type',$bad_type);
        $this->assign('shop_id',1);
        $this->display();
    }

    /**
     * 添加报溢报损
     */
    public function confirm_bad_add(){
        $return=array('status'=>0,'');
        $postdata=I('post.');
        if(empty($postdata['infos'])){$return=array('status'=>0,'msg'=>'请选择商品'); $this->ajaxReturn($return);}
        $now_time=NOW_TIME;
        $shop_id=intval($postdata['shop_id']);
        $shop_account_id=intval($postdata['shop_id']);
        $bad_all_money=floatval($postdata['all_price']);
        $bad_all_num=floatval($postdata['all_count']);
        $remarks=empty($postdata['remarks'])?'无':$postdata['remarks'];
        if($postdata['bad_type']==1){
            $qianzhui='BS';
        }elseif ($postdata['bad_type']==2){
            $qianzhui='BY';
        }
        $data=array(
            'sn'=>D('Common/InvoicingOrder')->invoicing_sn($qianzhui),
            'type'=>3,
            'type_id'=>$shop_id,
            'addtime'=>$now_time,
            'admin_id'=>$shop_account_id,
            'remarks'=>$remarks,
            'info_type'=>$postdata['bad_type'],
            'bad_all_money'=>$bad_all_money,
            'bad_all_num'=>$bad_all_num,
            'status'=>0,//审核状态
        );
        $id=M('StocktakingInfo')->add($data);
        if($id<=0){$return['msg']="添加报损失败";$this->ajaxReturn($return);}
        $goodslist=$postdata['infos'];
        foreach($goodslist['goods_id'] as $k => $v){
            $list_info=array(
                'stocktaking_id'=>$id,
                'goods_id'=>$v,
                'cate_id'=>0,
                'supplier_id'=>empty($goodslist['supplier_id'][$k])?0:$goodslist['supplier_id'][$k],
                'shop_id'=>$shop_id,
                'goods_name'=>$goodslist['goods_name'][$k],
                'goods_sn'=>$goodslist['goods_sn'][$k],
                'goods_attr_sn'=>empty($goodslist['goods_attr_sn'][$k])?0:$goodslist['goods_attr_sn'][$k],
                'remark'=>$remarks,
                'info_type'=>$postdata['bad_type'],
                'bad_money'=>$goodslist['all_money'][$k],
                'bad_num'=>$goodslist['bad_num'][$k],
                'status'=>0,//审核状态
            );
            $res=M('StocktakingGoods')->add($list_info);
        }
        if($res==false){$return['msg']="添加报损商品失败";$this->ajaxReturn($return);}
        action_log('create_bad_order', 'Admin', $id, UID);//操作日志
        $return['status']=1;
        $return['msg']='提交成功';
        $this->ajaxReturn($return);
    }
    public function bad_print()
    {
        $id = I('get.id');
        if(empty($id)){$this->error('参数错误',U('InvoicingOrder/bad_list'));exit;}
        $template = 'bad_goods_template';
        $map=array('id'=>$id,'info_type'=>1);
        $field='id,bad_all_money,remarks,status,addtime,bad_all_num';
        $info=M('StocktakingInfo')->where($map)->field($field)->find();
        if(empty($info)){$this->error('无报损记录',U('InvoicingOrder/bad_list'));exit;}
        $info['bad_all_num']=floatval($info['bad_all_num']);
        $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();
        if(empty($list)){$this->error('暂无记录',U('InvoicingOrder/bad_list'));exit;}
        foreach($list as $k=>$v){
            $list[$k]['attr_name']=D("Common/GoodsAttr")->goods_to_attrname($v['goods_attr_sn']);
            $list[$k]['goods_attrsn']=$v['goods_sn'];
            $list[$k]['cate_name']=idtoname($v['cate_id'],'PurchaseCategory');
            $list[$k]['bad_num']=floatval($v['bad_num']);
        }
        $url = C('WEB_URL');
        $phone = C('WEB_SITE_PHONE');
        $name = C('WEB_SITE_TITLE');
        $admin = idtoname(UID,'admin','username');
        $time = date('Y-m-d H:i:s',NOW_TIME);
        $this->assign('url',$url);
        $this->assign('phone',$phone);
        $this->assign('name',$name);
        $this->assign('admin',$admin);
        $this->assign('print_time',$time);
        $this->assign('order_info',$info);
        $this->assign('order_goods',$list);
        if($template){
            $map = array();
            $map['code'] = $template;
            $content = M('PrintTemplate')->where($map)->getField('content');
            $content1 = $this->fetch('',htmlspecialchars_decode($content));
            $this->assign('info',$content1);
        }
        $this->display('order_print');
    }
    /**报损结束**/


    public function stock_confirm_order(){
        $return=array('status'=>0,'msg'=>'');
        $postdata=I('post.');
        if(empty($postdata['id'])) {$return['msg']='参数错误'; $this->ajaxReturn($return);}
        if(empty($postdata['status'])){$return['msg']='请选择要进行的操作'; $this->ajaxReturn($return);}
        $type = empty($postdata['type'])?0:$postdata['type'];
        $map=array();
        $map['id']=$postdata['id'];
        $map['info_type']=$type;
        $map['type']=3;
        $map['status']=0;
        $stocktaking_info=M('StocktakingInfo')->where($map)->count();
        if(empty($stocktaking_info)) {$return['msg']='订单信息错误'; $this->ajaxReturn($return);}
        $admin_info=session('admin_info');
        $savedata=array();
        $savedata['status']=$postdata['status'];
        $savedata['audit_name']=$admin_info['username'];
        $savedata['audit_time']=NOW_TIME;
        $savedata['audit_remarks']=empty($postdata['audit_remarks'])?'':$postdata['audit_remarks'];
        $res = M('StocktakingInfo')->where($map)->save($savedata);
        if($res){
            $map=array();
            $map['status']=0;
            $map['stocktaking_id'] = $postdata['id'];
            $map['info_type'] = $type;
            $map['type'] = 3;
            $savedata=array();
            $savedata['status'] = $postdata['status'];
            $result=M('StocktakingGoods')->where($map)->save($savedata);
            //修改库存并记录日志
            if($postdata['status']==1){
                $map['status']=1;
                $stocktaking_goods = M('StocktakingGoods')->where($map)->field(true)->select();
                if($type==0) {
                    //盘点修改库存并记录日志
                    foreach ($stocktaking_goods as $k => $v) {
                        $map = array('goods_id' => $v['goods_id'], 'goods_stock' => empty($v['goods_attr_sn']) ? 0 : $v['goods_attr_sn'], 'shop_id' => $v['shop_id']);
                        $data_info = array('goods_number' => $v['reality']);
                        M('ShopsGoodsStock')->where($map)->save($data_info);
                        if ($v['loss_num'] > 0) {
                            $change_type = 1;
                            $change_number = $v['loss_num'];
                        } else {
                            $change_type = 0;
                            $change_number = $v['profit_num'];
                        }
                        $attr_key = empty($v['goods_attr_sn']) ? '' : $v['goods_attr_sn'];
                        change_stock_log($v['shop_id'], 0, $v['stock'], $v['goods_id'], $change_number, $change_type, '库存盘点修正', 7, $attr_key);
                    }
                }elseif($type==1 || $type==2){
                    //报损修改库存并记录日志
                    foreach($stocktaking_goods as $k => $v) {
                        $map = array('goods_id' => $v['goods_id'], 'goods_stock' => empty($v['goods_attr_sn']) ? 0 : $v['goods_attr_sn'], 'shop_id' => $v['shop_id']);
                        $stock = M('ShopsGoodsStock')->where($map)->getField('goods_number');
                        $attr_key = empty($v['goods_attr_sn']) ? '' : $v['goods_attr_sn'];
                        if($type==1){
                            M('ShopsGoodsStock')->where($map)->setDec('goods_number', $v['bad_num']);
                            change_stock_log($v['shop_id'], 0, $stock, $v['goods_id'], $v['bad_num'], 1, '商品报损', 8, $attr_key);
                        }elseif($type==2){
                            M('ShopsGoodsStock')->where($map)->setInc('goods_number', $v['bad_num']);
                            change_stock_log($v['shop_id'], 0, $stock, $v['goods_id'], $v['bad_num'], 0, '商品报损', 8, $attr_key);
                        }
                    }
                }
                $this->add_bad_stock($postdata['id'],$type);
            }
            $return['msg']='操作成功';
            if($type==0){$return['url']=U('InvoicingOrder/bad_list');}
            else{$return['url']=U('InvoicingOrder/stocktaking_list');}
            $return['status']=1;
            $this->ajaxReturn($return);
        }else{
            $return['msg']='操作失败';
            $this->ajaxReturn($return);
        }
    }
    public function add_bad_stock($id,$type){
        $map=array();
        $map['id']=$id;
        $map['info_type']=$type;
        $map['type']=3;
        $stocktaking_info=M('StocktakingInfo')->where($map)->field(true)->find();
        $map=array();
        $map['stocktaking_id']=$id;
        $map['info_type']=$type;
        $stocktaking_goods=M('StocktakingGoods')->where($map)->field(true)->select();
        $bs_money=0;$bs_count=0;$by_money=0;$by_count=0;
        foreach($stocktaking_goods as $k => $v){
            if($type==1){//报损报溢
                $bs_money+=floatval($v['bad_money']);
                $bs_count+=floatval($v['bad_num']);
            }
            if($type==2){
                $by_money+=floatval($v['bad_money']);
                $by_count+=floatval($v['bad_num']);
            }
            if($type==0){
                if(floatval($v['profit_num'])>0) {//盘盈
                    $by_count+=floatval($v['profit_num']);
                    $by_money+=floatval($v['bad_money']);
                }
                if(floatval($v['loss_num'])>0){
                    $bs_count+=floatval($v['loss_num']);
                    $bs_money+=floatval($v['bad_money']);
                }
            }
        }
        $data=array();
        $data['mtype']=0;
        $data['add_time']=NOW_TIME;
        $data['update_time']=NOW_TIME;
        $data['status']=3;
        if($bs_count>0){
            $data['sn']=D('Common/InvoicingOrder')->invoicing_sn('CK');
            $data['type']=7;
            $data['shop_id_out']=$stocktaking_info['type_id'];
            $data['all_money']=$bs_money;
            $data['count']=$bs_count;
            $data['goods_allmoney']=$bs_money;
            $bs_id=M('InvoicingOrder')->add($data);
        }
        if($by_count>0 || ($bs_count==0 && $by_count==0)){
            $data['sn']=D('Common/InvoicingOrder')->invoicing_sn('RK');
            $data['type']=8;
            $data['shop_id_in']=$stocktaking_info['type_id'];
            $data['all_money']=$by_money;
            $data['count']=$by_count;
            $data['goods_allmoney']=$by_money;
            $by_id=M('InvoicingOrder')->add($data);
        }
        if($bs_id!==false || $by_id!==false) {
            foreach ($stocktaking_goods as $ke => $vo) {
                $bs_goods = array();$by_goods=array();
                if($bs_id!==false && ($type==1 || ($type==0 && floatval($vo['loss_num'])>0))){
                    $bs_goods['order_id'] =  $bs_id;
                    if($type==1){
                        $bs_goods['freight_num'] =  $vo['bad_num'];
                        $bs_goods['request_num'] =  $vo['bad_num'];
                        $bs_goods['fact_num'] =  $vo['bad_num'];
                    }else{
                        $bs_goods['freight_num'] =  $vo['loss_num'];
                        $bs_goods['request_num'] =  $vo['loss_num'];
                        $bs_goods['fact_num'] =  $vo['loss_num'];
                    }
                    $bs_goods['all_money'] =  $vo['bad_money'];
                    $bs_goods['goods_id'] = $vo['goods_id'];
                    $bs_goods['goods_name'] = $vo['goods_name'];
                    $bs_goods['goods_sn'] = $vo['goods_sn'];
                    $bs_goods['goods_attr_sn'] = empty($vo['goods_attr_sn'])?'':$vo['goods_attr_sn'];
                    $bs_goods['supply_price'] = idtoname($vo['goods_id'], 'Goods', 'supply_price');
                    $bs_goods['shop_id'] = $vo['shop_id'];
                    $bs_goods['supplier_id'] = $vo['supplier_id'];
                    $bs_goods['storage_id'] = 1;
                    $bs_goods['status'] = 3;
                    $bs_goods['order_time'] = NOW_TIME;
                    $bs_goods['update_time'] = NOW_TIME;
                    $bs_goods['audit_status'] = 1;
                    $bs_goods['price'] = idtoname($vo['goods_id'], 'Goods', 'supply_price');
                    if(!empty($bs_goods)){
                        M('InvoicingGoods')->add($bs_goods);
                    }
                }
                if($by_id!==false && ($type==2 || ($type==0 && floatval($vo['profit_num'])>0) || ($type==0 && floatval($vo['profit_num'])==0 && floatval($vo['loss_num'])==0))){
                    $by_goods['order_id'] =  $by_id;
                    if($type==2) {
                        $by_goods['freight_num'] = $vo['bad_num'];
                        $by_goods['request_num'] = $vo['bad_num'];
                        $by_goods['fact_num'] = $vo['bad_num'];
                    }else{
                        $by_goods['freight_num'] = $vo['profit_num'];
                        $by_goods['request_num'] = $vo['profit_num'];
                        $by_goods['fact_num'] = $vo['profit_num'];
                    }
                    $by_goods['all_money'] =  $vo['bad_money'];
                    $by_goods['goods_id'] = $vo['goods_id'];
                    $by_goods['goods_name'] = $vo['goods_name'];
                    $by_goods['goods_sn'] = $vo['goods_sn'];
                    $by_goods['goods_attr_sn'] = empty($vo['goods_attr_sn'])?'':$vo['goods_attr_sn'];
                    $by_goods['supply_price'] = idtoname($vo['goods_id'], 'Goods', 'supply_price');
                    $by_goods['shop_id'] = $vo['shop_id'];
                    $by_goods['supplier_id'] = $vo['supplier_id'];
                    $by_goods['storage_id'] = 1;
                    $by_goods['status'] = 3;
                    $by_goods['order_time'] = NOW_TIME;
                    $by_goods['update_time'] = NOW_TIME;
                    $by_goods['audit_status'] = 1;
                    $by_goods['price'] = idtoname($vo['goods_id'], 'Goods', 'supply_price');
                    if(!empty($by_goods)){
                        M('InvoicingGoods')->add($by_goods);
                    }
                }
            }
        }
    }
    /**库存预警开始**/
    public function warning(){
        $postdata=I('request.');
        $stock_list=array(0=>'全部状态','1'=>"库存不足",'2'=>"库存过剩");
        $this->assign('stock_list',$stock_list);
        $map=array();
        $shop_id=$postdata['shop_id'];
        if(!empty($shop_id)){$map['a.shop_id']=$shop_id;}
        $suppliers_id=$postdata['suppliers_id'];
        if(!empty($suppliers_id)){$map['a.suppliers_id']=$suppliers_id;}
        if(!empty($postdata['stock_id'])){
            if($postdata['stock_id']==1){
                $map['_string']='a.goods_number <= g.lower_count';
            }elseif($postdata['stock_id']==2){
                $map['_string']='a.goods_number >= g.limit_count';
            }
        }else{
            $map['_string']='a.goods_number > g.limit_count or a.goods_number < g.lower_count';
        }
		
		if (!empty($postdata['catid'])) {
            $cat_sons = get_children($postdata['catid'], 1,5);
            $catstr = implode(',', $cat_sons);
            $extension_goods_id = get_extension_goods($postdata['catid'], 1);
            $extensionstr = implode(',', $extension_goods_id);
            $where = array();
            if (!empty($cat_sons) && !empty($catstr)) {
                $where['cat_id'] = array('in', $cat_sons);
            }
            if (!empty($extension_goods_id) && !empty($extensionstr)) {
                $where['id'] = array('in', $extension_goods_id);
            }
            if (!empty($where)) {
                $where['_logic'] = 'or';
                $map['_complex'] = $where;
            }
        }
		
		$map['g.limit_count']=array('neq',0);
		$map['g.lower_count']=array('neq',0);
		$map['g.is_delete']=0;
		
       /* $map['a.qh_count']=array('neq',0);
        $map['_string']='a.qh_count >= a.goods_number';*/
        $field='a.*,g.limit_count,g.lower_count';
        $join='LEFT JOIN __GOODS__ g ON g.id=a.goods_id';
        $list=page_list('ShopsGoodsStock',$map,'',$field,0,$join);
		
        foreach($list['list'] as $key=>$val){
            if($val['goods_stock'] && $val['goods_stock'] != 'null'){
                $list['list'][$key]['attr_info']=D("Common/GoodsAttr")->goods_to_attrname($val['goods_stock']);
                $map=array();
                $map['goods_id']=$val['goods_id'];
                $map['attr_key']=$val['goods_stock'];
                $list['list'][$key]['goods_sn']=M("GoodsAttrStock")->where($map)->getField('goods_attr_sn');
            }else{
                $map=array();
                $map['goods_id']=$val['goods_id'];
                $list['list'][$key]['goods_sn']=M("ShopsGoods")->where($map)->getField('goods_sn');
            }
            $list['list'][$key]['goods_number']=floatval($val['goods_number']);
        }
        $this->assign($list);
        $this->assign($postdata);
        $this->get_supplier_list();
        $this->get_shops_list();
		$this->add_getcateTree($postdata['catid'], '');
        $this->display();
    }
    /**库存预警结束**/
    /**
     * 搜索商品
     */
    public function search_goods(){
        $goods_sn=trim(I('post.goods_sn'));// 商品编号或名字
        $return = array('status'=>0,'msg'=>'');
        if(empty($goods_sn)){$return['msg'] = '请输入商品编号/名称';$this->ajaxReturn($return);}
        $map=array('goods_sn|goods_name'=>array('like', '%'.$goods_sn.'%'));//模糊查询
        $list=M('Goods')->where($map)->field('id,goods_name,goods_sn')->select();
        if(empty($list)){$return['msg']='暂未搜出商品';$this->ajaxReturn($return);}
        $return=array('status'=>1,'list'=>$list);
        $this->ajaxReturn($return);
    }

    /**
     * 库存查询
     */
    public function stock_search($is_return=false){
        $postdata=I('param.');
		if(!isset($postdata['catid'])) $postdata['catid'] = 0;
        $map=array();
        if(!isset($postdata['keyword'])){
            $postdata['keyword']='';
        }
        if ($postdata['keyword'] || $postdata['catid']) {
            $whereor = array();
			
			if (!empty($postdata['catid'])) {
				$cat_sons = get_children($postdata['catid'], 1,5);
				$catstr = implode(',', $cat_sons);
				$extension_goods_id = get_extension_goods($postdata['catid'], 1);
				$extensionstr = implode(',', $extension_goods_id);
				$where = array();
				if (!empty($cat_sons) && !empty($catstr)) {
					$where['cat_id'] = array('in', $cat_sons);
				}
				if (!empty($extension_goods_id) && !empty($extensionstr)) {
					$where['id'] = array('in', $extension_goods_id);
				}
				if (!empty($where)) {
					$where['_logic'] = 'or';
					$whereor['_complex'] = $where;
				}
			}
			
			if($postdata['keyword']){
				$whereor['id|goods_sn|goods_name'] = array('like', '%' . $postdata['keyword'] . '%');
			}
            $goods_ids = M('Goods')->where($whereor)->getField('id',true);
            if($goods_ids){
                $map['goods_id'] = array('in',$goods_ids);
            }else{
				$map['goods_id'] = array('in','');
			}
        }
		if(!empty($postdata['shop_id'])){$map['shop_id']=$postdata['shop_id'];}
        if(!empty($postdata['suppliers_id'])){$map['suppliers_id']=$postdata['suppliers_id'];}
        $map['status']=1;
        $map['group']="goods_id";
        if($is_return==false) $list=page_list("ShopsGoods",$map,'id desc');
        else {
            unset($map['group']);
            $list['list'] = M('ShopsGoods')->where($map)->field(true)->order('id desc')->group('goods_id')->select();
        }
        foreach($list['list'] as $key=>$val){
            $map=array();
            $map['goods_id']=$val['goods_id'];
			if(!empty($postdata['shop_id'])){$map['shop_id']=$postdata['shop_id'];}
            $map['status']=1;
            $total_stock=M("ShopsGoodsStock")->where($map)->getField("sum(goods_number)");
            $list['list'][$key]['total_stock']=floatval($total_stock);
        }
        if($is_return==false) {
            $this->assign($list);
            $this->assign($postdata);
            $this->get_shops_list();
            $this->get_supplier_list();
			$this->add_getcateTree($postdata['catid'], '');
            $this->display();
        }else{
            return $list;
        }
    }
    public function stock_info(){
        $postdata=I('param.');
        if(empty($postdata['id'])){echo '参数错误';exit;}
        $map=array();
        $map['goods_id']=$postdata['id'];
        $map['status']=1;
        $shop_info=M("ShopsGoodsStock")->where($map)->field(true)->select();
        foreach($shop_info as $key=>$val){
            if($val['goods_stock']){
                $shop_info[$key]['attr_info']=D("Common/GoodsAttr")->goods_to_attrname($val['goods_stock']);
                if(empty($shop_info[$key]['attr_info'])) {unset($shop_info[$key]); continue;}
                $map=array();
                $map['goods_id']=$val['goods_id'];
                $map['attr_key']=$val['goods_stock'];
                $goods_attr_sn=M("GoodsAttrStock")->where($map)->getField('goods_attr_sn');
                if($goods_attr_sn) {
                    $shop_info[$key]['goods_sn']=$goods_attr_sn;
                } else{
                    $map=array();
                    $map['id']=$val['goods_id'];
                    $shop_info[$key]['goods_sn']=M('Goods')->where($map)->getField('goods_sn');
                }
            }else{
                $map=array();
                $map['goods_id']=$val['goods_id'];
                $map['shop_id']=$val['shop_id'];
                $shop_info[$key]['goods_sn']=M("ShopsGoods")->where($map)->getField('goods_sn');
            }
            $shop_info[$key]['goods_number']=floatval($val['goods_number']);
        }
        if(empty($shop_info)){echo '暂无仓库';exit;}
        $this->assign('list',$shop_info);
        $this->display();
    }

    public function stock_search_export(){
        $postdata=I('get.');
        $list=$this->stock_search(true);
        if(empty($postdata['shop_id'])){
            $title = array('商品名称', '商品编号','供货商', '库存', '进货价', '售价');
            $data = array();
            foreach ($list['list'] as $k => $v) {
                $data[$k][] = idtoname($v['goods_id'],'Goods','goods_name');
                $data[$k][] = $v['goods_sn'];
                $data[$k][] = empty($v['suppliers_id'])?'':idtoname($v['suppliers_id'],'Suppliers','name');
                $data[$k][] = $v['total_stock'];
                $data[$k][] = format_price(idtoname($v['goods_id'],'Goods','supply_price'));
                $data[$k][] = format_price(idtoname($v['goods_id'],'Goods','shop_price'));
            }
            export_csv('库存查询.csv',$title,$data);
            unset($title, $data);
            exit;
        }else{
            foreach($list['list'] as $v){
                $ids[]=$v['goods_id'];
            }
            $map=array();
            $map['shop_id']=$postdata['shop_id'];
            $map['goods_id']=array('in',$ids);
            $shop_info=M("ShopsGoodsStock")->where($map)->field(true)->select();
            $title = array('商品名称', '商品编号','商品属性','供货商', '库存', '进货价', '售价','仓库名称');
            $data = array();
            foreach($shop_info as $k=>$v){
                $data[$k][] = idtoname($v['goods_id'],'Goods','goods_name');
                if($v['goods_stock']){
                    $map=array();
                    $map['goods_id']=$v['goods_id'];
                    $map['attr_key']=$v['goods_stock'];
                    $goods_attr_sn=M("GoodsAttrStock")->where($map)->getField('goods_attr_sn');
                }
                if($goods_attr_sn) {
                    $data[$k][]=$goods_attr_sn;
                } else{
                    $map=array();
                    $map['id']=$v['goods_id'];
                    $data[$k][]=M('Goods')->where($map)->getField('goods_sn');
                }
                $data[$k][] = empty($v['goods_stock'])?'':attr_key2name($v['goods_stock'],$v['goods_id']);
                $data[$k][] = empty($v['suppliers_id'])?'':idtoname($v['suppliers_id'],'Suppliers','name');
                $data[$k][] = floatval($v['goods_number']);
                $data[$k][] = format_price(idtoname($v['goods_id'],'Goods','supply_price'));
                $data[$k][] = format_price(idtoname($v['goods_id'],'Goods','shop_price'));
                $data[$k][] = format_price(idtoname($postdata['shop_id'],'Shops','name'));
            }
            export_csv('库存查询.csv',$title,$data);
            unset($title, $data);
            exit;
        }
    }

    /**
     * 仓库对账
     */
    public function shop_balance($is_return=false){
        $map=array();
        $map['shop_id_in']=array('neq',0);
        $map['shop_id_out']=array('neq',0);
        $map['type']=4;
        $postdata=I('param.');
        $shop_id=intval($postdata['shop_id']);
        if(!empty($shop_id)){$map['shop_id_in|shop_id_out']=$shop_id;}
        if(empty($postdata['data_from']))$postdata['data_from']=date('Y-m-d 00:00:00', time());
        if(empty($postdata['data_to']))$postdata['data_to']=date('Y-m-d 23:59:59', time());
        if($postdata['data_from']){$map['update_time'][] = array('egt',strtotime($postdata['data_from']));}
        if($postdata['data_to']){$map['update_time'][] = array('elt',strtotime($postdata['data_to']));}
        $field="id,shop_id_in,shop_id_out,count(id) as order_count,sum(count) as goods_number,sum(all_money) as all_price,sum(money) as yue_money,sum(online_money) as all_online_money,sum(offline_money) as all_offline_money";
        $map['status']=3;//已完成
        //调入统计
        $info=M('InvoicingOrder')->where($map)->group('shop_id_in')->field($field)->select();
        $list=array();
        foreach($info as $k=>$v){
            $list[$v['shop_id_in']]['shop_id_in']=$v['shop_id_in'];
            $list[$v['shop_id_in']]['shop_name']=idtoname($v['shop_id_in'],'Shops');
            $list[$v['shop_id_in']]['in_count']=$v['order_count'];
            $list[$v['shop_id_in']]['in_number']=floatval($v['goods_number']);
            $list[$v['shop_id_in']]['in_price']=$v['all_price'];
            $list[$v['shop_id_in']]['in_yue_price']=$v['yue_price'];
            $list[$v['shop_id_in']]['in_online_price']=$v['online_price'];
            $list[$v['shop_id_in']]['in_offline_price']=$v['offline_price'];
        }
        //调出统计
        $info=M('InvoicingOrder')->where($map)->group('shop_id_out')->field($field)->select();
        foreach($info as $k=>$v){
            //$list[$v['shop_id_out']]['shop_name']=idtoname($v['shop_id_out'],'Shops');
            $list[$v['shop_id_out']]['out_count']=$v['order_count'];
            $list[$v['shop_id_out']]['out_number']=floatval($v['goods_number']);
            $list[$v['shop_id_out']]['out_price']=$v['all_price'];
            $list[$v['shop_id_out']]['out_yue_price']=$v['yue_price'];
            $list[$v['shop_id_out']]['out_online_price']=$v['online_price'];
            $list[$v['shop_id_out']]['out_offline_price']=$v['offline_price'];
            $map=array();
            $map['order_id']=$v['id'];
            $goods_info=M('InvoicingGoods')->where($map)->field('goods_id,fact_num,supply_price')->select();
            foreach($goods_info as $key => $val){
                $map=array();
                $map['goods_id']=$val['goods_id'];
                $map['shop_id']=$v['shop_id_out'];
                $avg_price=M('ShopsGoods')->where($map)->getField('avg_price');
                $list[$v['shop_id_out']]['profit']=floatval(($val['supply_price']-$avg_price)*$val['fact_num']);
            }
        }
        foreach($list as $ke => $vo){
            $list[$ke]['in_count']=$vo['in_count']?$vo['in_count']:0;
            $list[$ke]['in_number']=$vo['in_number']?$vo['in_number']:0;
            $list[$ke]['in_price']=$vo['in_price']?$vo['in_price']:'0.00';
            $list[$ke]['in_yue_price']=$vo['in_yue_price']?$vo['in_yue_price']:'0.00';
            $list[$ke]['in_online_price']=$vo['in_online_price']?$vo['in_online_price']:'0.00';
            $list[$ke]['in_offline_price']=$vo['in_offline_price']?$vo['in_offline_price']:'0.00';
            $list[$ke]['out_count']=$vo['out_count']?$vo['out_count']:0;
            $list[$ke]['out_number']=$vo['out_number']?$vo['out_number']:0;
            $list[$ke]['out_price']=$vo['out_price']?$vo['out_price']:'0.00';
            $list[$ke]['out_yue_price']=$vo['out_yue_price']?$vo['out_yue_price']:'0.00';
            $list[$ke]['out_online_price']=$vo['out_online_price']?$vo['out_online_price']:'0.00';
            $list[$ke]['out_offline_price']=$vo['out_offline_price']?$vo['out_offline_price']:'0.00';
            $list[$ke]['profit']=$vo['profit']?$vo['profit']:'0.00';
            $list[$ke]['shop_id_in']=$vo['shop_id_in'];
            $data=array(
                'in_order_count'=>array_sum(array_map(function($vo){return $vo['in_count'];},$list)),
                'in_order_num'=>array_sum(array_map(function($vo){return $vo['in_number'];},$list)),
                'in_order_yue_price'=>format_decimal(array_sum(array_map(function($vo){return $vo['in_yue_price'];},$list))),
                'in_order_online_price'=>format_decimal(array_sum(array_map(function($vo){return $vo['in_online_price'];},$list))),
                'in_order_offline_price'=>format_decimal(array_sum(array_map(function($vo){return $vo['in_offline_price'];},$list))),
                'in_order_price'=>format_decimal(array_sum(array_map(function($vo){return $vo['in_price'];},$list))),
                'out_order_count'=>array_sum(array_map(function($vo){return $vo['out_count'];},$list)),
                'out_order_num'=>array_sum(array_map(function($vo){return $vo['out_number'];},$list)),
                'out_order_yue_price'=>format_decimal(array_sum(array_map(function($vo){return $vo['out_yue_price'];},$list))),
                'out_order_online_price'=>format_decimal(array_sum(array_map(function($vo){return $vo['out_online_price'];},$list))),
                'out_order_offline_price'=>format_decimal(array_sum(array_map(function($vo){return $vo['out_offline_price'];},$list))),
                'out_order_price'=>format_decimal(array_sum(array_map(function($vo){return $vo['out_price'];},$list))),
                'order_profit'=>array_sum(array_map(function($vo){return $vo['profit'];},$list)),
            );
        }
        if($is_return==true){
            $return=array('data'=> $data,'list'=> $list);
            return $return;
        }else {
            $this->assign('list', $list);
            $this->assign('data',$data);
            $this->assign($postdata);
            $this->get_shops_list();
            $this->display();
        }
    }

    /**
     * 供货商结算导出
     */
    public function shop_balance_export(){
        $shop_balance=$this->shop_balance(true);
        $title = array('仓库名称', '调入货单数','调入商品数量','调入余额支付总额','调入线上支付总额','调入线下支付总额', '调入总价', '调出货单数', '调出商品数量','调出余额支付总额','调出线上支付总额','调出线下支付总额', '调出总价','调出利润');
        $data = array();
        foreach ($shop_balance['list'] as $k => $v) {
            $data[$k][] = $v['shop_name'];
            $data[$k][] = $v['in_count'];
            $data[$k][] = $v['in_number'];
            $data[$k][] = $v['in_yue_price'];
            $data[$k][] = $v['in_online_price'];
            $data[$k][] = $v['in_offline_price'];
            $data[$k][] = $v['out_count'];
            $data[$k][] = $v['out_number'];
            $data[$k][] = $v['out_yue_price'];
            $data[$k][] = $v['out_online_price'];
            $data[$k][] = $v['out_offline_price'];
            $data[$k][] = $v['out_price'];
            $data[$k][] = $v['profit'];
        }
        $data[]=array(
            '总计：',
            $shop_balance['data']['in_order_count'],
            $shop_balance['data']['in_order_num'],
            $shop_balance['data']['in_order_yue_price'],
            $shop_balance['data']['in_order_online_price'],
            $shop_balance['data']['in_order_offline_price'],
            $shop_balance['data']['in_order_price'],
            $shop_balance['data']['out_order_count'],
            $shop_balance['data']['out_order_num'],
            $shop_balance['data']['out_order_yue_price'],
            $shop_balance['data']['out_order_online_price'],
            $shop_balance['data']['out_order_offline_price'],
            $shop_balance['data']['out_order_price'],
            $shop_balance['data']['order_profit'],
        );
        export_csv('',$title,$data);
        unset($title, $data);
        exit;
    }
    /**
     * 结算记录
     */
    public function settlement_record(){
        $postdata=I('param.');
        if(!empty($shop_id)){$map['shop_id_in|shop_id_out']=$shop_id;}
        if(empty($postdata['data_from']))$postdata['data_from']=date('Y-m-d 00:00:00', time());
        if(empty($postdata['data_to']))$postdata['data_to']=date('Y-m-d 23:59:59', time());
        if($postdata['data_from']){$map['add_time'][] = array('egt',strtotime($postdata['data_from']));}
        if($postdata['data_to']){$map['add_time'][] = array('elt',strtotime($postdata['data_to']));}
        if(!empty($postdata['supplier_id'])) $map['supplier_id']=$postdata['supplier_id'];
        $list = $this->lists("InvoicingSupplierLog", $map);
        $all_money=$fact_money=0;
        foreach($list as $k => $v){
            $list[$k]['supplier_name']=idtoname($v['supplier_id'],"Suppliers",'name');
            $all_money+=$v['all_money'];
            $fact_money+=$v['fact_money'];
        }
        $this->assign('list',$list);
        $this->assign('all_money',format_decimal($all_money));
        $this->assign('fact_money',format_decimal($fact_money));
        //print_r($list);exit;
        $this->assign($postdata);
        $this->display();
    }
	/**
     * 得到节点树
     */
    private function add_getcateTree($pid = '', $assign = ''){
		$GoodsCategory = getcache('PurchaseCategory');
        $Tree = new \Common\Vendor\Tree();
        $select_categorys = '';
        $treemini = $Tree->treemini($GoodsCategory);
        $select_categorys .= $Tree->treeminioption($treemini, $pid);
        if ($assign) return $select_categorys; else $this->assign('select_categorys', $select_categorys);
	}
    /**
     * 差异审核页面
     */
    public function differ_info(){
        $getdata=I('get.');
        $id=intval($getdata['id']);
        if(empty($id)){echo '参数错误';exit;}
        $map=array();
        $map['id']=$id;
        $map['status']=array('in','3,4');
        $order_info=M('InvoicingOrder')->where($map)->field('id,pay_code,pay_status,is_pay')->find();
        $map=array();
        $map['order_id']=$order_info['id'];
        $order_goods=M('InvoicingGoods')->where($map)->field('price,discount_extra,request_num,fact_num,freight_num')->select();
        $differ_money=$all_differ_num=$fact_money=$request_money=$request_num=$fact_num=0;
        foreach($order_goods as $k =>$v){
            $differ_price=$differ_num=0;
            $differ_price=$v['price']-$v['discount_extra'];
            $differ_num=$v['request_num']-$v['fact_num'];
            $differ_money+=$differ_num*$differ_price;
            $all_differ_num+=$differ_num;
            $fact_num+=$v['fact_num'];
            $fact_money+=format_decimal($v['fact_num']*$differ_price);
            $request_money+=format_decimal($v['request_num']*$differ_price);
            $request_num+=$v['request_num'];
        }
        $this->assign($order_info);
        $this->assign('differ_money',abs($differ_money));
        $this->assign('all_differ_num',abs($all_differ_num));
        $this->assign('fact_money',$fact_money);
        $this->assign('fact_num',$fact_num);
        $this->assign('request_money',$request_money);
        $this->assign('request_num',$request_num);
        $this->display();
    }
    /**
     * 差异库存审核操作
     */
    public function differ_confirm(){
        $return=array('status'=>0,'msg'=>'');
        $postdata=I('post.');
        if(empty($postdata['id'])){$return['msg']='参数错误';$this->ajaxReturn($return);}
        $map=array();
        $map['id']=$postdata['id'];
        $map['status']=array('in','3,4');
        $map['audit_status']=0;
        $order_info=M('InvoicingOrder')->where($map)->field('id,sn,shop_id_in,shop_id_out,status,pay_code,is_pay,pay_status')->find();
        if(empty($order_info)){$return['msg']='订单不存在'; $this->ajaxReturn($return);}
        $savedata=array();
        if($postdata['differ_type']==0){
            $savedata['audit_status']=1;
        }else{
            $savedata['audit_status']=2;
        }
        $savedata['audit_time']=NOW_TIME;
        $admininfo=session('admin_info');
        $savedata['audit_id']=$admininfo['id'];
        $res=M('InvoicingOrder')->where($map)->save($savedata);
        if($res!==false){
            $map=array();
            $map['order_id']=$postdata['id'];
            $map['status']=array('in','3,4');
            $map['audit_status']=0;
            $savedata=array();
            if($postdata['differ_type']==0){
                $savedata['audit_status']=1;
            }else{
                $savedata['audit_status']=2;
            }
            M('InvoicingGoods')->where($map)->save($savedata);
            if($postdata['differ_type']==1) {
                $map['audit_status']=2;
                $order_goods=M('InvoicingGoods')->where($map)->field('goods_id,goods_attr_sn,differ_num,request_num,freight_num,price,discount_extra')->select();
                foreach ($order_goods as $k => $v) {
                    if($order_info['status']==3) {
                        if (floatval($v['differ_num']) != 0) {
                            $map = array();
                            $map['goods_id'] = $v['goods_id'];
                            $map['goods_stock'] = empty($v['goods_attr_sn']) ? 0 : $v['goods_attr_sn'];
                            $map['shop_id'] = $order_info['shop_id_out'];
                            $out_goods_number = M('ShopsGoodsStock')->where($map)->getField('goods_number');
                            $map['shop_id'] = $order_info['shop_id_in'];
                            $in_goods_number = M('ShopsGoodsStock')->where($map)->getField('goods_number');
                            if (floatval($v['differ_num']) > 0) {//给出库仓库加库存，入库仓库减库存
                                $new_out = floatval($out_goods_number) + floatval($v['differ_num']);
                                $new_in = floatval($in_goods_number) - floatval($v['differ_num']);
                                $out_desc = $order_info['sn'] . '差异库存拒绝仓库' . $order_info['shop_id_out'] . '加库存';
                                change_stock_log($order_info['shop_id_out'], $order_info['id'], $out_goods_number, $v['goods_id'], $v['differ_num'], 0, $out_desc, 6, $v['goods_attr_sn']);
                                $in_desc = $order_info['sn'] . '差异库存拒绝仓库' . $order_info['shop_id_in'] . '减库存';
                                change_stock_log($order_info['shop_id_in'], $order_info['id'], $in_goods_number, $v['goods_id'], $v['differ_num'], 1, $in_desc, 6, $v['goods_attr_sn']);
                            } else {
                                $new_out = floatval($out_goods_number) - abs(floatval($v['differ_num']));
                                $new_in = floatval($in_goods_number) + abs(floatval($v['differ_num']));
                                $out_desc = $order_info['sn'] . '差异库存拒绝仓库' . idtoname($order_info['shop_id_out'], 'Shops', 'name') . '减库存';
                                change_stock_log($order_info['shop_id_out'], $order_info['id'], $out_goods_number, $v['goods_id'], abs($v['differ_num']), 1, $out_desc, 6, $v['goods_attr_sn']);
                                $in_desc = $order_info['sn'] . '差异库存拒绝仓库' . idtoname($order_info['shop_id_in'], 'Shops', 'name') . '加库存';
                                change_stock_log($order_info['shop_id_in'], $order_info['id'], $in_goods_number, $v['goods_id'], abs($v['differ_num']), 0, $in_desc, 6, $v['goods_attr_sn']);
                            }
                            $savedata = array();
                            $map['shop_id'] = $order_info['shop_id_out'];
                            $savedata['goods_number'] = $new_out;
                            M('ShopsGoodsStock')->where($map)->save($savedata);
                            $savedata = array();
                            $map['shop_id'] = $order_info['shop_id_in'];
                            $savedata['goods_number'] = $new_in;
                            M('ShopsGoodsStock')->where($map)->save($savedata);
                        } else {
                            break;
                        }
                    }elseif($order_info['status']==4){
                        $map = array();
                        $map['goods_id'] = $v['goods_id'];
                        $map['goods_stock'] = empty($v['goods_attr_sn']) ? 0 : $v['goods_attr_sn'];
                        $map['shop_id'] = $order_info['shop_id_out'];
                        $out_goods_number = M('ShopsGoodsStock')->where($map)->getField('goods_number');
                        $map['shop_id'] = $order_info['shop_id_in'];
                        $in_goods_number = M('ShopsGoodsStock')->where($map)->getField('goods_number');
                        $new_out = floatval($out_goods_number) - floatval($v['freight_num']);
                        $new_in = floatval($in_goods_number) + floatval($v['freight_num']);
                        $out_desc = $order_info['sn'] . '差异库存拒绝仓库' . $order_info['shop_id_out'] . '减库存';
                        change_stock_log($order_info['shop_id_out'], $order_info['id'], $out_goods_number, $v['goods_id'], $v['differ_num'], 1, $out_desc, 6, $v['goods_attr_sn']);
                        $in_desc = $order_info['sn'] . '差异库存拒绝仓库' . $order_info['shop_id_in'] . '减库存';
                        change_stock_log($order_info['shop_id_in'], $order_info['id'], $in_goods_number, $v['goods_id'], $v['differ_num'], 0, $in_desc, 6, $v['goods_attr_sn']);
                        $savedata = array();
                        $map['shop_id'] = $order_info['shop_id_out'];
                        $savedata['goods_number'] = $new_out;
                        M('ShopsGoodsStock')->where($map)->save($savedata);
                        $savedata = array();
                        $map['shop_id'] = $order_info['shop_id_in'];
                        $savedata['goods_number'] = $new_in;
                        M('ShopsGoodsStock')->where($map)->save($savedata);
                    }
                }
            }
            if($order_info['pay_code']!='HANCHAO_DAOFU' && $order_info['is_pay']==1 && $order_info['pay_status']==3) {
                if ($postdata['differ_type'] == 1) $is_refuse = 1;
                else $is_refuse = 0;
                if ($order_info['status'] == 3) $is_return = 0;
                if ($order_info['status'] == 4) $is_return = 2;
                $money = $postdata['money'];
                D('Common/InvoicingOrder')->return_shop_money($order_info['shop_id_in'], $order_info['id'], $is_return, $money, $is_refuse);
            }
            $return['status']=1;
            $return['msg']='操作成功';
            $this->ajaxReturn($return);
        }else{
            $return['msg']='操作失败';
            $this->ajaxReturn($return);
        }
    }


    /**
     * 订货单管理列表 
     * jxr start 18.10.11 
     */
    public function order_ding(){
        $postdata = I('param.');
        $sn = $postdata['sn'];
        $shopid=$postdata['shopid'];
        $this->get_shops_list();
        if($sn){$map['sn'] = array('like','%'.$sn.'%');}
        $map['status'] = 1;    //配货中
        $map['type'] = 0;    //订货单
        if($shopid){$map_or=array('shop_id_in'=>$shopid,'shop_id_out'=>$shopid,'_logic'=>'or');$map['_complex']=$map_or;}
        if($postdata['data_from']){$map['add_time'][] = array('egt',strtotime($postdata['data_from']));}
        if($postdata['data_to']){$map['add_time'][] = array('elt',strtotime($postdata['data_to']));}
        $list = $this->lists('InvoicingOrder',$map);
        $goods_count=M('InvoicingOrder')->where($map)->count();
        $this->assign('list',$list);
        $this->assign('goods_count',$goods_count);
        $this->assign($postdata);
        $this->display();
    }

    /**
     * 商品批量配送列表
     * jxr start 18.10.11 
     */
    public function goods_batch_send($is_return=""){
        $postdata = I('param.');
        $map=array(); 
        $map['type']=0;//订货单
        $map['status']=1;//配货中
        if(!empty($postdata['sn'])){$map['sn']=$postdata['sn'];}
        if($postdata['data_from']){$map['add_time'][] = array('egt',strtotime($postdata['data_from']));}
        if($postdata['data_to']){$map['add_time'][] = array('elt',strtotime($postdata['data_to']));}
        $list=M('InvoicingOrder')->where($map)->field('GROUP_CONCAT(id) as ids,shop_id_out')->group('shop_id_out')->select();
        if($list){
            $list_data=array();
            foreach ($list as $key => $value) {
                $list_data[$value['shop_id_out']]=$value['ids'];
            }
        }
         
        if($list_data){
            $map=array();
            foreach ($list_data as $k => $v) {
                $map['order_id']=array('in',$v);
                $list_data[$k]=M('InvoicingGoods')->where($map)->field('*,sum(request_num) as num')->group('goods_sn')->select();
            }
        }
        if($list_data){
            foreach($list_data as $key=>$va){
                foreach($va as $k=>$val){
                    if($val['goods_attr_sn']){
                        $index=$val['goods_id'].'-'.$val['goods_attr_sn'];
                        $va[$k]['name']=D("Common/GoodsAttr")->goods_to_attrname($val['goods_attr_sn']);
                    }
                    if($key){
                        $va[$k]['shop_out_id']=$key;
                        $map=$where=array();
                        $map['id']=$key;
                        $va[$k]['shop_name']=M("Shops")->where($map)->cache(true)->getField('name');
                        $where['goods_id']=$val['goods_id'];
                        $where['shop_id']=$key;
                        if($val['goods_attr_sn'])$where['goods_stock']=$val['goods_attr_sn'];
                        else $where['goods_stock']=0;
                        $stock=M('ShopsGoodsStock')->where($where)->sum('goods_number');
                        $va[$k]['stock']=floatval($stock);
                    }
                }
                $list_data[$key]=$va;
            }
        }
        $this->assign($postdata);
        if($is_return==false) {
            $this->assign('list',$list_data);
            $this->display();
        }else{
            return $list_data;
        }
    }

    //商品批量配送列表导出
    public function goods_send_export(){
        $goods_send=$this->goods_batch_send(true);
        $title = array('商品名称','商品编码','商品属性', '进货数', '出货仓库', '库存参考');
        $data = array();
        $i=1;
        foreach ($goods_send as $key => $value) {
            foreach ($value as $k => $v) {
                $i=$i+1;
                $data[$i][] = $v['goods_name'];
                $data[$i][] = $v['goods_sn'];
                $data[$i][] = empty($v['name'])?'':$v['name'];
                $data[$i][] = $v['num'];
                $data[$i][] = $v['shop_name'];
                $data[$i][] = empty($v['stock'])?0:$v['stock'];
            }
        }
        export_csv('商品配货明细.csv',$title,$data);
        unset($title, $data);
        exit;
    }

    /**
     * 批量配货详情
     */
    public function send_detail($is_return=""){
        $postdata = I('param.');
        $shop_id_out=intval($postdata['shop_id_out']);
        $goods_id=$postdata['goods_id'];
        $goods_sn=$postdata['goods_sn'];
        $map=array(); 
        $map['a.shop_id_out']=$shop_id_out;//出库仓库id
        $map['a.type']=0;//订货单
        $map['a.status']=1;//出库仓库id
        if($goods_sn) $map['g.goods_sn']=$goods_sn;
        else $map['g.goods_id']=$goods_id;
        $field='a.sn,a.shop_id_in,g.*';
        $join='LEFT JOIN __INVOICING_GOODS__ g ON a.id=g.order_id';
        
        if($is_return==false){$list=page_list('InvoicingOrder',$map,'',$field,20,$join);
        }else {
            $list['list'] = M('InvoicingOrder')->alias('a')->join($join)->where($map)->field($field)->select();
        }
        $this->assign($postdata);
        if($is_return==false) {
            $this->assign('list',$list);
            $this->display();
        }else{
            return $list;
        }
    }


    //批量配货详情导出
    public function send_detail_export(){
        $list=$this->send_detail(true);
        $title = array('商品名称','商品编码','订单id','进货数','配货数');
        $data = array();
        foreach ($list['list'] as $k => $v) {
            $data[$k][] = $v['goods_name'];
            $data[$k][] = $v['goods_sn'];
            $data[$k][] = $v['order_id'];
            $data[$k][] = $v['request_num'];
            $data[$k][] = $v['freight_num'];
        }
        export_csv('商品批量配货明细.csv',$title,$data);
        unset($title, $data);
        exit;
    }

    /**
     * 修改配货数量
     */
    public function update_freight_num(){
        $return=array('status'=>0,'msg'=>'');
        $postdata = I('param.');
        $map=$data=array(); 
        $map['order_id']=$postdata['order_id'];
        $map['goods_sn']=$postdata['goods_sn'];
        $data['freight_num']=$postdata['freight_num'];
        $data['tab_status']=1; //修改标记
        $request=M('InvoicingGoods')->where($map)->save($data);
        if($request==true){
            $return['status']=1;
        }else{
            $return['msg']="操作失败";
        }
        $this->ajaxReturn($return);
    }

    /**
     * 未支付订单 确定为已支付
     */
    public function pay_remark(){
        $postdata = I('param.');
        if (IS_POST) {
            $paylogsave=$paylogwhere=array(); 
            $paylogsave['is_paid'] = 1;
            $paylogsave['update_time'] = NOW_TIME;
            $paylogsave['remarks']=$postdata['remarks'];
            $paylogwhere['type']=30;
            $paylogwhere['payment_id']=9;
            $paylogwhere['order_id']=array('in',$postdata['id']);
            $res = M('PayLog')->where($paylogwhere)->save($paylogsave);
            if ($res) {
                $orderwhere=$updatedata=array();
                $orderwhere['id'] = $postdata['id'];
                $orderwhere['pay_status'] = array('neq',3);
                $orderwhere['status'] = array('lt',3);
                $updatedata['pay_status'] =3;
                $updatedata['pay_time'] = NOW_TIME;
                $updatedata['pay_remarks']=$postdata['remarks'];
                $request=M('InvoicingOrder')->where($orderwhere)->save($updatedata);
            }
            if($request==true){
                $this->success('操作成功！');
            }else{
                $this->error('操作失败！');
            }
        }else{
            if(!$postdata['id']){$this->error("参数错误！");}
            $this->assign($postdata);
            $this->display();
        }
    }
    // jxr end 18.10.11

    public function order_ding_audit(){
        $postdata = I('param.');
        $sn = $postdata['sn'];
        $shopid=$postdata['shopid'];
        $pay_type=$postdata['pay_status'];
        $this->get_shops_list();
        if($sn){$map['sn'] = array('like','%'.$sn.'%');}
        $map['status'] = 0;
        $map['type'] = 0;
        $map['mtype'] = 1;
        if($pay_type==1) {$map['is_pay']=1;$map['pay_status']=array('elt',2);}
        if($pay_type==2) {$map['_string']="is_pay =0 OR pay_status = 3";}
        if($shopid){$map_or=array('shop_id_in'=>$shopid,'shop_id_out'=>$shopid,'_logic'=>'or');$map['_complex']=$map_or;}
        if($postdata['data_from']){$map['add_time'][] = array('egt',strtotime($postdata['data_from']));}
        if($postdata['data_to']){$map['add_time'][] = array('elt',strtotime($postdata['data_to']));}
        $list = $this->lists('InvoicingOrder',$map);
        $goods_count=M('InvoicingOrder')->where($map)->count();
        $this->assign('list',$list);
        $this->assign('goods_count',$goods_count);
        $this->assign($postdata);
        $this->display();
    }
    /*
     * 进销存商品汇总统计
     */
    public function statistics($is_return=false){
        $postdata=I('param.');
        $order_type = array('0'=>'仓库订货','1'=>'仓库进货','4'=>'仓库调货');
        $shop_types = array('0'=>'调出','1'=>'调入');
        $goods_ids=$map=$data=array();
        //按照分类查询商品
        if (!empty($postdata['catid'])) {
            $cat_sons = get_children($postdata['catid'], 1,5);
            $catstr = implode(',', $cat_sons);
            $extension_goods_id = get_extension_goods($postdata['catid'], 1);
            $extensionstr = implode(',', $extension_goods_id);
            $where = $rg_map=array();
            if (!empty($cat_sons) && !empty($catstr)) {
                $where['cat_id'] = array('in', $cat_sons);
            }
            if (!empty($extension_goods_id) && !empty($extensionstr)) {
                $where['id'] = array('in', $extension_goods_id);
            }
            if (!empty($where)) {
                $where['_logic'] = 'or';
                $where_g['_complex'] = $where;
            }
            $goods_ids = M('Goods')->where($where_g)->getField('id',true);
        }
        //获取仓库列表，按仓库id查询
        $shop_list=D('Shops')->shop_list();
        $this->assign('shop_list',$shop_list);
        if($postdata['shop_id']){
            if($postdata['type']!=4 || $postdata['shop_type']==1) {
                $map['shop_id_in'] = $postdata['shop_id'];
            }elseif($postdata['type']==4 && $postdata['shop_type']==0){
                $map['shop_id_out'] = $postdata['shop_id'];
            }
        }

        if($postdata['type'])$map['type']=$postdata['type'];
        else {$postdata['type']=0;$map['type']=0;}
        //按时间查询
        if($postdata['date_from'] || $postdata['date_to']){
            $date_from = strtotime($postdata['date_from']);
            if($date_from){
                $map['add_time'][] = array('egt',$date_from);
            }
            $date_to = strtotime($postdata['date_to']);
            if($date_to){
                $date_to=$date_to+83699;
                $map['add_time'][] = array('lt',$date_to);
            }
            $postdata['dates']=0;
        }else{
            if(in_array($postdata['dates'],array(1,2,7,30))){
                $between=quick_time($postdata['dates']);
                $map['add_time']=array('between',array($between[0],$between[1]));
            }else{
                $postdata['dates']=99;
            }
        }
        $map['status']=array('lt','4');
        //获取符合条件的订单id
        $order_ids = M('InvoicingOrder')->where($map)->getField('id',true);
        if(!empty($order_ids)){
            $map = array();
            if($postdata['keyword']){
                $map['goods_sn|goods_name'] = array('like','%'.$postdata['keyword'].'%');
            }
            $map['order_id'] = array('in',$order_ids);
            if($goods_ids){
                $map['goods_id'] = array('in',$goods_ids);
            }
            $map['_string']='goods_id > 0';
            if($postdata['supplier_id'])$map['supplier_id'] = $postdata['supplier_id'];
            $field='sum(all_money) as all_price,sum(freight_num) as all_freight_num,sum(fact_num) as all_fact_num,sum(request_num) as all_request_num';
            $all = M('InvoicingGoods')->where($map)->field($field)->find();
            $order = 'sum(freight_num) desc';
            $fields = 'goods_id,goods_sn,goods_name,goods_attr_sn,sum(all_money) as goods_price,sum(freight_num) as all_freight,sum(fact_num) as all_fact,sum(request_num) as all_request';
            $lists=M('InvoicingGoods')->where($map)->field($fields)->group('goods_id')->order($order)->select();
            $map['group'] = 'goods_id';
            $list = page_list('InvoicingGoods',$map,$order,$fields,20);
        }
        $data=$all;

        if($is_return==false){
            $this->assign($list);
            $this->assign($data);
            $this->add_getcateTree($postdata['catid'], '');
            $this->get_supplier_list();
            $this->assign('order_type',$order_type);
            $this->assign('shop_types',$shop_types);
            $this->assign($postdata);
            $this->display();
        }else{
            return $return=array('data'=>$data,'list'=>$lists);
        }
    }
    /**
     * 进销存商品汇总统计导出
     */
    public function export_statistics(){
        $list=$this->statistics(true);
        $i=0;
        $data=array();
        foreach ($list['list'] as $k => $v) {
            $i++;
            $data[$i]['n']=$i;
            $data[$i]['goods_sn']=$v['goods_sn'];
            $data[$i]['goods_name']=$v['goods_name'];
            $data[$i]['goods_price']=format_decimal($v['goods_price']);
            $data[$i]['all_request']=floatval($v['all_request']);
            $data[$i]['all_freight']=floatval($v['all_freight']);
            $data[$i]['all_fact']=floatval($v['all_fact']);
        }
        $data[]=array('总计','--','--',format_decimal($list['data']['all_price']),floatval($list['data']['all_request_num']),floatval($list['data']['all_freight_num']),floatval($list['data']['all_fact_num']));
        $title = array('序号', '商品编号', '商品名称','总金额','总请求量','总货流量','总实收量');
        export_csv('进销存商品统计.csv',$title,$data);
        exit;
    }
    /*
     *
     */
    public function order_statistics($is_return=false){
        $postdata=I('param.');
        $map=array();
        $order_type=array('0'=>'仓库订货','1'=>'仓库进货','4'=>'仓库调货');
        $this->assign('order_type',$order_type);
        $shop_types = array('0'=>'调出','1'=>'调入');
        $this->assign('shop_types',$shop_types);
        $sou_type=strtoarray(array('1'=>'按仓库','2'=>'按小时','3'=>'按日','4'=>'按月'));
        $this->assign('sou_type',$sou_type);
        $shop_list=D('Shops')->shop_list();
        $this->assign('shop_list',$shop_list);
        $map['status']=array('lt','4');
        if($postdata['type'])$map['type']=$postdata['type'];
        else {$postdata['type']=0;$map['type']=0;}
        if($postdata['date_from'] || $postdata['date_to']){
            $date_from = strtotime($postdata['date_from']);
            if($date_from){$map['update_time'][] = array('egt',$date_from);}
            $date_to = strtotime($postdata['date_to']);
            if($date_to){$date_to = $date_to+86399;$map['update_time'][] = array('lt',$date_to);}
            $postdata['dates']=0;
        }else{
            if(in_array($postdata['dates'],array(1,2,7,30))){
                $between=quick_time($postdata['dates']);
                $map['update_time']=array('between',array($between[0],$between[1]));
            }else{
                $postdata['dates']=99;
            }
        }
        if($postdata['shop_id']){
            if($postdata['shop_type']==1) {
                $map['shop_id_in'] = $postdata['shop_id'];
            }elseif($postdata['shop_type']==0){
                $map['shop_id_out'] = $postdata['shop_id'];
            }
        }
        /*按仓库、小时、日、月统计start*/
        switch($postdata['sou_value']){
            case 2://按小时
                for($i=0;$i<24;$i++){
                    $day_arr[$i] = $i; //处理时间数组
                }
                $field="sum(all_money) as order_money,sum(count) as all_count,count(id) as num,shop_id_in,shop_id_out,add_time";
                if(empty($map['shop_id_in']))$map['shop_id_in']=array('neq',0);
                $list_in=M('InvoicingOrder')->where($map)->group("DATE_FORMAT(FROM_UNIXTIME(add_time),'%k')")->field($field)->select();
                if(empty($map['shop_id_in']))unset($map['shop_id_in']);
                if(empty($map['shop_id_out']))$map['shop_id_out']=array('neq',0);
                $list_out=M('InvoicingOrder')->where($map)->group("DATE_FORMAT(FROM_UNIXTIME(add_time),'%k')")->field($field)->select();
                if(empty($map['shop_id_out']))unset($map['shop_id_out']);
                $list_time=array();
                if($list_in){
                    foreach ($list_in as $k => $v) {
                        $list[date('G',$v['add_time'])]['add_time']=date('G',$v['add_time']).'点';
                        $list[date('G',$v['add_time'])]['in_money']=format_decimal($v['order_money']);
                        $list[date('G',$v['add_time'])]['in_count']=floatval($v['all_count']);
                        $list[date('G',$v['add_time'])]['in_num']=floatval($v['num']);
                        $list_time[]=date('G',$v['add_time']);
                    }unset($k,$v);
                    /*$new_day=array_diff($day_arr,$list_time);
                    foreach($new_day as $vt){
                        $list[$vt]['add_time']=$vt.'点';
                        $list[$vt]['in_money']=0.00;
                        $list[$vt]['in_count']=0;
                        $list[$vt]['in_num']=0;
                    }
                    ksort($list);*/
                }
                if($list_out){
                    foreach ($list_out as $k => $v) {
                        $list[date('G',$v['add_time'])]['add_time']=date('G',$v['add_time']).'点';
                        $list[date('G',$v['add_time'])]['out_money']=format_decimal($v['order_money']);
                        $list[date('G',$v['add_time'])]['out_count']=floatval($v['all_count']);
                        $list[date('G',$v['add_time'])]['out_num']=floatval($v['num']);
                        $list_time[]=date('G',$v['add_time']);
                    }unset($k,$v);

                }
                $new_day=array_diff($day_arr,$list_time);
                foreach($new_day as $vt){
                    $list[$vt]['add_time']=$vt.'点';
                    $list[$vt]['in_money']=0.00;
                    $list[$vt]['in_count']=0;
                    $list[$vt]['in_num']=0;
                    $list[$vt]['out_money']=0.00;
                    $list[$vt]['out_count']=0;
                    $list[$vt]['out_num']=0;
                }
                ksort($list);
                break;
            case 3://按日
                for($i=1;$i<32;$i++){
                    $day_arr[$i] = $i; //处理时间数组
                }
                $field="sum(all_money) as order_money,sum(count) as all_count,count(id) as num,shop_id_in,shop_id_out,add_time";
                if(empty($map['shop_id_in']))$map['shop_id_in']=array('neq',0);
                $list_in=M('InvoicingOrder')->where($map)->group("DATE_FORMAT(FROM_UNIXTIME(add_time),'%e')")->field($field)->select();
                if(empty($map['shop_id_in']))unset($map['shop_id_in']);
                if(empty($map['shop_id_out']))$map['shop_id_out']=array('neq',0);
                $list_out=M('InvoicingOrder')->where($map)->group("DATE_FORMAT(FROM_UNIXTIME(add_time),'%e')")->field($field)->select();
                if(empty($map['shop_id_out']))unset($map['shop_id_out']);
                if($list_in){
                    foreach ($list_in as $k => $v) {
                        $list[date('j',$v['add_time'])]['add_time']=date('j',$v['add_time']).'日';
                        $list[date('j',$v['add_time'])]['in_money']=format_decimal($v['order_money']);
                        $list[date('j',$v['add_time'])]['in_count']=floatval($v['all_count']);
                        $list[date('j',$v['add_time'])]['in_num']=floatval($v['num']);
                        $list_time[]=date('j',$v['add_time']);
                    }unset($k,$v);
                }
                if($list_out){
                    foreach ($list_out as $k => $v) {
                        $list[date('j',$v['add_time'])]['add_time']=date('j',$v['add_time']).'日';
                        $list[date('j',$v['add_time'])]['out_money']=format_decimal($v['order_money']);
                        $list[date('j',$v['add_time'])]['out_count']=floatval($v['all_count']);
                        $list[date('j',$v['add_time'])]['out_num']=floatval($v['num']);
                        $list_time[]=date('j',$v['add_time']);
                    }unset($k,$v);
                }
                $new_day=array_diff($day_arr,$list_time);
                foreach($new_day as $vt){
                    $list[$vt]['add_time']=$vt.'日';
                    $list[$vt]['in_money']=0.00;
                    $list[$vt]['in__count']=0;
                    $list[$vt]['in_num']=0;
                    $list[$vt]['out_money']=0.00;
                    $list[$vt]['out_count']=0;
                    $list[$vt]['out_num']=0;
                }
                ksort($list);
                break;
            case 4://月
                for($i=1;$i<13;$i++){
                    $day_arr[$i] = $i; //处理时间数组
                }
                $field="sum(all_money) as order_money,sum(count) as all_count,count(id) as num,shop_id_in,shop_id_out,add_time";
                if(empty($map['shop_id_in']))$map['shop_id_in']=array('neq',0);
                $list_in=M('InvoicingOrder')->where($map)->group("DATE_FORMAT(FROM_UNIXTIME(add_time),'%c')")->field($field)->select();
                if(empty($map['shop_id_in']))unset($map['shop_id_in']);
                if(empty($map['shop_id_out']))$map['shop_id_out']=array('neq',0);
                $list_out=M('InvoicingOrder')->where($map)->group("DATE_FORMAT(FROM_UNIXTIME(add_time),'%c')")->field($field)->select();
                if(empty($map['shop_id_out']))unset($map['shop_id_out']);
                if($list_in){
                    foreach ($list_in as $k => $v) {
                        $list[date('n',$v['add_time'])]['add_time']=date('n',$v['add_time']).'月';
                        $list[date('n',$v['add_time'])]['in_money']=format_decimal($v['order_money']);
                        $list[date('n',$v['add_time'])]['in_count']=floatval($v['all_count']);
                        $list[date('n',$v['add_time'])]['in_num']=floatval($v['num']);
                        $list_time[]=date('n',$v['add_time']);
                    }unset($k,$v);
                }
                if($list_out){
                    foreach ($list_out as $k => $v) {
                        $list[date('n',$v['add_time'])]['add_time']=date('n',$v['add_time']).'月';
                        $list[date('n',$v['add_time'])]['out_money']=format_decimal($v['order_money']);
                        $list[date('n',$v['add_time'])]['out_count']=floatval($v['all_count']);
                        $list[date('n',$v['add_time'])]['out_num']=floatval($v['num']);
                        $list_time[]=date('n',$v['add_time']);
                    }unset($k,$v);
                }
                $new_day=array_diff($day_arr,$list_time);
                foreach($new_day as $vt){
                    $list[$vt]['add_time']=$vt.'月';
                    $list[$vt]['in_money']=0.00;
                    $list[$vt]['in_count']=0;
                    $list[$vt]['in_num']=0;
                    $list[$vt]['out_money']=0.00;
                    $list[$vt]['out_count']=0;
                    $list[$vt]['out_num']=0;
                }
                ksort($list);
                break;
            default://按店
                $shoplist=$shop_list;
                if($postdata['shop_id']){
                    $map_s=array();
                    $map_s['id']=$postdata['shop_id'];
                    $shoplist=M('Shops')->where($map_s)->getField('id,name');
                }
                $shop_ids=array_keys($shoplist);
                $postdata['sou_value']=1;
                $field="sum(all_money) as order_money,sum(count) as all_count,count(id) as num,shop_id_in,shop_id_out,add_time";
                if(empty($map['shop_id_in']))$map['shop_id_in']=array('neq',0);
                $list_in=M('InvoicingOrder')->where($map)->group("shop_id_in")->field($field)->select();
                if(empty($map['shop_id_in']))unset($map['shop_id_in']);
                if(empty($map['shop_id_out']))$map['shop_id_out']=array('neq',0);
                $list_out=M('InvoicingOrder')->where($map)->group("shop_id_out")->field($field)->select();
                if(empty($map['shop_id_out']))unset($map['shop_id_out']);
                if($list_in){
                    foreach ($list_in as $k => $v) {
                        $list[$v['shop_id_in']]['shop_name']=$shop_list[$v['shop_id_in']]?$shop_list[$v['shop_id_in']]:'该仓库已删除或禁用('.$v['shop_id_in'].')';
                        $list[$v['shop_id_in']]['in_money']=format_decimal($v['order_money']);
                        $list[$v['shop_id_in']]['in_count']=floatval($v['all_count']);
                        $list[$v['shop_id_in']]['in_num']=floatval($v['num']);
                        $list_time[]=$v['shop_id_in'];
                    }unset($k,$v);
                }
                if($list_out){
                    foreach ($list_out as $k => $v) {
                        $list[$v['shop_id_in']]['shop_name']=$shop_list[$v['shop_id_in']]?$shop_list[$v['shop_id_in']]:'该仓库已删除或禁用('.$v['shop_id_in'].')';
                        $list[$v['shop_id_in']]['out_money']=format_decimal($v['order_money']);
                        $list[$v['shop_id_in']]['out_count']=floatval($v['all_count']);
                        $list[$v['shop_id_in']]['out_num']=floatval($v['num']);
                        $list_time[]=$v['shop_id_in'];
                    }unset($k,$v);
                }
                $new_day=array_diff($shop_ids,$list_time);
                foreach($new_day as $vt){
                    $list[$vt]['shop_name']=$shop_list[$vt];
                    $list[$vt]['in_money']=0.00;
                    $list[$vt]['in_count']=0;
                    $list[$vt]['in_num']=0;
                    $list[$vt]['out_money']=0.00;
                    $list[$vt]['out_count']=0;
                    $list[$vt]['out_num']=0;
                }
                break;

        }
        foreach($list as $ke => $vo){
            $list[$ke]['in_money']=$vo['in_money']?$vo['in_money']:'0.00';
            $list[$ke]['in_count']=$vo['in_count']?$vo['in_count']:0;
            $list[$ke]['in_num']=$vo['in_num']?$vo['in_num']:0;
            $list[$ke]['out_money']=$vo['out_money']?$vo['out_money']:'0.00';
            $list[$ke]['out_count']=$vo['out_count']?$vo['out_count']:0;
            $list[$ke]['out_num']=$vo['out_num']?$vo['out_num']:0;
            $data=array(
                'in_order_money'=>format_decimal(array_sum(array_map(function($vo){return $vo['in_money'];},$list))),
                'in_order_count'=>array_sum(array_map(function($vo){return $vo['in_count'];},$list)),
                'in_order_num'=>array_sum(array_map(function($vo){return $vo['in_num'];},$list)),
                'out_order_money'=>format_decimal(array_sum(array_map(function($vo){return $vo['out_money'];},$list))),
                'out_order_count'=>array_sum(array_map(function($vo){return $vo['out_count'];},$list)),
                'out_order_num'=>array_sum(array_map(function($vo){return $vo['out_num'];},$list)),
            );
        }
        /*按仓库、小时、日、月统计end*/
        if($is_return){
            $return['list']=$list;
            $return['info']=$data;
            if($postdata['sou_value']==1){
                $return['title'] = array('仓库','调入总金额','调入总数量','调入订单量','调出总金额','调出总数量','调出订单量');
            }else{
                $return['title'] = array('时间','调入总金额','调入总数量','调入订单量','调出总金额','调出总数量','调出订单量');
            }

            return $return;
        }else{
            $this->assign($postdata);
            $this->assign('list',$list);
            $this->assign('data',$data);
            $this->display();
        }
    }
    /**
     * 供货商结算导出
     */
    public function order_statistics_export(){
        $rest=$this->order_statistics(true);
        $data=array();
        $data=$rest['list'];
        $data[]=array('总计',format_decimal($rest['info']['in_order_money']),floatval($rest['info']['in_order_count']),floatval($rest['info']['in_order_num']),format_decimal($rest['info']['out_order_money']),floatval($rest['info']['out_order_count']),floatval($rest['info']['out_order_num']));
        export_csv('进销存订单统计.csv',$rest['title'],$data);
        exit;
    }

    /*采购相关start*/
    public function purchase_index(){
        $postdata = I('param.');
        $sn = $postdata['sn'];
        if(empty($postdata['shopid']))$postdata['shopid']=1; //默认仓库1 jxr
        $shopid=$postdata['shopid'];
        $this->get_shops_list();
        $map['type'] = 0;    //订货单
        $map['status'] = array('elt',1);
        if($sn){$map['sn'] = array('like','%'.$sn.'%');}
        if($shopid){$map_or=array('shop_id_in'=>$shopid,'shop_id_out'=>$shopid,'_logic'=>'or');$map['_complex']=$map_or;}
        if($postdata['data_from']){$map['add_time'][] = array('egt',strtotime($postdata['data_from']));}
        if($postdata['data_to']){$map['add_time'][] = array('elt',strtotime($postdata['data_to']));}
        $list = $this->lists('InvoicingOrder',$map);
        //计算总采购项，已采购项
        $order_ids=array();
        foreach ($list as $key => $value) {
            $map_num['order_id']=$value['id'];
            $map_num['request_num']=array('gt',0);
            $list[$key]['zc_num'] = intval(M('InvoicingGoods')->where($map_num)->count());
        }

        $goods_count=M('InvoicingOrder')->where($map)->count();
        $this->assign('list',$list);
        $this->assign('goods_count',$goods_count);
        $this->assign($postdata);
        $this->display();
    }
    /**
     * 采购准备
     */
    public function order_cai_add(){
        $this->get_shops_list();
        $this->get_supplier_list();
        $this->getcateTree();
        $this->assign('shopid',1);
        $this->display();
    }

    /**
     * 采购操作
     */
    public function order_cai_insert(){
        $postdata=I('post.');
        // $postdata['is_pay'] = 1; // 默认支付
        if(empty($postdata['shop_id_in'])){$return=array('status'=>0,'msg'=>'请选择仓库'); $this->ajaxReturn($return);}
        if(empty($postdata['supplier_id'])){$return=array('status'=>0,'msg'=>'请选择供货商'); $this->ajaxReturn($return);}
        if(empty($postdata['infos'])){$return=array('status'=>0,'msg'=>'请选择商品'); $this->ajaxReturn($return);}
        $supplier_array=array_unique($postdata['infos']['supplier_id']);
        $supplier=array_filter($supplier_array);
        if(empty($supplier) || count($supplier_array)!=count($supplier)){$return=array('status'=>0,'msg'=>'请选择供货商');$this->ajaxReturn($return);}
        $data = D('Common/InvoicingOrder')->order_in_insert($postdata);
        if($data['status']==1){$data['url']=U('InvoicingOrder/order_print',array('id'=>$data['id']));}
        $this->ajaxReturn($data);
    }
    /*采购相关end*/

    /*入库相关start*/
    /**
     * 入库管理列表
     */
    public function order_ru(){
        $postdata = I('param.');
        $sn = $postdata['sn'];
        $status = $postdata['status'];
        $type = $postdata['type'];
        if(empty($postdata['shopid']))$postdata['shopid']=1; //默认仓库1
        $shopid=$postdata['shopid'];
        $this->get_shops_list();
        if($sn){$map['sn'] = array('like','%'.$sn.'%');}
        if($status){$map['status'] = $status-1;}
        else $map['status'] = array('in','2,3,4,5');//采购单只是查询待入库的
        if(intval($type) == 20 || !$type){
            $map['type'] = array('in','0,1,4,5,8');// 0采购入库、1其他入库、4调货入库、6退货入库
        }else{
            if($type==21) $type=0;
            $map['type'] = $type;
        }
        if($shopid){$map_or=array('shop_id_in'=>$shopid,'shop_id_out'=>$shopid,'_logic'=>'or');$map['_complex']=$map_or;}
        if($postdata['data_from']){$map['add_time'][] = array('egt',strtotime($postdata['data_from']));}
        if($postdata['data_to']){$map['add_time'][] = array('elt',strtotime($postdata['data_to']));}
        $list = $this->lists('InvoicingOrder',$map);
        $goods_count=M('InvoicingOrder')->where($map)->count();
        $this->assign('list',$list);
        $this->assign('goods_count',$goods_count);
        $this->assign($postdata);
        $this->assign('out_price',$this->out_price);
        $this->display();
    }
    //确认收货
    public function confirm_goods(){
        $postdata=I('post.');
        $id=$postdata['id'];
        $return=array('status'=>3,'msg'=>'');
        if(empty($id)){$return['msg']='请选择要操作的货流单';$this->ajaxReturn($return);}
        $map=array('id'=>$id);
        $shop_id=M('InvoicingOrder')->where($map)->getField('shop_id_in');
        $data=array();
        $data['id']=$id;
        $data['shop_id']=$shop_id;
        if($postdata['goods_id']) {
            foreach($postdata['goods_id'] as $k=>$v) {
                $data['fact_num'][$k]=$postdata['fact_num'][$k];
                $data['goods_id'][$k]=$postdata['goods_id'][$k];
                $data['supply_price'][$k]=$postdata['supply_price'][$k];
                $data['goods_attr_sn'][$k]=$postdata['invoicing_goods_attr'][$k];
            }
        }
        $res=D('Common/InvoicingOrder')->update_order($data);
        if($res['status']==1) {
            //修改对账信息
            $map=array();
            $map['id']=$postdata['id'];
            $type=M('InvoicingOrder')->where($map)->getField('type');
            if($type!=4)D('Common/InvoicingOrder')->add_invoicing_detail($id,1,1);
            D('Common/InvoicingOrder')->add_storage($id);
            $return['status']=1;
            $return['msg']='确认收货成功';
            $this->ajaxReturn($return);
        }else{
            $return['msg']='该订单不能确认入库';
            $this->ajaxReturn($return);
        }
    }
    /*入库相关end*/
    /*出库相关start*/
    /**
     * 出库管理列表
     */
    public function order_chu(){
        $postdata = I('param.');
        $sn = $postdata['sn'];
        $status = $postdata['status'];
        $type = $postdata['type'];
        if(empty($postdata['shopid']))$postdata['shopid']=1; //默认仓库1
        $shopid=$postdata['shopid'];
        $this->get_shops_list();
        $this->assign('shop_id',1);
        $this->assign('out_shop_id',1);
        $this->assign('in_shop_id',1);
        if($sn){$map['sn'] = array('like','%'.$sn.'%');}
        if($status){$map['status'] = $status-1;}
        else{$map['status'] = array('in','0,1,3,4,5');}
        if(intval($type) > 0){
            $map['type'] = $type;
        }else{
            $map['type'] = array('in','2,3,4,6,7');// 2普通出库 、3仓库退货、4调货出库、6销售出库、7报损出库
        }
        if($shopid){$map_or=array('shop_id_in'=>$shopid,'shop_id_out'=>$shopid,'_logic'=>'or');$map['_complex']=$map_or;}
        if($postdata['data_from']){$map['add_time'][] = array('egt',strtotime($postdata['data_from']));}
        if($postdata['data_to']){$map['add_time'][] = array('elt',strtotime($postdata['data_to']));}
        $list = $this->lists('InvoicingOrder',$map);
        $goods_count=M('InvoicingOrder')->where($map)->count();
        $this->assign('list',$list);
        $this->assign('goods_count',$goods_count);
        $this->assign($postdata);
        $this->assign('out_price',$this->out_price);
        $this->display();
    }
    /*入库相关end*/
}
?>