<?php
/**
 * 门店进销存
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author
 */

namespace Shop\Controller;
use Think\Controller;
class InvoicingOrderController extends BaseController {
	public function _initialize(){
        parent::_initialize();
        $shops_info=session('shops_info');
        if(empty($shops_info['id']))$this->error('身份过期，请重新登录',U('Shop/Register/shop_login'));
		$this->mendian();
         $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'=>'门店调货');
        $this->assign('order_type',$this->order_type);
        $this->out_price=array('0'=>'以最近进货价出库','1'=>'以平均进货价出库','2'=>'以商品销售价出库','3'=>'以商品批发价出库');
        $this->move_price=array('0'=>'以进货价调货','2'=>'以商品销售价调货','3'=>'以商品批发价调货');
        $this->stock_status=array('0'=>'未审核','1'=>'审核通过','2'=>'拒绝','3'=>'作废');
        $this->getcateTree();
    }

    /**
     * 订货列表
     */
    public function order_goods(){
        $param=I('param.');
        $tabid=$param['tabid'];
        $param['shop_id']=MID;//门店id
        $this->assign('title_ass','订货');
        if(empty($tabid)){//订货列表
            $param['mtype']=1;//门店进货
            $data=D('Shop/InvoicingOrder')->order_list($param);
            if($data['status']==1){
                $this->assign($data['data']);
            }
        }elseif($tabid=='add_order_goods'){//添加订货单页面
            $chu_type = 2;//订货单位 2供货商 3仓库
            $this->assign('chu_type',$chu_type);
            $this->assign('storage_id',1);
            $this->assign('shop_id',$param['shop_id']);//入库的门店id
        }else{
            $id=I('id');
            $param['order_id']=$id;
            $order_info=D('Shop/InvoicingOrder')->order_info($param);
            if($order_info['status']==1){$this->assign($order_info['data']);}
            else{$this->error($order_info['msg']);}
            // $this->assign('menu_tab','');
        }
        $this->getcateTree();        
        $tabid=$tabid?$tabid:'order_goods';
        $this->display($tabid);
    }

    /**
     * 根据输入关键字搜索商品
     */
    public function search_goods(){
        $return=array('status'=>0,'msg'=>'');
        $param = I('param.');
        $param['is_add']=1;
        $goods_info=D('Shop/InvoicingOrder')->search_goods($param);
        if($goods_info['status']==1){
            $data = '';
            $data .= '<option value="">请选择</option>';
            foreach ($goods_info['data'] as $val) {
                if($val['attr_name']){
                    $data.="<option value='".$val['attr_key']."'>".$val['goods_name'].$val['attr_name']."</option>";
                }else{
                    $data.="<option value='".$val['attr_key']."'>".$val['goods_name']."</option>";
                }
            }
            $return['info']=$data;
            $return['status']=1;
            $this->ajaxReturn($return);
        }else{
            $return['msg']=$goods_info['msg'];
            $this->ajaxReturn($return);
        }
    }
    /**2018-07-24**/
    /**选择商品加属性***/
    //搜索单商品
    public function add_goods_list(){
        $return=array('status'=>1,'msg'=>'');
        $postdata=I('param.');
        $postdata['is_shop']=$postdata['is_shop'];
        if($postdata['is_shop']==1){$postdata['shop_id']=MID;}
        $result=D('Common/InvoicingOrder')->search_by_sn($postdata);
        // print_r($result);exit();
        if($result['status']==0){
            $return['status']=0;
            $return['msg']=$result['msg'];
            $this->ajaxReturn($return);
        }
        $return['data']=$result['data'];
        $this->ajaxReturn($return);
    }
    //弹窗搜索商品
    public function search_goods_list(){
        $return=array('status'=>1,'msg'=>'');
        $postdata=I('param.');
        if($postdata['is_shop']==1){$postdata['shop_id']=MID;}
        $result=D('Common/InvoicingOrder')->search_by_keyword($postdata);
        if($result['status']==0){
            $return['status']=0;
            $return['msg']=$result['msg'];
            $this->ajaxReturn($return);
        }
        $left_html=$right_html='';
        foreach($result['data']['left_list'] as $k=>$v){
            if(empty($v['goods_attrs'])){
                $left_html.='<div class="choose_goods_item clearfix">
                        <input type="checkbox" value="'.$v['index'].'" data-id="'.$v['index'].'" title="'.$v['goods_name'].'" attr_data="" attr_name="" supplier_id="'.$v['suppliers_id'].'" goods_id="'.$v['id'].'" unit_name="'.$v['unit_name'].'" supply_price="'.$v['supply_price'].'" shop_price="'.$v['shop_price'].'" goods_sn="'.$v['goods_sn'].'" stock="'.$v['stock'].'" name="choose_goods" class="check_box f_l" />
                        <dl class="flex_outside" onclick="name_search_select(\''.$v['index'].'\')">
                            <dt><img src="'.$v['img'].'"></dt>
                            <dd class="flex_inside">
                                <p class="ellipsis_one">'.str_cut($v['goods_name'],70).'</p>
                                <p class="ellipsis_one">条码:<span>'.$v['goods_sn'].'</span></p>
                                <p class="ellipsis_one">￥'.$v['supply_price'].'</p>
                            </dd>
                        </dl>
                    </div>';
            }else{
                $left_html.='<div class="choose_goods_item clearfix">
                            <em class="shrink f_l down_img" onclick="shrink(this)"><img src="'.__ROOT__.'/Public/images/more_dow.png" /></em>
                            <dl class="flex_outside">
                                <dt><img src="'.$v['img'].'"></dt>
                                <dd class="flex_inside">
                                    <p class="ellipsis_one">'.str_cut($v['goods_name'],70).'</p>
                                    <p class="ellipsis_one">条码:<span>'.$v['goods_sn'].'</span></p>
                                    <p class="ellipsis_one">￥'.$v['supply_price'].'</p>
                                </dd>
                            </dl>
                            <div class="goods_shuxing" style="display: none;">';
                foreach($v['goods_attrs'] as $ke=>$va){
                    $left_html.='<div class="goos_sx_item">
                                    <input type="checkbox" value="'.$va['index'].'" data-id="'.$va['index'].'" title="'.$va['goods_name'].'" attr_data="'.$va['attr_key'].'" attr_name="'.$va['name'].'" supplier_id="'.$v['suppliers_id'].'" shop_price="'.$va['shop_price'].'" goods_id="'.$va['goods_id'].'" unit_name="'.$va['unit_name'].'" supply_price="'.$va['supply_price'].'" goods_sn="'.$va['goods_sn'].'" goods_attr_sn="'.$va['goods_attr_sn'].'"  stock="'.$va['stock'].'" name="choose_goods" class="check_box f_l" />
                                    <dl class="flex_outside" onclick="name_search_select(\''.$va['index'].'\')">
                                        <dt><img src="'.$va['img'].'"></dt>
                                        <dd class="flex_inside">
                                            <p class="ellipsis_one">'.$va['name'].'</p>
                                            <p class="ellipsis_one">条码:<span>'.$va['goods_attr_sn'].'</span></p>
                                            <p class="ellipsis_one">￥'.$va['supply_price'].'</p>
                                        </dd>
                                    </dl>
                                </div>';
                }
                $left_html.='</div>
                        </div>';
            }
        }
        foreach($result['data']['right_list'] as $k=>$v){
            if(empty($v['goods_attrs'])){
                $right_html.='<div class="choose_goods_item clearfix">
                        <input type="checkbox" value="'.$v['index'].'" data-id="'.$v['index'].'" title="'.$v['goods_name'].'" attr_data="" attr_name="" supplier_id="'.$v['suppliers_id'].'" goods_id="'.$v['id'].'" unit_name="'.$v['unit_name'].'" supply_price="'.$v['supply_price'].'" shop_price="'.$v['shop_price'].'" goods_sn="'.$v['goods_sn'].'"  stock="'.$v['stock'].'" name="choose_goods" class="check_box f_l" />
                        <dl class="flex_outside" onclick="name_search_select(\''.$v['index'].'\')">
                            <dt><img src="'.$v['img'].'"></dt>
                            <dd class="flex_inside">
                                <p class="ellipsis_one">'.str_cut($v['goods_name'],70).'</p>
                                <p class="ellipsis_one">条码:<span>'.$v['goods_sn'].'</span></p>
                                <p class="ellipsis_one">￥'.$v['supply_price'].'</p>
                            </dd>
                        </dl>
                    </div>';
            }else{
                $right_html.='<div class="choose_goods_item clearfix">
                            <em class="shrink f_l down_img" onclick="shrink(this)"><img src="'.__ROOT__.'/Public/images/more_dow.png" /></em>
                            <dl class="flex_outside">
                                <dt><img src="'.$v['img'].'"></dt>
                                <dd class="flex_inside">
                                    <p class="ellipsis_one">'.str_cut($v['goods_name'],70).'</p>
                                    <p class="ellipsis_one">条码:<span>'.$v['goods_sn'].'</span></p>
                                    <p class="ellipsis_one">￥'.$v['supply_price'].'</p>
                                </dd>
                            </dl>
                            <div class="goods_shuxing" style="display: none;">';
                foreach($v['goods_attrs'] as $ke=>$va){
                    $right_html.='<div class="goos_sx_item">
                                    <input type="checkbox" value="'.$va['index'].'" data-id="'.$va['index'].'" title="'.$va['goods_name'].'" attr_data="'.$va['attr_key'].'" attr_name="'.$va['name'].'" supplier_id="'.$v['suppliers_id'].'" goods_id="'.$va['goods_id'].'" unit_name="'.$va['unit_name'].'" supply_price="'.$va['supply_price'].'" shop_price="'.$va['shop_price'].'" goods_sn="'.$va['goods_sn'].'" goods_attr_sn="'.$va['goods_attr_sn'].'"  stock="'.$va['stock'].'"  name="choose_goods" class="check_box f_l" />
                                    <dl class="flex_outside" onclick="name_search_select(\''.$va['index'].'\')">
                                        <dt><img src="'.$va['img'].'"></dt>
                                        <dd class="flex_inside">
                                            <p class="ellipsis_one">'.$va['name'].'</p>
                                            <p class="ellipsis_one">条码:<span>'.$va['goods_attr_sn'].'</span></p>
                                            <p class="ellipsis_one">￥'.$va['supply_price'].'</p>
                                        </dd>
                                    </dl>
                                </div>';
                }
                $right_html.='</div>
                        </div>';
            }
        }
        $return['data']['left_html']=$left_html;
        $return['data']['right_html']=$right_html;
        $return['page']=$result['data']['page'];
        $this->ajaxReturn($return);
    }

    /**
     * 进货列表
     */
    public function stock_goods(){
        $param=I('param.');
        $param['shop_id']=MID;
        $tabid=$param['tabid'];
        $this->assign('title_ass','进货');
        $param['chu_type']=2;
        if(empty($tabid)){//订货列表
            $param['type']=1;
            $param['mtype']=1;
            $param['status']=3;
            $data=D('Shop/InvoicingOrder')->order_list($param);
            if($data['status']==1){
                $order_goods=$data['data'];
                $this->assign($order_goods);
            }
        }elseif($tabid=='add_stock_goods'){//添加订货单页面
            $this->get_supplier_list();
            $chu_type = 2;//订货单位 2供货商 3仓库
            $this->assign('chu_type',$chu_type);
            $this->assign('storage_id',1);
            $this->assign('shop_id',$param['shop_id']);//入库的门店id
        }else{
            $id=I('id');
            $param['order_id']=$id;
            $order_info=D('Shop/InvoicingOrder')->order_info($param);
            if($order_info['status']==1){$this->assign($order_info['data']);}
            else{$this->error($order_info['msg']);}
            // $this->assign('menu_tab','');
        }
        // 
        $tabid=$tabid?$tabid:'stock_goods';
        $this->display($tabid);
    }
    /**
    *调货liebiao
    */
    public function transfer_goods(){
        $param=I('param.');
        $param['shop_id']=MID;
        $tabid=$param['tabid'];
        $param['is_huoliu']=0;
        $param['in_out']=1;
        if(empty($tabid)){//订货列表
            $param['type']=4;
            $param['mtype']=1;
            $data=D('Shop/InvoicingOrder')->order_list($param);
            if($data['status']==1){
                $order_goods=$data['data'];
                $this->assign($order_goods);
            }
        }elseif($tabid=='add_transfer_goods'){//添加订货单页面
            $this->get_supplier_list();
            $this->get_shops_list();
            $this->assign('shop_id',$param['shop_id']);//出库的门店id
        }else{
            $id=I('id');
            $param['order_id']=$id;
            $order_info=D('Shop/InvoicingOrder')->order_info($param);
            if($order_info['status']==1){$this->assign($order_info['data']);}
            else{$this->error($order_info['msg']);}
            // $this->assign('menu_tab','');
        }
        $this->assign('title_ass','调货');
        $this->getcateTree();
        $tabid=$tabid?$tabid:'transfer_goods';
        $this->display($tabid);
    }
    //添加调货记录
    public function transfer_add(){
        $return=array('status'=>1,'msg'=>'');
        $postdata=I('post.');
        foreach ($postdata['infos']['goods_id'] as $ke => $vv) {
           $postdata['list'][$ke]['goods_id']=$postdata['infos']['goods_id'][$ke];
           $postdata['list'][$ke]['goods_name']=$postdata['infos']['goods_name'][$ke];
           $postdata['list'][$ke]['goods_attr_sn']=$postdata['infos']['goods_attr_sn'][$ke];
           $postdata['list'][$ke]['goods_sn']=$postdata['infos']['goods_sn'][$ke];
           $postdata['list'][$ke]['attr_key']=$postdata['infos']['attr_key'][$ke];
           $postdata['list'][$ke]['supply_price']=$postdata['infos']['supply_price'][$ke];
           $postdata['list'][$ke]['suppliers_id']=$postdata['infos']['suppliers_id'][$ke];
           $postdata['list'][$ke]['freight_num']=$postdata['infos']['freight_num'][$ke];
        }
        if(empty($postdata['shop_id'])){$return['status']=3;$return['msg']='参数错误'; $this->ajaxReturn($return);}
        if(empty($postdata['in_shop_id'])){$return['status']=3;$return['msg']='请选择门店'; $this->ajaxReturn($return);}
        $i =0;
        $shop_id=intval($postdata['in_shop_id']);
        parse_str($post_info,$info);
        $cashier_id=empty($postdata['cashier_id'])?0:intval($postdata['cashier_id']);
        $now_time=NOW_TIME;
        $data=array(
            'type'=>4,
            'mtype'=>1,
            'count'=>intval($postdata['count']),
            'all_money'=>format_decimal($postdata['all_money']),
            'shop_id_in'=>$shop_id,
            'shop_id_out'=>$postdata['shop_id'],
            'cashier_id'=>$cashier_id,
            'add_time'=>$now_time,
            'status'=>2,
            'remarks'=>$postdata['remarks'],
            'sn'=>D('Common/InvoicingOrder')->invoicing_sn(),
        );
        $id=M('InvoicingOrder')->add($data);
        if($id<=0){$return['status']=3;$return['msg']='添加调货单失败';$this->ajaxReturn($return);}
        //加入InvoicingGoods表
        $infos=array();
        foreach($postdata['list'] as $k => $v){
            $infos[$i]['order_id']=$id;
            $infos[$i]['goods_id']=$v['goods_id'];
            $infos[$i]['goods_name']=$v['goods_name'];
            if($v['goods_attr_sn'])$infos[$i]['goods_sn']=$v['goods_attr_sn'];
            else $infos[$i]['goods_sn']=$v['goods_sn'];
            $infos[$i]['goods_attr_sn']=$v['attr_key']?$v['attr_key']:0;
            $infos[$i]['supply_price']=$v['supply_price'];
            $infos[$i]['shop_id']=$shop_id;
            $infos[$i]['supplier_id']=$v['suppliers_id']?$v['suppliers_id']:0;
            $infos[$i]['storage_id']=1;
            $infos[$i]['all_money']=format_decimal($v['supply_price']*$v['freight_num']);
            $infos[$i]['request_num']=$v['freight_num'];
            $infos[$i]['freight_num']=$v['freight_num'];
            $infos[$i]['fact_num']=$v['freight_num'];
            $infos[$i]['status']=2;
            M('InvoicingGoods')->add($infos[$i]);
            $i++;
        }
        if($i!=0){
            D('Common/InvoicingOrder')->reduce_storage($id);//减少库存
            $return=array('status'=>1,'msg'=>'已成功为门店调货','id'=>$id);
        }else{
            $return['status']=3;
            $return['msg']='添加调货商品失败';
        }
        $this->ajaxReturn($return);
    }
    public function order_move_begin(){
        $postdata=I('post.');
        // print_r($postdata);exit();
        $data = D('Common/InvoicingOrder')->order_move_begin($postdata);
        $this->ajaxReturn($data);
    }
    /**
     * 出货操作
     */
    public function order_shipment_insert(){
        $postdata=I('post.');
        $data = D('Common/InvoicingOrder')->order_shipment_insert($postdata);
        $this->ajaxReturn($data);
    }
    /**
     * 货流管理打印
     */
    public function order_print(){

         $auth_code = 'fmanage_mlist_print';
        $ret=D('Shop/Shops')->shop_account_option($auth_code);
        if($ret['status']!=1) {$this->error($ret['msg']);exit;}

        $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']];
        $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();
        $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(MID,'Shops','name');
        $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 confirm_order_move(){
        $return=array('status'=>0,'msg'=>'');
        $postdata=I('post.');
        $map=array();
        $map['id']=$postdata['id'];
        $map['type']=$postdata['type'];
        $map['status']=0;
        $count=M('InvoicingOrder')->where($map)->count();
        if($count<=0){$return['msg']='订单信息错误'; $this->ajaxReturn($return);}
        $save=array();
        $save['status']=1;
        $result=M('InvoicingOrder')->where($map)->save($save);
        if($result){
            $map=array();
            $map['order_id']=$postdata['id'];
            M('InvoicingGoods')->where($map)->save($save);
            $return['status']=1;
            $return['msg']='操作成功';
            $this->ajaxReturn($return);
        }else{
            $return['msg']='操作失败';
            $this->ajaxReturn($return);
        }
    }

    /**
     * 创建订货或进货表格
     */
    public function create_table(){
        $goods_attr_sn = trim(I('post.goods_attr_sn'));//商品id_属性编号
        $postdata=I('post.');
        $postdata['shop_id']=MID;
        $result=D('Shop/InvoicingOrder')->search_goods($postdata);
        if($result['status']==1){
            $data['status']=1;
            foreach ($result['data']  as  $v) {
                if ($v['attr_key'] == $goods_attr_sn) {$goods_info = $v; break;}
            }
            $supplier_list=$this->get_supplier_list();
            $data['tr']='';
            $tpl='';
            if($goods_info['suppliers_id']==0 || !$goods_info['suppliers_id']){
                $tpl .= "<option value='0'>空</option>";
            }
            if($supplier_list){
                foreach($supplier_list as $k => $v){
                    $tpl .= "<option value='".$v['id']."'";
                    if($goods_info['suppliers_id'] == $v['id']){$tpl .= " select='select'";}
                    $tpl .= ">".$v['name']."</option>";
                }
            }
            $data['tr'].="<tr>
            <td><input name='infos[goods_id][]' value='".$goods_info['goods_id']."' readonly='readonly' style='border:none;' /><input type='hidden' name='infos[goods_attr_sn][]' value='".$goods_info['attr_key']."' /></td>
            <td class='goodsn' attr_key = ".$goods_info['attr_key']."><input name='infos[goods_sn][]' value='".$goods_info['goods_sn']."' readonly='readonly' style='border:none;' /></td>
            <td><input name='infos[goods_name][]' value='".$goods_info['goods_name']."' readonly='readonly' style='border:none;' /></td>
			<td>".idtoname($goods_info['cat_id'],'PurchaseCategory','name')."</td>";
            if($postdata['is_ding']==1){
                $data['tr'].="<td><input name='infos[supply_price][]' value='".$goods_info['supply_price']."' readonly='readonly' style='border:none;' /></td>";
            }else{
                $data['tr'].="<td><select name='infos[supplier_id][]' class='w100'>".$tpl."</select></td>
                <td><input name='infos[supply_price][]' value='".$goods_info['supply_price']."' onchange='change_price(this)' /></td>";
            }
            $data['tr'].="<td>".$goods_info['shop_price']."</td>
            <td><input name='infos[all_money][]' value='".$goods_info['supply_price']."' readonly='readonly' style='border:none;' /></td>
            <td><input name='infos[request_num][]' style='width:80px;' type='number' onchange='change_loss(this)' value='1'></td>
            <td><a onclick='delCurrentRow(this);' style='cursor:pointer;'>删除</a></td>
            </tr>";
        }else{
            $data=$result;
        }
        $this->ajaxReturn($data);
    }
    /**
     * 获取商品信息
     */
    public function get_goods()
    {
        $return=$where=$map = array();
        $postdata = I('param.');
        $id= intval($postdata['id']);
        $html='';
        if($id){
            $map['id'] = $id;
            // $map['goods_type']=5;
            $info = M('Goods')->where($map)->field('id,shop_price,supply_price,goods_sn,unit_id,is_type,goods_name')->find();
            $where['goods_id'] =$id;
            $attr_key = M('GoodsAttrStock')->where($where)->field('attr_key,attr_price,goods_attr_sn')->select();
            if($attr_key){

                $html='<select class=\'form-control\' name=\'attr_key[]\' onchange=\'shopprice('.this.')\'>';
                foreach($attr_key as $k=>$v){
                    $attr = attr_key2name($v['attr_key'],$id);
                    $html.='<option value='.$v['attr_key'].' attrprice='.$v['attr_price'].' goodssn='.$v['goods_attr_sn'].'>'.$attr.'</option>';
                }
                $html.='</select>';
                $info['shop_price']=$attr_key[0]['attr_price'];
                $info['goods_sn']=$attr_key[0]['goods_attr_sn'];
                $info['attr_keys']=$html;
            }else{
                $info['attr_keys']='';
            }
            $info['unit_name']=idtoname($info['unit_id'],'GoodsUnit','name','id',false);
            $return['status'] = 1;
            $return['info'] = $info;
        }else{
            $return['status'] = 0;
            $return['info'] = '数据获取错误';
        }

        $this->ajaxReturn($return);
   }

   /**
     * 获取下拉门店
     */
    private function get_shops_list(){
        // $map=array('shop_type'=>1); 
        $map['status']=1;
        $map['id']=array('neq',MID);  
        $shops_list=M('Shops')->where($map)->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();
    //     return $Suppliers;
    // }
    /**
     * 获取下拉供货商
     */
    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);
    }

    /**
     * 提交订货或进货
     */
    public function sub_order(){
        $return=array('status'=>1,'msg'=>'');
        $postdata=I('post.');
        $postdata['shop_id']=MID;
        $postdata['shop_id_in']=$postdata['shop_id'];
        $postdata['mtype']=1;
        $postdata['all_pre_money']=0;
        if($postdata['is_ding']==1){
            $postdata['status']=0;
            $postdata['type']=0;
        }else{
            $supplier_array=array_unique($postdata['infos']['supplier_id']);
            $supplier=array_filter($supplier_array);
            $postdata['status']=3;
            $postdata['type']=1;
            if(empty($supplier) || count($supplier_array)!=count($supplier)){$return=array('status'=>0,'msg'=>'请选择供货商');$this->ajaxReturn($return);}
        }
        if(empty($postdata['infos']['goods_id'])){$return['msg']='请选择商品'; $this->ajaxReturn($return);}
        // $postdata['infos']['request_num']=$postdata['infos']['freight_num'];
        $postdata['infos']['fact_num']=$postdata['infos']['freight_num'];
        
        $result=D('Common/InvoicingOrder')->order_in_insert($postdata);
        $return=$result;
        $this->ajaxReturn($return);
    }

    /**
     * 货流通知
     */
    public function freight_management(){
         $auth_code = 'fmanage_mlist';
        $ret=D('Shop/Shops')->shop_account_option($auth_code);
        if($ret['status']!=1) {$this->error($ret['msg']);exit;}


        $this->assign('shop_name',idtoname(MID,'Shops','name'));
        $param=I('param.');
        $this->assign($param);
        $tabid=$param['tabid'];
        $this->assign('status_array',array('0'=>'货流状态','1'=>'配货中','2'=>'待入库'));
        $this->assign($param);
        $this->assign('title_ass','货流通知');
        if(empty($tabid)) {
            $param['shop_id'] = MID;
            // $param['status'] = 2;
            $param['in_out'] = 3;
            // $data = D('Shop/InvoicingOrder')->order_list($param,1);
            $data=$this->order_list($param,1);
            if($param['is_return']){$this->export_freight_management($data['data']['list']);exit;}
            if ($data['status'] == 1) {$this->assign($data['data']);}
        }else{
            $id=I('id');
            $param['order_id']=$id;
            $param['shop_id'] = MID;
            $order_info=D('Shop/InvoicingOrder')->order_info($param);
            // echo "<pre>";
            // print_r($order_info);
            if($order_info['status']==1){$this->assign($order_info['data']);}
            else{$this->error($order_info['msg']);}
        }
        $this->assign('menu_tab','');
        $tabid=$tabid?$tabid:'freight_management';
        $this->display($tabid);
    }

    public function order_list($param){
        $return=array('status'=>0,'msg'=>'');
        if(empty($param['shop_id'])){$return['msg']='参数错误'; return $return;}
        $map = array();
        if($param['status']) $map['status']=$param['status'];//默认查询所有的状态
        $map['shop_id_in|shop_id_out'] = $param['shop_id'];
        $map['_string']='(type = 4 and (status = 2 or status = 1)) or (type = 0 and status = 2) or (type = 1 and status = 2)';
        if($param['sn']){$map['sn']=array('like','%'.$param['sn'].'%');}
        if($param['data_from']){$map['add_time'][] = array('egt',strtotime($param['data_from']));}
        if($param['data_to']){$map['add_time'][] = array('elt',strtotime($param['data_to']));}
        $order='id desc';
        $order_list=page_list('InvoicingOrder',$map,$order,'',20);
        if($param['is_return'])$order_list['list']=M('InvoicingOrder')->where($map)->order($order)->select();
        if(empty($order_list['list'])){$return['msg']='暂无数据'; return $return;}
        $return['status']=1;
        $return['data']=$order_list;
        return $return;
    }
    public function export_freight_management($list){
        $title = array('ID', '流水号', '总数', '金额', '时间','入库门店','出库门店', '状态');
        $data = array();
        foreach ($list as $k => $v) {
            $data[$k][] = $v['id'];
            $data[$k][] = $v['sn'];
            $data[$k][]=$v['count'];
            $data[$k][] = $v['all_money'];
            $data[$k][] =time_format($v['add_time']);
            $data[$k][]=idtoname($v['shop_id_in'],'Shops','name');
            $data[$k][]=idtoname($v['shop_id_out'],'Shops','name');
            $data[$k][]=$this->order_status[$v['status']];
        }
        export_csv('货流通知.csv',$title,$data);
        unset($title, $data);
        exit;
    }


    // 货流管理 最新版
    public function freight_management_new(){

        $param=I('param.');
        $tabid=$param['tabid'];
        $this->assign('title_ass','货流通知');
        if(empty($tabid)) {
            $postdata = I('param.');
            $sn = $postdata['sn'];
            $status = $postdata['status'];
            $type = $postdata['type'];
            $shopid=MID;
            if($sn){$map['sn'] = array('like','%'.$sn.'%');}
            if($status){$map['status'] = $status-1;}
            if($type){$map['type'] = $type-1;}
            $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);

        }else{
            $id=I('id');
            $param['order_id']=$id;
            $param['shop_id'] = MID;
            $order_info=D('Shop/InvoicingOrder')->order_info($param);
            // echo "<pre>";
            // print_r($order_info);
            if($order_info['status']==1){$this->assign($order_info['data']);}
            else{$this->error($order_info['msg']);}
        }
        $this->assign('menu_tab','');
        $tabid=$tabid?$tabid:'freight_management_new';
        $this->display($tabid);



    }

    /**
     * 确认收货
     */
    public function confirm_goods(){
        $auth_code = 'fmanage_mlist_confirm_goods';
        $ret=D('Shop/Shops')->shop_account_option($auth_code);
        if($ret['status']!=1) {$this->ajaxReturn($ret);}

        $postdata=I('post.');
        $id=$postdata['id'];
        $return=array('status'=>0,'msg'=>'');
        if(empty($id)){$return['msg']='参数错误'; $this->ajaxReturn($return);}
        $res=$this->update_order($postdata);
        if($res['status']==1) {
            //修改对账信息
            D('Common/InvoicingOrder')->add_invoicing_detail($id,1,1);
            D('Common/InvoicingOrder')->add_storage($id);
            $return['status']=1;
            $return['msg']='确认收货成功';
            $return['url']=U('InvoicingOrder/freight_management');
            $this->ajaxReturn($return);
        }else{
            $return['msg']='该订单不能确认入库';
            $this->ajaxReturn($return);
        }
    }
    /**
     * 确认配货
     */
    public function confirm_prepare_goods(){
          $auth_code = 'fmanage_mlist_confirm_prepare';
        $ret=D('Shop/Shops')->shop_account_option($auth_code);
        if($ret['status']!=1) {$this->ajaxReturn($ret);}

        $postdata=I('post.');
        $id=$postdata['id'];
        $return=array('status'=>0,'msg'=>'');
        if(empty($id)){$return['msg']='参数错误'; $this->ajaxReturn($return);}
        $res=$this->update_order($postdata,1);
        if($res['status']==1) {
            //修改对账信息
            // D('Common/InvoicingOrder')->add_invoicing_detail($id,1,1);
            // D('Common/InvoicingOrder')->add_storage($id);
            $return['status']=1;
            $return['msg']='确认配货成功';
            $return['url']=U('InvoicingOrder/freight_management');
            $this->ajaxReturn($return);
        }else{
            $return['msg']='该订单不能确认配货';
            $this->ajaxReturn($return);
        }
    }
    private function update_order($postdata,$is_prepare=0){
        $map=array();$savedata=array();
        $count_total=$total_money=0;
        $map['id']=$postdata['id'];
        if($is_prepare==1){
            $map['status']=1;
            $savedata['status']=2;
        } else {
            $map['status']=2;
            $savedata['status']=3;
        }
        $savedata['update_time']=NOW_TIME;
        if($postdata['fact_num']){
            foreach($postdata['fact_num'] as $k =>$v){
                $count_total+=$v;
                $total_money+=format_decimal($v*$postdata['supply_price'][$k]);
            }
        }
        $savedata['count']=$count_total;
        $savedata['all_money']=$total_money;
        $res=M('InvoicingOrder')->where($map)->save($savedata);
        if($res){
            $map=array();
            $map['order_id'] = $postdata['id'];
            $savedata = array();
            if($is_prepare==1) $savedata['status']=2;
            else $savedata['status'] = 3;
            $savedata['update_time']=NOW_TIME;
            foreach($postdata['fact_num'] as $k => $v){
                $map['goods_id']=$postdata['goods_id'][$k];
                $savedata['fact_num']=$v;
                $savedata['all_money']=format_decimal($v*$postdata['supply_price'][$k]);
                M('InvoicingGoods')->where($map)->save($savedata);
            }
            if($is_prepare==1){
                $shop_id=M('InvoicingOrder')->where('id='.$postdata['id'])->getField('shop_id_in');
                FrieghtPushSend($shop_id);
            }
            $return['status']=1;
            return $return;
        }else{
            if($is_prepare==1) $return['msg']='配货失败';
            else $return['msg']='入库失败';
            $return['status']=0;
            return $return;
        }
    }
    public function refuse_goods(){
         $auth_code = 'fmanage_mlist_refuse';
        $ret=D('Shop/Shops')->shop_account_option($auth_code);
        if($ret['status']!=1) {$this->ajaxReturn($ret);}

        $id=I('id');
        $result=D('Common/InvoicingOrder')->cancel_order($id);
        $this->ajaxReturn($result);
    }
    /**
     * 获取分类
     */
    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 cancel_order(){
        $return=array('status'=>3,'msg'=>'');
        $postdata=I('post.');
        $id=$postdata['order_id'];
        if(empty($id)){$return['msg']='参数错误'; $this->ajaxReturn($return);}
        $type=$postdata['type'];
        $result=D('Common/InvoicingOrder')->cancel_order($id,$type);
        if($result['status']==1){
            $return=$result;
            $this->ajaxReturn($return);
        }else{
            $return['msg']=$result['msg'];
            $this->ajaxReturn($return);
        }
    }
    /**
     * 报损列表
     */
    public function bad_goods(){
        $param=I('param.');
        $tabid=$param['tabid'];
        $param['shop_id']=MID;//门店id
        $this->assign('title_ass','报损');
        if(empty($tabid)){//报损列表
            $map = array();
            $map['type_id'] = MID;
            $map['type'] = 3;
            $map['info_type'] = 1;
            $param['mtype']=1;
            $field='id,addtime,bad_all_money,turnover_proportion,bad_all_num';
            $list=page_list('StocktakingInfo',$map,'addtime desc',$field);
            if($list){
                $this->assign($list);
            }
        }elseif($tabid=='bad_add_goods'){//添加报损单页面
            $chu_type = 2;//订货单位 2供货商 3仓库
            $this->assign('chu_type',$chu_type);
            $this->assign('storage_id',1);
            $this->assign('shop_id',$param['shop_id']);//入库的门店id
        }else{
            $id=I('id');
            $param['order_id']=$id;
            $field='id,addtime,bad_all_money,remarks';
            $map = $where = array();
            $map['id'] = $id;
            $info=M('StocktakingInfo')->where($map)->field($field)->find();
            if(empty($info)){$this->error("无报损记录");}
            $where=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($where)->field($field)->select();
            foreach($list as $k=>$v){
                $list[$k]['cate_name']=idtoname($v['cate_id'],'PurchaseCategory');
                $map=array();
                $map['goods_id']=$v['goods_id'];
                $map['attr_key']=$v['goods_attr_sn'];
                $goods_attr_sn=M('GoodsAttrStock')->where($map)->getField('goods_attr_sn');
                if($goods_attr_sn)$list[$k]['goods_attrsn']=$goods_attr_sn;
                $list[$k]['attr_name']=attr_key2name($v['goods_attr_sn'],$v['goods_id']);
            }
            $this->assign('info',$info);
            $this->assign('list',$list);
        }
        $this->getcateTree();
        $this->assign('menu_tab','');
        $tabid=$tabid?$tabid:'bad_goods';
        $this->display($tabid);
    }
    /**
     * 报损打印
     */
    public function bad_order_print(){
        $id = I('get.id');
        $template = 'bad_goods_template';
        $map=array('id'=>$id);
        $field='id,addtime,bad_all_money,turnover_proportion,bad_all_num,remarks';
        $order_info = M('StocktakingInfo')->where($map)->field($field)->find();
        $where=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';
        $order_goods = M('StocktakingGoods')->where($where)->field($field)->select();
        foreach($order_goods as $k=>$v){
            $order_goods[$k]['cate_name']=idtoname($v['cate_id'],'PurchaseCategory');
            $map=array();
            $map['goods_id']=$v['goods_id']; 
            $map['attr_key']=$v['goods_attr_sn'];
            $goods_attr_sn=M('GoodsAttrStock')->where($map)->getField('goods_attr_sn');
            if($goods_attr_sn)$order_goods[$k]['goods_attrsn']=$goods_attr_sn;else $order_goods[$k]['goods_attrsn']=$v['goods_sn'];
            $order_goods[$k]['attr_name']=attr_key2name($v['goods_attr_sn'],$v['goods_id']);
            if($v['goods_attr_sn'] && $order_goods[$k]['attr_name'])$order_goods[$k]['attr_name'] = $order_goods[$k]['attr_name'];else $order_goods[$k]['attr_name'] = '无';
        }
        $url = C('WEB_URL');
        $phone = C('WEB_SITE_PHONE');
        $name = C('WEB_SITE_TITLE');
        $admin = idtoname(MID,'Shops','name');
        $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("order_print");
    }
    //添加报损记录
    function bad_add(){
        $return=array('status'=>3,'');
        $is_open_audit=C('IS_OPEN_STOCKTAKING_AUDIT');
        $postdata=I('post.');
        // echo "<pre>";
        // print_r($postdata);exit;
        $post_list=$postdata['infos'];
        if(empty($post_list)){$return['msg']="请添加报损商品";$this->ajaxReturn($return);}
        $now_time=NOW_TIME;
        $shop_id=MID;
        $shop_account_id=MID;
        $bad_all_money=floatval($postdata['bad_all_money']);
        $bad_all_num=intval($postdata['bad_all_num']);
        $remarks=empty($postdata['remarks'])?'无':$postdata['remarks'];
        $data=array(
            'type'=>3,
            'type_id'=>$shop_id,
            'addtime'=>$now_time,
            'admin_id'=>$shop_account_id,
            'remarks'=>$remarks,
            'info_type'=>1,
            'bad_all_money'=>$bad_all_money,
            'bad_all_num'=>$bad_all_num,
            'status'=>empty($is_open_audit)?1:0,//审核状态
        );
        $id=M('StocktakingInfo')->add($data);
        if($id<=0){$return['msg']="添加报损失败";$this->ajaxReturn($return);}
        $list=array();
        foreach($post_list['goods_name'] as $k=>$v){
            $supplier_id=empty($post_list['supplier_id'][$k])?0:$post_list['supplier_id'][$k];
            $goods_attr_sn = empty($post_list['goods_attr_sn'][$k])?0:$post_list['goods_attr_sn'][$k];
            $list_info=array(
                'stocktaking_id'=>$id,
                'goods_id'=>$post_list['goods_id'][$k],
                'cate_id'=>$post_list['cat_id'][$k]?$post_list['cat_id'][$k]:0,
                'supplier_id'=>$supplier_id,
                'shop_id'=>$shop_id,
                'goods_name'=>$v,
                'goods_sn'=>$post_list['goods_sn'][$k],
                'goods_attr_sn'=>$goods_attr_sn,
                'remark'=>$remarks,
                'info_type'=>1,
                'bad_money'=>$post_list['supply_price'][$k],
                'bad_num'=>$post_list['freight_num'][$k],
                'status'=>empty($is_open_audit)?1:0,//审核状态
            );
            if($goods_attr_sn) $list_info['goods_sn']=$goods_attr_sn;
            $list[]=$list_info;
            if($list_info['status']==1 && $is_open_audit==0) {
                //修改库存并记录日志
                $map = array('goods_id' => $list_info['goods_id'], 'goods_stock' => $list_info['goods_attr_sn'], 'shop_id' => $shop_id);
                $stock = M('ShopsGoodsStock')->where($map)->getField('goods_number');
                M('ShopsGoodsStock')->where($map)->setDec('goods_number', $list_info['bad_num']);
                $attr_key = empty($post_list['attr_key'][$k]) ? '' : $post_list['attr_key'][$k];
                change_stock_log($shop_id, 0, $stock, $list_info['goods_id'], $list_info['bad_num'], 1, '商品报损', 8, $attr_key);
            }
        }
        $res=M('StocktakingGoods')->addAll($list);
        if($res==false){$return['msg']="添加报损商品失败";$this->ajaxReturn($return);}else $return['msg']="添加成功";
        $return['status']=1;
        $return['id'] = $id;
        $this->ajaxReturn($return);
    }
    public function other_goods(){
        $param=I('param.');
        $param['shop_id']=MID;
        $tabid=$param['tabid'];
        $param['chu_type']=2;
        $this->get_shops_list();
        $chu_type = 2;//订货单位 2供货商 3仓库
        $this->assign('chu_type',$chu_type);
        $this->assign('storage_id',1);
        $this->assign('title_ass','库存查询');
        $this->assign('shop_id',$param['shop_id']);//入库的门店id
        $this->display();
    }
    /**查询别店库存开始**/
    public function othergoods(){
        $return=array('status'=>1,'msg'=>'');
        $postdata=I('post.');
        $shop_id=intval($postdata['shop_id']);
        $goods_ids=$postdata['infos']['goods_id'];
        if($shop_id==0){$return['status']=3;$return['msg']='没选门店';$this->ajaxReturn($return);}
        if(empty($goods_ids)){$return['status']=3;$return['msg']='没选商品';$this->ajaxReturn($return);}
        $map=array(
            'shop_id'=>$shop_id,
            'goods_id'=>array('in',$goods_ids)
        );
        $goods_list=M('ShopsGoodsStock')->where($map)->field('goods_id,goods_number,goods_stock')->select();
        if(count($goods_ids)==count($goods_list)){
            $return['show']=1;
        }else{
            $return['show']=0;
            $return['msg']='该门店下没有所查商品的部分商品';
        }
        
        if($goods_list){
            foreach($goods_list as $k=>$v){
                if($v['goods_stock']){
                    $goods_list[$k]['index']=$v['goods_id'].'-'.$v['goods_stock'];
                }else{
                    $goods_list[$k]['index']=$v['goods_id'].'-';
                }
                $goods_list[$k]['shop_name']=idtoname($shop_id,'Shops','name');
                $new_goods[]=$v['goods_id'];
                
            }
            
            $return['data']=$goods_list;
        }else{
            $return['status']=0;
        }    
        $this->ajaxReturn($return);
        
    }
    /**
     * 盘点列表
     */
    public function stocktaking_goods(){
        $param=I('param.');
        $tabid=$param['tabid'];
        $param['shop_id']=MID;//门店id
        $this->assign('title_ass','盘点');
        if(empty($tabid)){//盘点列表
            $map = array();
            $map['type_id'] = MID;
            $map['type'] = 3;
            $map['info_type'] = 0;
            $field='id,all_stock,reality_sum,profit_sum,loss_sum,addtime';
            $list=page_list('StocktakingInfo',$map,'addtime desc',$field);
            if($list){
                $this->assign($list);
            }
        }elseif($tabid=='stocktaking_add_goods'){//添加盘点单页面
            $map = array('s.shop_id' => MID);
            $cate_id = $getdata['cate_id'];
            // if (!empty($cate_id)) {
            //     $map['g.cat_id'] = $cate_id;
            // }
            $map['g.is_delete']=0;
            $map['g.status']=1;
            $map['g.sale_type']=0;
            $join = 'LEFT JOIN __GOODS__ g ON s.goods_id=g.id';
            $count =M('ShopsGoodsStock')->alias('s')->join($join)->where($map)->count();
            $this->assign('sum_count',$count);
            $chu_type = 2;//订货单位 2供货商 3仓库
            $this->assign('chu_type',$chu_type);
            $this->assign('storage_id',1);
            $this->assign('shop_id',$param['shop_id']);//入库的门店id
        }else{
            $id=I('id');
            $field='id,all_stock,reality_sum,profit_sum,loss_sum,addtime';
            $map = $where = array();
            $map['id'] = $id;
            $info=M('StocktakingInfo')->where($map)->field($field)->find();
            if(empty($info)){$this->error("无盘点记录");}
            $where=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($where)->field($field)->select();
            foreach($list as $k=>$v){
                $list[$k]['cate_name']=idtoname($v['cate_id'],'PurchaseCategory');
                $map=array();
                $map['goods_id']=$v['goods_id'];
                $map['attr_key']=$v['goods_attr_sn'];
                $goods_attr_sn=M('GoodsAttrStock')->where($map)->getField('goods_attr_sn');
                if($goods_attr_sn)$list[$k]['goods_attrsn']=$goods_attr_sn;
                $list[$k]['attr_name']=attr_key2name($v['goods_attr_sn'],$v['goods_id']);
            }
            $this->assign('info',$info);
            $this->assign('list',$list);
        }
        $this->getcateTree();
        $this->assign('menu_tab','');
        $tabid=$tabid?$tabid:'stocktaking_goods';
        $this->display($tabid);
    }
    /**
     * 盘点打印
     */
    public function stocktaking_order_print(){
        $id = I('get.id');
        $template = 'stocktaking_goods_template';
        $map=array('id'=>$id);
        $field='id,all_stock,reality_sum,profit_sum,loss_sum,addtime,remarks';
        $order_info = M('StocktakingInfo')->where($map)->field($field)->find();
        $where=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';
        $order_goods = M('StocktakingGoods')->where($where)->field($field)->select();
        foreach($order_goods as $k=>$v){
            $order_goods[$k]['cate_name']=idtoname($v['cate_id'],'PurchaseCategory');
            $map=array();
            $map['goods_id']=$v['goods_id']; 
            $map['attr_key']=$v['goods_attr_sn'];
            $goods_attr_sn=M('GoodsAttrStock')->where($map)->getField('goods_attr_sn');
            if($goods_attr_sn)$order_goods[$k]['goods_attrsn']=$goods_attr_sn;else $order_goods[$k]['goods_attrsn']=$v['goods_sn'];
            $order_goods[$k]['attr_name']=attr_key2name($v['goods_attr_sn'],$v['goods_id']);
            if($v['goods_attr_sn'] && $order_goods[$k]['attr_name'])$order_goods[$k]['attr_name'] = $order_goods[$k]['attr_name'];else $order_goods[$k]['attr_name'] = '无';
        }
        $url = C('WEB_URL');
        $phone = C('WEB_SITE_PHONE');
        $name = C('WEB_SITE_TITLE');
        $admin = idtoname(MID,'Shops','name');
        $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("order_print");
    }
    //添加盘点记录
    function stocktaking_add(){
        $return=array('status'=>3,'');
        $is_open_audit=C('IS_OPEN_STOCKTAKING_AUDIT');
        $postdata=I('post.');
        $post_list=$postdata['infos'];
        if(empty($post_list)){$return['msg']="请添加盘点商品";$this->ajaxReturn($return);}
        $now_time=NOW_TIME;
        $shop_id=MID;
        $shop_account_id=MID;
        $remarks=empty($postdata['remarks'])?'无':$postdata['remarks'];
        $data=array(
            'all_stock'=>$postdata['all_stock'],
            'reality_sum'=>$postdata['reality_sum'],
            'profit_sum'=>$postdata['profit_sum'],
            'loss_sum'=>$postdata['loss_sum'],
            'type'=>3,
            'type_id'=>$shop_id,
            'addtime'=>$now_time,
            'admin_id'=>$shop_account_id,
            'remarks'=>$remarks,
            'info_type'=>0,
            'status'=>empty($is_open_audit)?1:0,//审核状态
        );
        $id=M('StocktakingInfo')->add($data);
        if($id<=0){$return['msg']="添加盘点失败";$this->ajaxReturn($return);}
        $list=array();
        foreach($post_list['goods_name'] as $k=>$v){
            $supplier_id=empty($post_list['supplier_id'][$k])?0:$post_list['supplier_id'][$k];
            $goods_attr_sn = empty($post_list['goods_attr_sn'][$k])?0:$post_list['goods_attr_sn'][$k];
            $list_info=array(
                'stocktaking_id'=>$id,
                'goods_id'=>$post_list['goods_id'][$k],
                'cate_id'=>$post_list['cat_id'][$k]?$post_list['cat_id'][$k]:0,
                'supplier_id'=>$supplier_id,
                'shop_id'=>$shop_id,
                'goods_name'=>$v,
                'goods_sn'=>$post_list['goods_sn'][$k],
                'goods_attr_sn'=>$goods_attr_sn,
                'stock'=>$post_list['stock'][$k],
                'reality'=>$post_list['freight_num'][$k],
                'profit_num'=>$post_list['profit_sum'][$k],
                'loss_num'=>$post_list['loss_num'][$k],
                'remark'=>$remarks,
                'info_type'=>0,
                'status'=>empty($is_open_audit)?1:0,//审核状态
            );
            if($post_list['goods_attr_sn'][$k]) $list_info['goods_sn']=$post_list['goods_attr_sn'][$k];
            $list[]=$list_info;
            //如果库存有变动，则修改库存并记录日志
            if($list_info['stock']!=$list_info['reality'] && $list_info['status']==1 && $is_open_audit==0){
                $map=array('goods_id'=>$list_info['goods_id'],'goods_stock'=>$list_info['goods_attr_sn'],'shop_id'=>$shop_id);
                $data_info=array('goods_number'=>$list_info['reality']);
                M('ShopsGoodsStock')->where($map)->save($data_info);
                if($list_info['loss_num']>0){$change_type=1; $change_number=$list_info['loss_num'];}
                else {$change_type=0; $change_number=$list_info['profit_num'];}
                $attr_key=empty($post_list['attr_key'][$k])?'':$post_list['attr_key'][$k];
                change_stock_log($shop_id,0,$list_info['stock'],$list_info['goods_id'],$change_number,$change_type,'库存盘点修正',7,$attr_key);
            }
        }
        $res=M('StocktakingGoods')->addAll($list);
        if($res==false){$return['msg']="添加盘点商品失败";$this->ajaxReturn($return);}else $return['msg']="添加成功";
        $return['status']=1;
        $return['id'] = $id;
        $this->ajaxReturn($return);
    }
    public function return_goods_list(){
        $param=I('param.');
        $param['shop_id']=MID;
        $tabid=$param['tabid'];
        $this->get_shops_list();
        $this->get_supplier_list();
        $this->assign('storage_id',1);
        $this->assign('title_ass','退货');
        $this->getcateTree();
        $this->assign('shop_id',$param['shop_id']);//入库的门店id
        $this->display();
    }
    public function return_goods(){
        $return=array('status'=>3,'msg'=>'');
        $postdata=I('post.');
        foreach ($postdata['infos']['goods_sn'] as $key => $value) {
            $data['list'][$postdata['infos']['index'][$key]]['id']=$postdata['infos']['goods_id'][$key];
            $data['list'][$postdata['infos']['index'][$key]]['goods_id']=$postdata['infos']['goods_id'][$key];
            $data['list'][$postdata['infos']['index'][$key]]['goods_sn']=$postdata['infos']['goods_sn'][$key];
            $data['list'][$postdata['infos']['index'][$key]]['goods_name']=$postdata['infos']['goods_name'][$key];
            $data['list'][$postdata['infos']['index'][$key]]['goods_attr_sn']=$postdata['infos']['goods_attr_sn'][$key];
            $data['list'][$postdata['infos']['index'][$key]]['goods_number']=$postdata['infos']['freight_num'][$key];
            $data['list'][$postdata['infos']['index'][$key]]['all_money']=$postdata['infos']['all_money'][$key];
        }
        unset($postdata['infos']);
        $data['shop_id']=MID;
        $data['uid']=$postdata['user_id'];
        $data['content']=$postdata['reason'];
        $data['reason']=$postdata['reason'];

        $shops_info=session('shops_info');
        $postdata['is_root']=$shops_info['is_root'];
        $postdata['sid']=$shops_info['sid'];
        $data['cashier_name']=$shops_info['login_name'];
        $data['money']=$postdata['money'];
        $data['cash_money']=$postdata['cash_money'];
        if(empty($postdata['is_root'])) {
            $res = D('Pad/Cashier')->check_auth($postdata['sid'], 'back');
            if ($res['status'] == 0) {
                $res['status']=3; $this->ajaxReturn($res);
            }
        }
        $result=D('Pad/Cashier')->return_goods($data);
        if($result['status']==0){$return['msg']=$result['msg']; $this->ajaxReturn($return);}
        $return['status']=1; $return['msg']=$result['msg'];
        $this->ajaxReturn($return);
    }
    // 10.8 增加
      /**
     * 货流商品变动明细列表
     */
    public function goods_detail($is_return=false){
        $auth_code = 'othergoods_kcdetail_list';
        $ret=D('Shop/Shops')->shop_account_option($auth_code);
        if($ret['status']!=1) {$this->error($ret['msg']);exit;}

        $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']);}
        $map['shop_id'] = MID;
        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;
        }
    }
     /**
     * goods_detail页面搜索商品
     */
    public function detail_search_goods(){
        $goods_sn=trim(I('post.goods_sn'));// 商品编号或名字
        $return = array('status'=>0,'msg'=>'');
        if(empty($goods_sn)){$return['msg'] = '请输入商品编号/名称';$this->ajaxReturn($return);}
        $map['shop_id'] = MID;
        $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 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();
        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']);
        }
        $map=array();
        $map['id']=$order_info['shop_id_in'];
        $map['status']=1;
        $send_shop_id=M('Shops')->where($map)->getField('send_shop_id');
        if(!empty($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 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,goods_id';
        $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');
            $where['g.id']=$v['goods_id'];
            $where['g.unit_id']=array('neq','0');
            $unit=M('Goods')->alias('g')->join('__GOODS_UNIT__ as u on g.unit_id = u.id')->where($where)->field('u.name')->find();
            $data[$k][] = $unit['name']?$unit['name']:'无';
            $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 stock_search($is_return=false){
        $auth_code = 'othergoods_list';
        $ret=D('Shop/Shops')->shop_account_option($auth_code);
        if($ret['status']!=1) {$this->error($ret['msg']);exit;}

        $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','');
            }
        }
        $map['shop_id']=MID;
        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','',20);
        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['shop_id']=MID;
            $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;
        $map['shop_id']=MID;
        $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']=MID;
                $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']=MID;
            $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(MID,'Shops','name'));
            }
            export_csv('库存查询.csv',$title,$data);
            unset($title, $data);
            exit;
        // }
    }
     /**
     * 门店进货审核
     */
    public function audit(){
        $auth_code = 'stockgoods_list_confirm';
        $ret=D('Shop/Shops')->shop_account_option($auth_code);
        if($ret['status']!=1) {$this->ajaxReturn($ret);}

        $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){
            $savedata=array();
            $savedata['status']=1;
            $res=M('InvoicingOrder')->where($map)->save($savedata);
            if($res){
                $map=array();
                $map['status']=0;
                $map['order_id']=$id;
                $savedata=array();
                $savedata['status']=1;
                $result=M('InvoicingGoods')->where($map)->save($savedata);
            }
            if($res && $result){$return=array('status'=>1,'msg'=>'审核成功');}
            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')->find();
        if(empty($order_info)){$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);}
        /*lss 2018-9-19新加开始*/
        //订货订单配货选择门店的时候要判断库存
        if(!empty($postdata['send_shop_id'])){
            $map=array('order_id'=>$id,'status'=>1);
            foreach($postdata['invoicing_goods_id'] as $k=>$v) {
                $map['id']=$v;
                $order_goods=M('InvoicingGoods')->where($map)->field('goods_id,goods_attr_sn')->find();
                $goods_attr_sn=empty($order_goods['goods_attr_sn'])?0:$order_goods['goods_attr_sn'];
                $goods_number=D('Common/Cart')->shopgoodsstock($order_goods['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($order_goods['goods_id'],'Goods','goods_name').'"商品库存不足';
                    $this->ajaxReturn($return);break;
                }
            }
        }

         $map=array('id'=>$id,'status'=>1);
        $now_time=NOW_TIME;
        $count=floatval($postdata['count']);
        $all_money=floatval($postdata['all_money']);
        $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);}

        

    }
    /**
    *分割
    */
      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('Shop/InvoicingOrder/index');
            $result['url']=geturl('Shop/InvoicingOrder/freight_management_new');
        }
        $this->ajaxReturn($result);
    }
     /**
     * 差异库存审核
     */
    public function differ_confirm(){
        $return=array('status'=>0,'msg'=>'');
        $postdata=I('post.');
        // $postdata['id']=289;
        $postdata['differ_type']=1;
        if(empty($postdata['id'])){$return['msg']='参数错误';$this->ajaxReturn($return);}
        $map=array();
        $map['id']=$postdata['id'];
        $map['status']=3;
        $map['audit_status']=0;
        $order_info=M('InvoicingOrder')->where($map)->field('id,sn,shop_id_in,shop_id_out')->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']=3;
            $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')->select();
                foreach ($order_goods as $k => $v) {
                    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;}
                }
            }
        }
    }
    /**
     * 得到节点树
     */
    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 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['goods_attr_sn'])?'':$v['goods_attr_sn'];//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 warning(){
         $auth_code = 'othergoods_kcdetail_wan';
        $ret=D('Shop/Shops')->shop_account_option($auth_code);
        if($ret['status']!=1) {$this->error($ret['msg']);exit;}

        $postdata=I('request.');
        $stock_list=array(0=>'全部状态','1'=>"库存不足",'2'=>"库存过剩");
        $this->assign('stock_list',$stock_list);
        $map=array();
        $shop_id=MID;
        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);
// echo M('ShopsGoodsStock')->alias('a')->join($join)->where($map)->field($filed)->fetchSql(true)->select();
        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();
    }
    /**库存预警结束**/

     /**报损开始**/
    //报损记录
    function bad_list($is_return=false){
        $auth_code = 'badgoods_list';
        $ret=D('Shop/Shops')->shop_account_option($auth_code);
        if($ret['status']!=1) {$this->error($ret['msg']);exit;}
        

        $postdata=I('param.');
        $postdata['shop_id']=MID;
        $map=array();
        if($postdata['shop_id']){$map['type_id']=$postdata['shop_id'];}
        $map['type']=3;
        $map['info_type']=1;
        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(){

        $ret=D('Shop/Shops')->shop_account_option("badgoods_list_print");
        if($ret['status']!=1) { $this->error($ret['msg']);}

        $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'=>1);
        $field='id,bad_all_money,remarks,status';
        $info=M('StocktakingInfo')->where($map)->field($field)->find();
        if(empty($info)){echo '无报损记录';exit;}
        $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)){echo '暂无记录';exit;}
        foreach($list as $k=>$v){
            $list[$k]['attr_name']=D("Common/GoodsAttr")->goods_to_attrname($v['goods_attr_sn']);
            //$list[$k]['attr_name']=attr_key2name($v['goods_attr_sn'],$v['goods_id']);
            $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;
            }*/
        }
        //print_r($list);exit;
        $data=array('info'=>$info,'list'=>$list);
        $this->assign($data);
        $this->display();
    }
    public  function bad_print()
    {
        $ret=D('Shop/Shops')->shop_account_option("badgoods_list_print");
        if($ret['status']!=1) { $this->error($ret['msg']);}

        $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.');
        $auth_code='';
        if($postdata['type']==1){   //限定是商品
            switch ($postdata['status']) {
        // status 3作废  2拒绝 1审核通过
                case '1':
                     $auth_code = 'badgoods_confirm';
                    break;
                case '2':
                    $auth_code = 'badgoods_list_cancel';
                    break;
                case '3':
                    $auth_code = 'badgoods_list_cancel';
                    break;
            }

        }
        if($postdata['type']==0){   ////盘点
            switch ($postdata['status']) {
                 case '1':
                     $auth_code = 'stocktaking_confirm';
                    break;
                case '2':
                    $auth_code = 'stocktaking_del';
                    break;
                case '3':
                    $auth_code = 'stocktaking_del';
                    break;
            }


        }
        if($auth_code){
             $ret=D('Shop/Shops')->shop_account_option($auth_code);
            if($ret['status']!=1) { $this->ajaxReturn($ret);}
        }

        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();
                $is_changestock = C("IS_OPEN_STOCKTAKING_AUDIT");
                if($type==0) {
                    //盘点修改库存并记录日志
                    if($is_changestock == 1){
                        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){
                    //报损修改库存并记录日志
                    if($is_changestock == 1){
                        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');
                            M('ShopsGoodsStock')->where($map)->setDec('goods_number', $v['bad_num']);
                            $attr_key = empty($v['goods_attr_sn']) ? '' : $v['goods_attr_sn'];
                            change_stock_log($v['shop_id'], 0, $stock, $v['goods_id'], $v['bad_num'], 1, '商品报损', 8, $attr_key);
                        }
                    }
                }
            }
            $return['msg']='操作成功';
            $return['status']=1;
            $this->ajaxReturn($return);
        }else{
            $return['msg']='操作失败';
            $this->ajaxReturn($return);
        }
    }
    /**盘点开始**/
    //盘点记录
    public function stocktaking_list(){

        $ret=D('Shop/Shops')->shop_account_option('stocktaking_list');
        if($ret['status']!=1) { $this->ajaxReturn($ret);}


        $this->assign('is_gain_arr',array('1'=>'盘盈','2'=>'盘亏'));
        $stock_show=C("IS_OPEN_STOCKTAKING_SHOW");
        $this->assign('stock_show',$stock_show);
        $postdata=I('param.');
        $postdata['shop_id']=MID;
        $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);}
        if($postdata['status']||$postdata['status']==='0'){$map['status']=$postdata['status'];}
        $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=array();
        if($postdata['print']=='print'){ $list=M('StocktakingInfo')->where($map)->field($field)->order('addtime desc')->select(); $this->stocktaking_export($list);exit;}
        else {$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_export($list){
         $stock_show=C("IS_OPEN_STOCKTAKING_SHOW");
         $title=$data=array();
        if($stock_show==1)$title=array('ID','盘前库存','盘盈','盘亏','盘后库存','盘盈金额','盘亏金额','盘点时间','盘点人','审核状态','审核人','审核时间','审核备注');
        else $title=array('ID','盘后库存','盘点时间','盘点人','审核状态','审核人','审核时间','审核备注');
        foreach($list as $k=>$val){
            $data[$k][] = $val['id'];
            if($stock_show==1){
                $data[$k][] = floatval($val['all_stock']);
                $data[$k][] = floatval($val['profit_sum']);
                $data[$k][] = floatval($val['loss_num']);
            }
            $data[$k][] = floatval($val['reality_sum']);
            if($stock_show==1){
                $data[$k][] = $val['profit_all_money'];
                $data[$k][] = $val['loss_all_money'];
            }
            $data[$k][] = empty($val['add_time'])?'':time_format($val['add_time']);
            $data[$k][]=idtoname($val['admin_id'],'Shops','name');
            $data[$k][]=$this->stock_status[$val['status']];//==1?'通过':$val['status']==2?'拒绝':$val['status']==3?"作废":"未审核";

            if ($val['status'] == 3 && $val['audit_name'] == '') {$data[$k][] = '自动';}elseif($val['audit_name']){$data[$k][]=$val['audit_name'];}else{$data[$k][]='';}
            $data[$k][]=time_format($val['audit_time']);
            $data[$k][] = $val['audit_remarks'];
        }
        export_csv('盘点历史.csv',$title, $data);
        unset($title, $data);
        exit;
    }
    //盘点记录商品
    public function stocktaking_info(){
        $stock_show=C("IS_OPEN_STOCKTAKING_SHOW");
        $this->assign('stock_show',$stock_show);
        $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,remarks,status';
        $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');
    }
    /**盘点结束**/

     public function freight_management_export(){
        $postdata=I('get.');
        $sn = $postdata['sn'];
        $status = $postdata['status'];
        $type = $postdata['type'];
        $shopid=MID;
        if($sn){$map['sn'] = array('like','%'.$sn.'%');}
        if($status){$map['status'] = $status-1;}
        if($type){$map['type'] = $type-1;}
        $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($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;
    }
}    
?>