<?php
/** wap
 * 进销存
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaol liushanshan
 */
namespace App\Controller;
use Common\Controller\HanchaoController;
class InvoicingOrderController extends BaseController {
    public function _initialize(){
        parent::_initialize ();
    }
    /**
    *  查询商品
    */
    public function search_goods(){
        $return=array('status'=>1,'msg'=>'');
        $sid=I('sid');
        $token=I('token');
        $postdata=I('param.');
        $postdata['p'] = $postdata['page'];
        $result=D('App/InvoicingOrder')->search_by_keyword($postdata);
        if($result['status']==0){
            $return['status']=2;
            $return['msg']=$result['msg'];
            $this->ajaxReturn($return);
        }
        $returndata=D('App/InvoicingOrder')->arr_page($result['data'],$postdata['pagefrom']);
        $return['data']=$returndata['attr'];
		$return['arr']=$result['arr'];
        $return['pagefrom']=intval($returndata['pagefrom']);
        $this->ajaxReturn($return);
    }
    /**
    *  获取分类
    */
    public function get_category(){
        $return=array('status'=>1,'msg'=>'');
        $cate_list = D('Goods')->category_lists();
        $return['is_other_shop_num']=C('IS_OTHER_SHOP_SEE_NUM');
        if($cate_list['status'] == 1){
            $return['data']=$cate_list['data'];
            $this->ajaxReturn($return);
        }else{
            $return['status']=2;
            $return['msg']=$cate_list['msg'];
            $this->ajaxReturn($return);
        }
    }
    /**
    *获取二级分类
    */
    public function category_two_lists(){
        $postdata=I('param.');
        $return=array('status'=>1,'msg'=>'');
        $cate_list = D('Goods')->category_two_lists($postdata);
        if($cate_list['status'] == 1){
            $return['data']=$cate_list['data'];
            $this->ajaxReturn($return);
        }else{
            $return['status']=2;
            $return['msg']=$cate_list['msg'];
            $this->ajaxReturn($return);
        }
    }
    //获取供货商
    public function get_suppliers($is_return=false){
        $map=array();
        $map['status']=1;
        $suppliers_list=M('Suppliers')->where($map)->field('id,name')->select();
        foreach($suppliers_list as $k => $v){
            $supplier_list[$v['id']]['name']=$v['name'];
            $supplier_list[$v['id']]['id']=$v['id'];
        }
        $return['status']=1;
        $return['data']=$supplier_list;
        if($is_return==true){
            return $return;
        }else{
            $this->ajaxReturn($return);
        }
    }
    /**
     * 订货,进货,货流通知列表
     * @return array
     */
    public function get_order_list(){
        $return=array('status'=>1,'msg'=>'');
        $sid=I('sid');
        $token=I('token');
        $post=$data=array();
        $post=I('post.');
        $is_huoliu=empty($post['is_huoliu'])?0:$post['is_huoliu'];
        $post['type']=empty($post['type'])?0:$post['type'];
        /*验证权限开始*/
        if($post['type']==0 && $post['mtype']==1 && $is_huoliu==0){
            $auth_code='ordergoods_list';
        }
        if($post['type']==1 && $post['mtype']==1 && $is_huoliu==0){
            $auth_code='stockgoods_list';
        }
        if($is_huoliu==1){
            $auth_code='fmanage_mlist';
        }
        if($post['type']==4 && $post['mtype']==1 && $is_huoliu==0){
            $auth_code='transfergoods_list';
        }
        $res=D('Pad/ShopsRoleAuth')->check_auth_code($auth_code,$post);
        if($res['status']!=1){$this->ajaxReturn($res);}
        /*验证权限结束*/
        $result=D('Shop/InvoicingOrder')->order_list($post,$is_huoliu);
        if($result['status']==1){
            foreach($result['data']['list'] as $k => $v){
                $list[$k]['id']=$v['id'];
                $list[$k]['sn']=$v['sn'];
                $list[$k]['add_time']=time_format($v['add_time']);
            }
            $return['data']=$list;
            $this->ajaxReturn($return);
        }else{
            $return['status']=2;
            $return['msg']='没有更多数据了';
            $this->ajaxReturn($return);
        }
    }
    /**
     * 获取订货，进货，货流通知的订单商品
     * @return array
     */
    public function get_order_info(){
        $return=array('status'=>1,'msg'=>'');
        $sid=I('sid');
        $token=I('token');
        $order_id=I('order_id');
        $post=$data=array();
        $post=I('post.');
        $result=D('Shop/InvoicingOrder')->order_info($post);
        if($result['status']==1){
            $data['order_info']['io_sn']=$result['data']['sn'];
            $data['order_info']['remarks']=$result['data']['remarks'];
            $data['order_info']['add_time']=time_format($result['data']['add_time']);
            $data['order_info']['all_money']=floatval($result['data']['all_money']);
            $data['order_info']['shop_id_in']=$result['data']['shop_id_in'];
            $data['order_info']['shop_id_out']=$result['data']['shop_id_out'];
            $data['order_info']['type']=$result['data']['type'];
            $data['order_info']['status']=$result['data']['status'];
            $data['order_info']['is_huodaofk']=format_decimal($result['data']['offline_money']); //jxr
            $data['order_info']['pay_img']=thumb($result['data']['pay_img']); //jxr
            $data['order_info']['pay_status']=$result['data']['pay_status']; //jxr
            foreach($result['data']['order_goods'] as $k =>$v){
                if($result['data']['status']<2){
                    if($result['data']['is_transfer']==1){
                        $data['order_info']['total_num']+=$v['freight_num'];
                        $data['goods_list'][$k]['fact_num']=floatval($v['freight_num']);
                        $data['goods_list'][$k]['freight_num']=floatval($v['freight_num']);
                    }else {
                        $data['order_info']['total_num'] += $v['request_num'];
                        $data['goods_list'][$k]['fact_num'] = floatval($v['request_num']);
                        $data['goods_list'][$k]['freight_num'] = floatval($v['request_num']);
                    }
                }
                if($result['data']['status']==2){
                    if(empty($v['fact_num'])>0){
                        $data['order_info']['total_num']+=$v['fact_num'];
                        $data['goods_list'][$k]['fact_num']=floatval($v['fact_num']);
                        $data['goods_list'][$k]['freight_num']=floatval($v['fact_num']);
                    }else{
                        $data['order_info']['total_num']+=$v['freight_num'];
                        $data['goods_list'][$k]['fact_num']=floatval($v['freight_num']);
                        $data['goods_list'][$k]['freight_num']=floatval($v['freight_num']);
                    }
                }
                if($result['data']['status']==3 || $result['data']['status']==4){
                    $data['order_info']['total_num']+=$v['fact_num'];
                    $data['goods_list'][$k]['fact_num']=floatval($v['fact_num']);
                    $data['goods_list'][$k]['freight_num']=floatval($v['fact_num']);
                }
                if($result['data']['status']==5){
                    $data['order_info']['total_num']+=$v['request_num'];
                    $data['goods_list'][$k]['fact_num']=floatval($v['request_num']);
                    $data['goods_list'][$k]['freight_num']=floatval($v['request_num']);
                }
                $data['goods_list'][$k]['id']=$v['id'];
                $data['goods_list'][$k]['goods_id']=$v['goods_id'];
                $data['goods_list'][$k]['goods_name']=$v['goods_name'];
                $data['goods_list'][$k]['goods_sn']=$v['goods_sn'];
                $map=array();
                $map['attr_key']=$v['goods_attr_sn'];
                $map['goods_id']=$v['goods_id'];
                $goods_attr_sn=M('GoodsAttrStock')->where($map)->getField('goods_attr_sn');
                if($goods_attr_sn) $data['goods_list'][$k]['goods_attrsn']=$goods_attr_sn;
                $data['goods_list'][$k]['goods_attr_sn']=$v['goods_attr_sn'];
                $data['goods_list'][$k]['attr_name']=attr_key2name($v['goods_attr_sn'],$v['goods_id']);
                $data['goods_list'][$k]['supply_price']=format_price($v['supply_price']);
                $data['goods_list'][$k]['supplier_price']=$v['supply_price'];
            }
            $map=array();$map['id']=$result['data']['shop_id_in'];
            $data['order_info']['transfer_type']=M('Shops')->where($map)->getField('transfer_type');
            $return['data']=$data;
            $this->ajaxReturn($return);
        }else{
            $return['status']=3;
            $return['msg']=$result['msg'];
            $this->ajaxReturn($return);
        }
    }

    /**
     * 调货商品的门店配货
     */
    public function confirm_prepare_goods(){
        $postdata=I('post.');
        /*验证权限开始*/
        $auth_code='fmanage_mlist_confirm_prepare';
        $res=D('Pad/ShopsRoleAuth')->check_auth_code($auth_code,$postdata);
        if($res['status']!=1){$this->ajaxReturn($res);}
        /*验证权限结束*/
        $id=$postdata['order_id'];
        $return=array('status'=>3,'msg'=>'');
        if(empty($id)){$return['msg']='参数错误'; $this->ajaxReturn($return);}
        $data=array();
        $data['id']=$postdata['order_id'];
        if(!is_array($postdata['list'])) {
            $list=json_decode(htmlspecialchars_decode($postdata['list']),1);
        }else{
            $list=$postdata['list'];
        }
        foreach($list as $k => $v){
            /*if($v['freight_num']<$v['fact_num']){
                $return['msg']='商品配货量不能大于请求量';
                $this->ajaxReturn($return);break;
            }*/
            $map=array('id'=>$id);
            $order_type=M('InvoicingOrder')->where($map)->getField('type');
            $map=array('order_id'=>$id,'status'=>1);
            $map['goods_id']=$v['goods_id'];
            $map['goods_attr_sn']=$v['goods_attr_sn'];
            if($order_type==1)$request_num=M('InvoicingGoods')->where($map)->getField('freight_num');
            else $request_num=M('InvoicingGoods')->where($map)->getField('request_num');
            if($request_num<$v['fact_num']){
                $return['msg']='商品配货量不能大于请求量';
                $this->ajaxReturn($return);break;
            }
            $data['fact_num'][$k]=$v['fact_num'];
            $data['goods_id'][$k]=$v['goods_id'];
            $data['supply_price'][$k]=$v['supplier_price'];
            $data['goods_attr_sn'][$k]=$v['goods_attr_sn'];
        }
        $res=D('Common/InvoicingOrder')->update_order($data,1);
        if($res['status']==1) {
            D('Common/InvoicingOrder')->reduce_storage($id);//减少库存
            $return['status']=1;
            $return['msg']='确认配货成功';
            $this->ajaxReturn($return);
        }else{
            $return['msg']='该订单不能确认配货';
            $this->ajaxReturn($return);
        }
    }
    /**
     * 确认收货
     */
    public function confirm_goods(){
        $postdata=I('post.');
        /*验证权限开始*/
        $auth_code='fmanage_mlist_confirm_goods';
        $res=D('Pad/ShopsRoleAuth')->check_auth_code($auth_code,$postdata);
        if($res['status']!=1){$this->ajaxReturn($res);}
        /*验证权限结束*/
        $id=$postdata['order_id'];
        $return=array('status'=>3,'msg'=>'');
        if(empty($id)){$return['msg']='参数错误'; $this->ajaxReturn($return);}
        $data=array();
        $data['id']=$postdata['order_id'];
        $data['shop_id']=$postdata['shop_id'];
        if(!is_array($postdata['list'])) {
            $list=json_decode(htmlspecialchars_decode($postdata['list']),1);
        }else{
            $list=$postdata['list'];
        }
        foreach($list as $k => $v){
            $map=array('id'=>$id);
            $order_type=M('InvoicingOrder')->where($map)->getField('type');
            $map=array('order_id'=>$id,'status'=>2);
            $map['goods_id']=$v['goods_id'];
            $map['goods_attr_sn']=$v['goods_attr_sn'];
            if($order_type==1)$request_num=M('InvoicingGoods')->where($map)->getField('freight_num');
            else $request_num=M('InvoicingGoods')->where($map)->getField('request_num');
            if($request_num<$v['fact_num']){
                $return['msg']='商品确认收货量不能大于请求量';
                $this->ajaxReturn($return);break;
            }
            $data['fact_num'][$k]=$v['fact_num'];
            $data['goods_id'][$k]=$v['goods_id'];
            $data['supply_price'][$k]=$v['supplier_price'];
            $data['goods_attr_sn'][$k]=$v['goods_attr_sn'];
        }
        $res=D('Common/InvoicingOrder')->update_order($data);
        if($res['status']==1) {
            //修改对账信息
            D('Common/InvoicingOrder')->add_invoicing_detail($id,1,1);
            D('Common/InvoicingOrder')->add_storage($id);
            $return['status']=1;
            $return['msg']='确认收货成功';
            $this->ajaxReturn($return);
        }else{
            $return['msg']='该订单不能确认入库';
            $this->ajaxReturn($return);
        }
    }
    /**
     * 作废订单，拒绝收货
     */
    public function cancel_order(){
        $return=array('status'=>3,'msg'=>'');
        $postdata=I('post.');
        $type=$postdata['type'];
        /*验证权限开始*/
        switch($postdata['print_type']){
            case 1:
                $auth_code='ordergoods_cancel';
                break;
            case 4:
                if($type==1) $auth_code='fmanage_mlist_cancel';
                else $auth_code='fmanage_mlist_refuse';
                break;
            default:
                break;
        }
        $res=D('Pad/ShopsRoleAuth')->check_auth_code($auth_code,$postdata);
        if($res['status']!=1){$this->ajaxReturn($res);}
        /*验证权限结束*/
        $id=$postdata['order_id'];
        if(empty($id)){$return['msg']='参数错误'; $this->ajaxReturn($return);}
        $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 get_print_info(){
        $return = array('status' => 1);
        $sid = I('sid');
        $token = I('token');
        $post = I('post.');
        /*验证权限开始*/
        switch($post['print_type']){
            case 1://订货
                $auth_code='ordergoods_print';
                break;
            case 2://进货
                $auth_code='stockgoods_list_print';
                break;
            case 3://调货
                $auth_code='transfergoods_list_print';
                break;
            case 4://货流通知
                $auth_code='fmanage_mlist_print';
                break;
            default:
                break;
        }
        $res=D('Pad/ShopsRoleAuth')->check_auth_code($auth_code,$post);
        if($res['status']!=1){$res['status']=3;$res['msg']='无打印权限';$this->ajaxReturn($res);}
        /*验证权限结束*/
        $result = D('Common/InvoicingOrder')->invoicing_print_info($post);
        if($result['status']==0){$return['status']=3; $return['msg']=$result['msg']; $this->ajaxReturn($return);}
        $this->ajaxReturn($result);
    }
    /**
     * 提交订货单，进货单
     */
    public function sub_order_stock(){
        $return=array('status'=>1,'msg'=>'');
        $postdata=I('post.');
        if(empty($postdata['shop_id'])){$return['status']=3;$return['msg']='参数错误'; $this->ajaxReturn($return);}
        /*验证权限开始*/
        if($postdata['mtype']==1 && $postdata['status']==3 && $postdata['type']==1){
            $auth_code='stockgoods_list_confirm';
        }elseif($postdata['mtype']==1 && $postdata['status']==0 && $postdata['type']==0){
            $auth_code='ordergoods_list_confirm';
        }
        $res=D('Pad/ShopsRoleAuth')->check_auth_code($auth_code,$postdata);
        if($res['status']!=1){$this->ajaxReturn($res);}
        /*验证权限结束*/
        $postdata['shop_id_in']=$postdata['shop_id'];
        if(!empty($postdata['shop_id_out'])) $postdata['shop_id_out']=$postdata['shop_id_out'];
        $data=D('Pad/InvoicingOrder')->sub_order_stock($postdata);
        if($data['status']==0){ $this->ajaxReturn($data);}
        $result=D('Common/InvoicingOrder')->order_in_insert($data['data']);
        if($result['status']==1){
            $return['msg']='添加成功';
            $return['order_id']=$result['id'];
            $this->ajaxReturn($return);
        }else{
            $return['status']=3;
            $return['msg']=$result['msg'];
            $this->ajaxReturn($return);
        }
    }
    /**调货开始**/
    //添加调货开始
    public function transfer_add_before(){
        $return = array('status' => 1);
        $post=I('get.');
        $sid=I('get.sid');
        $is_root=I('get.is_root');
        $is_other = I('get.is_other');
        /*验证权限开始*/
        if($is_other) $auth_code='othergoods_list';
        else $auth_code='transfergoods_list_add';
        $res=D('Pad/ShopsRoleAuth')->check_auth_code($auth_code,$post);
        if($res['status']!=1){$this->ajaxReturn($res);}
        /*验证权限结束*/
        $shop_id=I('get.shop_id');
        $is_other_shop_num=C('IS_OTHER_SHOP_SEE_NUM');
        if($is_other && $is_other_shop_num==1){//全不可看，仅库存查询
            $shop_list=array();
        }else{
            if($is_other && $is_other_shop_num==2){//内部可看，仅库存查询
                $shop_type=idtoname($shop_id,'Shops','shop_type','id',false);
                if($shop_type==1){
                    $map=array('status'=>1,'id'=>array('neq',$shop_id),'shop_type'=>$shop_type);
                }else{
                    $map=array('status'=>1,'pid'=>$shop_id,'shop_type'=>$shop_type);
                }
            }else{//全部可看
                $map=array('status'=>1,'id'=>array('neq',$shop_id));
            }
            $shop_list = M('Shops')->where($map)->field('id,name')->select();
        }   
        $shoplist=array();
        foreach($shop_list as $k=>$v){
            $shoplist[$v['id']]=$v;
        }
        $return['is_other_shop_num'] = $is_other_shop_num;
        $return['shop_list'] = $shoplist;
        $this->ajaxReturn($return);
    }
    //添加调货记录
    public function transfer_add(){
        $return=array('status'=>1,'msg'=>'');
        $postdata=I('post.');
        /*验证权限开始*/
        $auth_code='transfergoods_list_confirm';
        $res=D('Pad/ShopsRoleAuth')->check_auth_code($auth_code,$postdata);
        if($res['status']!=1){$this->ajaxReturn($res);}
        /*验证权限结束*/
        if(empty($postdata['shop_id'])){$return['status']=3;$return['msg']='参数错误'; $this->ajaxReturn($return);}
        if(empty($postdata['shop_id_in'])){$return['status']=3;$return['msg']='请选择门店'; $this->ajaxReturn($return);}
        foreach($postdata['list'] as $k => $v){
            $karr = explode('-', $k);//得到属性值
            $goods_id = intval($karr[0]);
            $num = D('Common/Cart')->shopgoodsstock($goods_id,$postdata['shop_id'],$karr[1]);
            if($num['goods_number'] <= 0 || $num['goods_number'] < $v['freight_num']){$return['status']=3;$return['msg'] = '库存不足！';$this->ajaxReturn($return);}
        }
        $postdata['shop_id_out']=$postdata['shop_id'];
        $postdata['infos']=$postdata['list'];
        unset($postdata['list']);
        $data=D('Pad/InvoicingOrder')->sub_order_stock($postdata);
        if($data['status']==0){ $this->ajaxReturn($data);}
        $result=D('Common/InvoicingOrder')->order_in_insert($data['data']);
        if($result['status']==1){
            $return['msg']='已成功为门店调货';
            $return['order_id']=$result['id'];
            $this->ajaxReturn($return);
        }else{
            $return['status']=3;
            $return['msg']=$result['msg'];
            $this->ajaxReturn($return);
        }
    }
    /**报损开始**/
     //报损记录
    function bad_list(){
        $return=array('status'=>3,'msg'=>'');
        $getdata=I('get.');
        $auth_code='badgoods_list';
        $ret=D("Pad/ShopsRoleAuth")->check_auth_code($auth_code,$getdata);
        if($ret['status']!=1) $this->ajaxReturn($ret);
        $sid=$getdata['sid'];
        $shop_id=intval($getdata['shop_id']);
        if(empty($shop_id)){$return['msg']='参数错误';$this->ajaxReturn($return);}
        $map=array('type'=>3,'type_id'=>$shop_id,'info_type'=>1);
        if($getdata['data_from']){$map['addtime'][] = array('egt',strtotime($getdata['data_from']));}
        if($getdata['data_to']){$map['addtime'][] = array('elt',strtotime($getdata['data_to']));}
        $field='id,addtime,bad_all_money,turnover_proportion';
        $list=page_list('StocktakingInfo',$map,'addtime desc',$field);
        if(empty($list['list'])){$return=array('status'=>2,'msg'=>'没有更多数据了');$this->ajaxReturn($return);}
        $data=$list['list'];
        foreach($list['list'] as $k=>$v){
            $data[$k]['add_time']=time_format($v['addtime']);
        }
        $return=array('status'=>1,'data'=>$data);
        $this->ajaxReturn($return);
    }
    //报损信息
    function bad_info(){
        $return=array('status'=>3,'msg'=>'');
        $getdata=I('get.');
        $id=intval($getdata['id']);
        if(empty($id)){$return['msg']='参数错误';$this->ajaxReturn($return);}
        $map=array('id'=>$id,'info_type'=>1);
        $field='bad_all_num,bad_all_money,remarks,status,audit_name,audit_time,audit_remarks,addtime';
        $info=M('StocktakingInfo')->where($map)->field($field)->find();
        if(empty($info)){$return['msg']='无报损记录';$this->ajaxReturn($return);}
        $info['audit_time']=empty($info['audit_time'])?'':time_format($info['audit_time']);
        $info['addtime']=empty($info['addtime'])?'':time_format($info['addtime']);
        $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,status';
        $list=M('StocktakingGoods')->where($map)->field($field)->select();
        if(empty($list)){$return=array('status'=>2,'msg'=>'暂无记录');$this->ajaxReturn($return);}
        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']);
            $list[$k]['bad_num']=floatval($v['bad_num']);
        }
        $return=array('status'=>1,'data'=>array('info'=>$info,'list'=>$list));
        $this->ajaxReturn($return);
    }
    //添加报损记录
    function bad_add(){
        $return=array('status'=>3,'');
        $is_open_audit=C('IS_OPEN_STOCKTAKING_AUDIT');
        $postdata=I('post.');
        $auth_code='badgoods_list_add';
        $ret=D("Pad/ShopsRoleAuth")->check_auth_code($auth_code,$postdata);
        if($ret['status']!=1) $this->ajaxReturn($ret);
        $post_list=$this->StrToparamArray($postdata['list']);
        if(empty($post_list)){$return['msg']="请添加报损商品";$this->ajaxReturn($return);}
        $now_time=NOW_TIME;
        $post_info=html_entity_decode($postdata['info']);
        parse_str($post_info,$info);
        $shop_id=intval($postdata['shop_id']);
        $shop_account_id=intval($postdata['shop_id']);
        $bad_all_money=floatval($info['all_price']);
        $bad_all_num=floatval($info['all_count']);
        $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,//审核状态
        );
        if($is_open_audit==0){
            $data['audit_time']=NOW_TIME;
            $data['audit_remarks']='自动审核';
        }
        $id=M('StocktakingInfo')->add($data);
        if($id<=0){$return['msg']="添加报损失败";$this->ajaxReturn($return);}
        $list=array();
        foreach($post_list as $k=>$v){
            $supplier_id=empty($v['suppliers_id'])?0:$v['suppliers_id'];
            $list_info=array(
                'stocktaking_id'=>$id,
                'goods_id'=>$v['goods_id'],
                'cate_id'=>$v['cat_id']?$v['cat_id']:0,
                'supplier_id'=>$supplier_id,
                'shop_id'=>$shop_id,
                'goods_name'=>$v['goods_name'],
                'goods_sn'=>$v['goods_sn'],
                'goods_attr_sn'=>empty($v['attr_key'])?0:$v['attr_key'],
                'remark'=>$remarks,
                'info_type'=>1,
                'bad_money'=>$v['realprice'],
                'bad_num'=>$v['number'],
                'status'=>empty($is_open_audit)?1:0,//审核状态
            );
            if($v['goods_attr_sn']) $list_info['goods_sn']=$v['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($v['attr_key']) ? '' : $v['attr_key'];
                change_stock_log($shop_id, 0, $stock, $list_info['goods_id'], $list_info['bad_num'], 1, '商品报损', 8, $attr_key);
            }$res=M('StocktakingGoods')->add($list_info);
        }
        //$res=M('StocktakingGoods')->addAll($list);
        if($res==false){$return['msg']="添加报损商品失败";$this->ajaxReturn($return);}
        $return['status']=1;
        $this->ajaxReturn($return);
    }
    /**
     * 报损打印
     */
    public function bad_print_info(){
        $return=array('status'=>1,'msg'=>'');
        $getdata=I('post.');
        $auth_code='badgoods_list_print';
        $ret=D("Pad/ShopsRoleAuth")->check_auth_code($auth_code,$getdata);
        if($ret['status']!=1) $this->ajaxReturn($ret);
        $result = D('Common/InvoicingOrder')->bad_print_info($getdata);
        if($result['status']==0){$return['status']=3; $return['msg']=$result['msg']; $this->ajaxReturn($return);}
        $this->ajaxReturn($result);
    }
    /**报损结束**/
    public function stock_confirm_order(){
        $return=array('status'=>3,'msg'=>'');
        $postdata=I('post.');
        if($postdata['type'] == 0){$auth_code='stocktaking_del';}
        elseif($postdata['type'] == 1){$auth_code='badgoods_list_cancel';}
        $ret=D("Pad/ShopsRoleAuth")->check_auth_code($auth_code,$postdata);
        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);}
        $result=D('Pad/InvoicingOrder')->stock_confirm_order($postdata);
        if($result['status']==0) {$return['msg']=$result['msg']; $this->ajaxReturn($return);}
        else $this->ajaxReturn($result);
    }
    /**盘点开始**/
    //盘点记录
    public function stocktaking_list(){
        $return=array('status'=>3,'msg'=>'');
        $getdata=I('get.');
        $auth_code='stocktaking_list';
        $ret=D("Pad/ShopsRoleAuth")->check_auth_code($auth_code,$getdata);
        if($ret['status']!=1) {$this->ajaxReturn($ret);}
        $sid=intval($getdata['sid']);
        $shop_id=intval($getdata['shop_id']);
        if(empty($shop_id)){$return['msg']='参数错误';$this->ajaxReturn($return);}
        $map=array('type'=>3,'type_id'=>$shop_id,'info_type'=>0);
        if($getdata['data_from']){$map['addtime'][] = array('egt',strtotime($getdata['data_from']));}
        if($getdata['data_to']){$map['addtime'][] = array('elt',strtotime($getdata['data_to']));}
        $is_gain=$getdata['is_gain'];//是否盈利1盘盈2盘亏
        if($is_gain==1){$map['profit_sum']=array('neq',0);}
        elseif($is_gain==2){$map['loss_sum']=array('neq',0);}
        $field='id,all_stock,reality_sum,profit_sum,loss_sum,addtime';
        $list=page_list('StocktakingInfo',$map,'addtime desc',$field);
        if(empty($list['list'])){$return=array('status'=>2,'msg'=>'没有更多数据了');$this->ajaxReturn($return);}
        $data=$list['list'];
        foreach($list['list'] as $k=>$v){
            $data[$k]['add_time']=time_format($v['addtime']);
            $data[$k]['all_stock']=floatval($v['all_stock']);
            $data[$k]['reality_sum']=floatval($v['reality_sum']);
            $data[$k]['profit_sum']=floatval($v['profit_sum']);
            $data[$k]['loss_sum']=floatval($v['loss_sum']);
        }
        $return=array('status'=>1,'data'=>$data,'stock_show'=>C("IS_OPEN_STOCKTAKING_SHOW"));
        $this->ajaxReturn($return);
    }
    //盘点记录商品
    public function stocktaking_info(){
        $return=array('status'=>3,'msg'=>'');
        $getdata=I('get.');
        $id=intval($getdata['id']);
        if(empty($id)){$return['msg']='参数错误';$this->ajaxReturn($return);}
        $map=array('id'=>$id,'info_type'=>0);
        $field='all_stock,reality_sum,profit_sum,loss_sum,remarks,status,audit_name,audit_time,audit_remarks,profit_all_money,loss_all_money,addtime';
        $info=M('StocktakingInfo')->where($map)->field($field)->find();
        if(empty($info)){$return['msg']='无盘点记录';$this->ajaxReturn($return);}
        $info['audit_time']=empty($info['audit_time'])?'':time_format($info['audit_time']);
        $info['addtime']=empty($info['addtime'])?'':time_format($info['addtime']);
        $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,status,bad_money';
        $list=M('StocktakingGoods')->where($map)->field($field)->select();
        if(empty($list)){$return=array('status'=>2,'msg'=>'暂无记录');$this->ajaxReturn($return);}
        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']);
            $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']);
        }
        $return=array('status'=>1,'data'=>array('info'=>$info,'list'=>$list),'stock_show'=>C("IS_OPEN_STOCKTAKING_SHOW"));
        $this->ajaxReturn($return);
    }
    //添加盘点开始
    public function stocktaking_add_before()
    {
        $return = array('status' => 1);
        $cate_list = D('InvoicingOrder')->getcateTree();
        $return['cate_list'] = $cate_list;
        $getdata = I('get.');
        $shop_id = $getdata['shop_id'];
        if (empty($shop_id)) {
            $return['data'] = 0;
            $this->ajaxReturn($return);
        }
        $map = array('s.shop_id' => $shop_id);
        $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();
        $return['data'] = $count;
        $return['stock_show'] = C("IS_OPEN_STOCKTAKING_SHOW");
        $this->ajaxReturn($return);
    }
    //添加盘点
    public function stocktaking_add(){
        $return=array('status'=>3,'');
        $is_open_audit=C('IS_OPEN_STOCKTAKING_AUDIT');
        $postdata=I('post.');
        $auth_code='stocktaking_add';
        $ret=D("Pad/ShopsRoleAuth")->check_auth_code($auth_code,$postdata);
        if($ret['status']!=1) {$this->ajaxReturn($ret);}
        $post_list=$this->StrToparamArray($postdata['list']);
        if(empty($post_list)){$return['msg']="请添加盘点商品";$this->ajaxReturn($return);}
        $now_time=NOW_TIME;
        $post_info=html_entity_decode($postdata['info']);
        parse_str($post_info,$info);
        $shop_id=intval($postdata['shop_id']);
        $shop_account_id=intval($postdata['shop_id']);
        $remarks=empty($postdata['remarks'])?'无':$postdata['remarks'];

        if($postdata['is_zero'] == 1){
            $where = $map = $ids = array();
            foreach($post_list as $k=>$v){
                $map=array('goods_id'=>$v['goods_id'],'goods_stock'=>empty($v['attr_key'])?0:$v['attr_key'],'shop_id'=>$shop_id);
                $ids[] = M("ShopsGoodsStock")->where($map)->getField("id");
            }
            $where['id'] = array('not in',$ids);
            $where['shop_id'] = $shop_id;
            $shop_goods = M("ShopsGoodsStock")->where($where)->field("goods_id,goods_number,goods_stock,suppliers_id,goods_stock")->select();
            $all_stock = $profit_sum = $loss_sum = $sum_profit_price = $sum_loss_price = 0;
            foreach ($shop_goods as $key => $value) {
                $all_stock = round($all_stock + $value['goods_number'],3);
                $shop_goods[$key]['profit_num'] = $shop_goods[$key]['loss_num'] = 0;
                $goods_map = array();
                $goods_map['id'] = $value['goods_id'];
                $sto_goods = M("Goods")->where($goods_map)->field("supply_price,cat_id,goods_name,goods_sn")->find();
                $map_sg=array();
                $map_sg['goods_id']=$value['goods_id'];
                $map_sg['shop_id']=$shop_id;
                $supply_price=M('ShopsGoods')->where($map_sg)->getField('avg_price');
                $supply_price = $supply_price>0?$supply_price:$sto_goods['supply_price'];
                $shop_goods[$key]['all_supply_price'] = $supply_price*abs($value['goods_number']);
                if($value['goods_number'] > 0){
                    $loss_sum = round($loss_sum + $value['goods_number'],3);
                    $shop_goods[$key]['loss_num'] = $loss_sum;
                    $sum_loss_price = round($sum_loss_price + $shop_goods[$key]['all_supply_price'],2);
                }else{
                    $profit_sum = round($profit_sum + $value['goods_number'],3);
                    $shop_goods[$key]['profit_num'] = $profit_sum;
                    $sum_profit_price = round($sum_profit_price + $shop_goods[$key]['all_supply_price'],2);
                }
                $shop_goods[$key]['cat_id'] = $sto_goods['cat_id'];
                $shop_goods[$key]['goods_name'] = $sto_goods['goods_name'];
                $shop_goods[$key]['goods_sn'] = $sto_goods['goods_sn'];

                $map=array();
                $map['goods_id']=$value['goods_id'];
                if($value['goods_stock']==0) $map['attr_key']='';
                else $map['attr_key']=$value['goods_stock'];
                $goods_attr=M('GoodsAttrStock')->where($map)->field('goods_attr_sn,attr_price')->find();
                if($goods_attr['goods_attr_sn'])$shop_goods[$key]['goods_attr_sn']=$goods_attr['goods_attr_sn'];
            }unset($key,$value);
            $info['all_stock'] = floatval($all_stock)+floatval($info['all_stock']);
            $info['reality_sum'] = count($shop_goods)+$info['reality_sum'];
            $info['profit_sum'] = floatval($info['profit_sum'])+floatval($profit_sum);
            $info['loss_sum'] = floatval($info['loss_sum'])+floatval($loss_sum);
            $info['sum_profit_price'] = floatval($info['sum_profit_price'])+floatval($sum_profit_price);
            $info['sum_loss_price'] = floatval($info['sum_loss_price'])+floatval($sum_loss_price);
        }


        $data=array(
            'all_stock'=>$info['all_stock'],
            'reality_sum'=>$info['reality_sum'],
            'profit_sum'=>$info['profit_sum'],
            'loss_sum'=>$info['loss_sum'],
            'profit_all_money'=>$info['sum_profit_price'],
            'loss_all_money'=>$info['sum_loss_price'],
            '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,//审核状态
        );
        if($is_open_audit==0){
            $data['audit_time']=NOW_TIME;
            $data['audit_remarks']='自动审核';
        }
        $id=M('StocktakingInfo')->add($data);
        if($id<=0){$return['msg']="添加盘点失败";$this->ajaxReturn($return);}
        $list=array();
        foreach($post_list as $k=>$v){
            $supplier_id=empty($v['suppliers_id'])?0:$v['suppliers_id'];
            $list_info=array(
                'stocktaking_id'=>$id,
                'goods_id'=>$v['goods_id'],
                'cate_id'=>$v['cat_id']?$v['cat_id']:0,
                'supplier_id'=>$supplier_id,
                'shop_id'=>$shop_id,
                'goods_name'=>$v['goods_name'],
                'goods_sn'=>$v['goods_sn'],
                'goods_attr_sn'=>empty($v['attr_key'])?0:$v['attr_key'],
                'stock'=>$v['stock'],
                'reality'=>$v['number'],
                'profit_num'=>$v['profit_num'],
                'loss_num'=>$v['loss_num'],
                'bad_money'=>$v['all_supply_price'],
                'remark'=>$remarks,
                'info_type'=>0,
                'status'=>empty($is_open_audit)?1:0,//审核状态
            );
            if($v['goods_attr_sn']) $list_info['goods_sn']=$v['goods_attr_sn'];
            $list[]=$list_info;
            //如果库存有变动，则修改库存并记录日志
            if($list_info['stock']!=$list_info['reality'] && $list_info['status']==1 && $is_open_audit==0){
                $map=array();
                $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($v['attr_key'])?'':$v['attr_key'];
                change_stock_log($shop_id,0,$list_info['stock'],$list_info['goods_id'],$change_number,$change_type,'库存盘点修正',7,$attr_key);
            }
            $res=M('StocktakingGoods')->add($list_info);
        }
        if($postdata['is_zero'] == 1){
            foreach ($shop_goods as $key => $value) {
                $supplier_id=empty($value['suppliers_id'])?0:$value['suppliers_id'];
                $list_info=array(
                    'stocktaking_id'=>$id,
                    'goods_id'=>$value['goods_id'],
                    'cate_id'=>$value['cat_id']?$value['cat_id']:0,
                    'supplier_id'=>$supplier_id,
                    'shop_id'=>$shop_id,
                    'goods_name'=>$value['goods_name'],
                    'goods_sn'=>$value['goods_sn'],
                    'goods_attr_sn'=>empty($value['goods_stock'])?0:$value['goods_stock'],
                    'stock'=>$value['goods_number'],
                    'reality'=>0,
                    'profit_num'=>$value['profit_num'],
                    'loss_num'=>$value['loss_num'],
                    'bad_money'=>$value['all_supply_price'],
                    'remark'=>$remarks,
                    'info_type'=>0,
                    'status'=>empty($is_open_audit)?1:0,//审核状态
                );
                if($v['goods_attr_sn']) $list_info['goods_sn']=$value['goods_attr_sn'];
                $list[]=$list_info;
                //如果库存有变动，则修改库存并记录日志
                if($list_info['stock']!=$list_info['reality'] && $list_info['status']==1 && $is_open_audit==0){
                    $map=array();
                    $map=array('goods_id'=>$list_info['goods_id'],'goods_stock'=>empty($list_info['goods_attr_sn'])?0:$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($value['goods_stock'])?'':$value['goods_stock'];
                    change_stock_log($shop_id,0,$list_info['stock'],$list_info['goods_id'],$change_number,$change_type,'库存盘点修正',7,$attr_key);
                }
                $res=M('StocktakingGoods')->add($list_info);
            }unset($key,$value);
        }
        // $res=M('StocktakingGoods')->addAll($list);
        if($res==false){$return['msg']="添加盘点商品失败";$this->ajaxReturn($return);}
        $return['status']=1;
        $this->ajaxReturn($return);
    }
    /**盘点结束**/
    /**查询别店库存开始**/
    public function other_goods(){
        $return=array('status'=>1,'msg'=>'');
        $postdata=I('post.');
        $auth_code='othergoods_list_other';
        $ret=D("Pad/ShopsRoleAuth")->check_auth_code($auth_code,$postdata);
        if($ret['status']!=1) $this->ajaxReturn($ret);
        $shop_id=intval($postdata['shop_id']);
        $goodsids=html_entity_decode($postdata['goods_ids']);
        parse_str($goodsids,$goods_ids);
        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['msg']='该门店下没有所查商品的部分商品';
        }
        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'].'-';
            }
			$discount_price=D('Pad/InvoicingOrder')->get_min_price($shop_id,$v['goods_id'],$v['goods_stock']);
			$realprice = 0;
			if($discount_price['price_type']==1){
				$realprice = $discount_price['goods_price'];
			}
			$goods_list[$k]['realprice']=$realprice;
        }
        $return['data']=$goods_list;
        $this->ajaxReturn($return);
    }
	/**库存预警开始**/
    public function warning(){
		$return = array();
        $postdata=I('param.');
        $auth_code='othergoods_list';
        $ret=D("Pad/ShopsRoleAuth")->check_auth_code($auth_code,$postdata);
        if($ret['status']!=1) $this->ajaxReturn($ret);
        $result = D('Pad/InvoicingOrder')->warning($postdata);
		if($result['status']){$return['status']=1; $return = $result;}
        else{$return=array('status'=>2,'msg'=>'暂无数据');}
        $this->ajaxReturn($return);
    }
    /**库存预警结束**/

    /**
     * 提交订单
     * jxr 2018.10.26
     */
    public function add_order(){
        $return=array('status'=>1,'msg'=>'');
        $postdata=I('post.');
        if(empty($postdata['shop_id'])){$return['status']=3;$return['msg']='参数错误'; $this->ajaxReturn($return);}
        /*验证权限开始*/
        $auth_code='ordergoods_list_confirm';
        $res=D('Pad/ShopsRoleAuth')->check_auth_code($auth_code,$postdata);
        if($res['status']!=1){$this->ajaxReturn($res);}
        /*验证权限结束*/
        $postdata['shop_id_in']=$postdata['shop_id'];
        if(!empty($postdata['shop_id_out'])) $postdata['shop_id_out']=$postdata['shop_id_out'];
        $postdata['pay_type']=explode(',',strtr($postdata['pay_type'],array('['=>'',']'=>'')));
        if($postdata['cart_list']) $postdata['cart_list']=$this->StrToparamArray($postdata['cart_list']);
        $result=D('Pad/InvoicingOrder')->add_order($postdata);
        // $return['status']=3;
        // $return['test_data']=$result;
        // $this->ajaxReturn($return);
        if($result['status']==1){

            $this->ajaxReturn($result);
        }else{
            $return['status']=3;
            if($result['msg']) $return['msg']=$result['msg'];
            else $return['msg']='支付失败';
            $this->ajaxReturn($return);
        }
    }

    /**
     * 店铺上传支付凭证
     */
    public function save_pay_img(){
        $return=array('status'=>1,'msg'=>'');
        $postdata=I('post.');
        if(empty($postdata['order_id'])){$return['status']=3;$return['msg']='参数错误'; $this->ajaxReturn($return);}
        if(intval($postdata['order_id'])){
            $map=$savedata=array();
            $map['id']=intval($postdata['order_id']);
            $savedata['pay_img']=$postdata['pay_img'];
            $result=M('InvoicingOrder')->where($map)->save($savedata);
        }
        if($result==true){
            $return['msg']='上传成功';
        }else{
            $return['status']=3;
            $return['msg']='上传失败';
        }
        $this->ajaxReturn($return);
    }

    //jxr end
    //实时监测是否付款成功双乾支付
    public function check_paysuccess(){
        $return=array('status'=>1,'msg'=>'');
        $sid=I('sid');
        $token=I('token');
        $order_id=I('order_id');
        $result=D('Pad/InvoicingOrder')->check_paysuccess($order_id);
        if($result['status']==0){$return['msg']=$result['msg']; $return['status']=3; $this->ajaxReturn($return);}
        $this->ajaxReturn($result);
    }
    /**
     * 店铺实时信息
     */
    public function get_shopmoney(){
        $return=array('status'=>1,'msg'=>'');
        $postdata=I('post.');
        if(empty($postdata['shop_id'])){$return['status']=3;$return['msg']='参数错误'; $this->ajaxReturn($return);}
        if(intval($postdata['shop_id'])){
            $map=array();
            $map['id']=intval($postdata['shop_id']);
            $map['status']=1;
            $total_revenues=M('Shops')->where($map)->getField('total_revenues');
        }
        if(format_decimal($total_revenues)){
            $return['data']=$total_revenues;
        }else{
            $return['status']=3;
            $return['msg']='参数错误';
        }
        $this->ajaxReturn($return);
    }
    //获取退货列表
    //获取退货列表
    public function get_return_order(){
        $return = array('status'=>3,'msg'=>'');
        $postdata=I('param.');
        $auth_code='returngoods_lists';
        $ret=D("Pad/ShopsRoleAuth")->check_auth_code($auth_code,$postdata);
        if($ret['status']!=1) $this->ajaxReturn($ret);
        $result = D('Pad/InvoicingOrder')->get_return_order($postdata);
        if($result['status']==0){$return['msg']=$result['msg'];$this->ajaxReturn($return);}
        if($result['status']==2)$this->ajaxReturn($result);
        $return['status']=1;
        $return['data']['list']=$result['list'];
        $this->ajaxReturn($return);
    }
    //获取退货详情
    public function get_return_goods(){
        $return = array('status'=>3,'msg'=>'');
        $postdata=I('param.');
        $result = D('Pad/InvoicingOrder')->get_return_goods($postdata);
        if($result['status']==0) {$return['msg']=$result['msg']; $this->ajaxReturn($return);}
        $this->ajaxReturn($result);
    }
}
