<?php
/**进销存
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaol <xiaol@sina.cn>
 */
namespace Pad\Model;
use Think\Model;
class InvoicingOrderModel extends Model
{
    /**得到商品分类节点树**/
    public function getcateTree($pid=0){
        $GoodsCategory = getcache('PurchaseCategory');
        $Tree = new \Common\Vendor\Tree();
        $select_categorys = '';
        $treemini = $Tree->treemini($GoodsCategory);
        $select_categorys .= $Tree->treeminioption($treemini, $pid);
        return $select_categorys;
    }
	public function warning($postdata){
		$return=array('status'=>1,'msg'=>'');
		
		if(empty($postdata['time'])) $postdata['time'] = NOW_TIME;
		$cachename = 'warn_goods_list'.$postdata['time'];
		$cachedata = S($cachename);
		
		if(empty($cachedata)){
			$map=array();$list = array();
			$shop_id=$postdata['shop_id'];
			if(!empty($shop_id)){$map['a.shop_id']=$shop_id;}
			$map['_string']='a.goods_number > g.limit_count or a.goods_number < g.lower_count';
			$map['g.limit_count']=array('neq',0);
			$map['g.lower_count']=array('neq',0);
			$map['g.is_delete']=0;

			$field='a.*,g.limit_count,g.lower_count,g.goods_name,g.supply_price';
			$join='LEFT JOIN __GOODS__ g ON g.id=a.goods_id';
			$list=M('ShopsGoodsStock')->alias('a')->where($map)->join($join)->field($field)->select();
			if($list){
			    $datas=array();
				foreach($list as $key=>$val){
				    $data=$val;
					if($val['goods_stock']){
					    $index=$val['goods_id'].'-'.$val['goods_stock'];
						$data['name']=$this->goods_attrname($val['goods_stock']);
						$map=array();
						$map['goods_id']=$val['goods_id'];
						$map['attr_key']=$val['goods_stock'];
						$data['goods_attr_sn']=M("GoodsAttrStock")->where($map)->cache(true)->getField('goods_attr_sn');
					}else{
					    $index=$val['goods_id'].'-';
						$map=array();
						$map['goods_id']=$val['goods_id'];
						$data['goods_sn']=M("ShopsGoods")->where($map)->cache(true)->getField('goods_sn');
					}
					$discount_price=$this->get_min_price($shop_id,$val['goods_id'],$val['goods_stock']);
					$realprice = 0;
					if($discount_price['price_type']==1){
						$realprice = $discount_price['goods_price'];
					}
					$data['supply_price']=$realprice;//实际价格
					$map=array();
					$map['id']=$val['shop_id'];
					$data['shop_name']=M("Shops")->where($map)->cache(true)->getField('name');
					$data['stock']=floatval($val['goods_number']);
					$data['is_red']=1;
					$goods_ids[]=$val['goods_id'];
                    $datas[$index]=$data;
				}
			}
            if($datas)S($cachename,$datas);
			$return['goods_ids']=$goods_ids;
			$data_list = $datas;
		}else{
			$data_list = $cachedata;
		}
		if($data_list){
			$returndata=D('App/InvoicingOrder')->arr_page($data_list,$postdata['pagefrom'],8);
			$return['data']=$returndata['attr'];
			$return['pagefrom']=intval($returndata['pagefrom']);
			$return['time']=$postdata['time'];
		}else{
			$return['status'] = 0;
		}
		return $return;
	}
	/**
     * 根据属性id获取属性名称
     * @param $attr_ids
     * @return string
     */
    public function goods_attrname($attr_ids){
        $where['ga.id'] = array("in", explode("_", $attr_ids));
        $where['g.type'] = "checkbox";
        $list = M('GoodsAttribute')->alias('g')->where($where)->JOIN('LEFT JOIN __GOODS_ATTR__ ga ON ga.attr_id=g.id')->field('ga.attr_value,g.name,g.options')->select();
        $attrname = '';
        foreach ($list as $key => $val) {
            if ($val['options']) {
                $formatarr = strtoarray($val['options']);
                $attrname .= $formatarr[$val['attr_value']];
            }
        }
        return $attrname;
    }

    /**
     * 格式化从App和pad提交过来的数据
     * @param $postdata
     */
    public function sub_order_stock($postdata){
        $return=array('status'=>1,'msg'=>'');
        if(empty($postdata['shop_id_in']) && empty($postdata['shop_id_out'])){$return['status']=0;$return['msg']='参数错误'; return $return;}
        $i =0;
        $postdata['infos']=$this->StrToparamArray($postdata['infos']);
        foreach($postdata['infos'] as $k => $v){
            $infos['goods_id'][$i]=$v['id'];
            $infos['goods_name'][$i]=$v['goods_name'];
            if($v['goods_attr_sn']) $infos['goods_sn'][$i]=$v['goods_attr_sn'];
            else $infos['goods_sn'][$i]=$v['goods_sn'];
            $infos['goods_attr_sn'][$i]=$v['attr_key'];
            $infos['supply_price'][$i]=$v['supply_price'];
            $infos['supplier_id'][$i]=$v['suppliers_id'];
            $infos['storage_id'][$i]=1;
            $infos['all_money'][$i]=$v['all_money'];
            $infos['freight_num'][$i]=empty($v['freight_num'])?0:$v['freight_num'];
            if($postdata['type']==1){
                $infos['fact_num'][$i]=$v['freight_num'];
            }elseif($postdata['type']==4){
                $infos['fact_num'][$i]=empty($v['fact_num'])?$v['freight_num']:$v['fact_num'];
            }else{
                $infos['request_num'][$i]=empty($v['request_num'])?0:$v['request_num'];
                $infos['fact_num'][$i]=empty($v['fact_num'])?0:$v['fact_num'];
            }
            $i++;
        }
        $data['shop_id_in']=$postdata['shop_id_in'];
        $data['shop_id_out']=empty($postdata['shop_id_out'])?0:$postdata['shop_id_out'];
        $data['mtype']=empty($postdata['mtype'])?0:$postdata['mtype'];
        $data['status']=empty($postdata['status'])?0:$postdata['status'];
        $data['goods_status']=empty($postdata['goods_status'])?0:$postdata['goods_status'];
        $data['type']=empty($postdata['type'])?0:$postdata['type'];
        $data['all_pre_money']=empty($postdata['all_pre_money'])?0:$postdata['all_pre_money'];
        $data['remarks']=$postdata['remarks'];
        $data['best_time']=$postdata['best_time'];
        $data['cashier_id']=$postdata['cashier_id'];
        $data['infos']=$infos;
        $postdata['supplier_money']=$this->StrToparamArray($postdata['supplier_money']);
        if(!empty($postdata['supplier_money'])){
            foreach($postdata['supplier_money'] as $k => $vo){
                $data['pre_money'][$vo['supplier_id']]=$vo['money'];
            }
        }
        $return['data']=$data;
        return $return;
    }
    public function stock_confirm_order($postdata){
        $return=array('status'=>0,'msg'=>'');
        $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']='订单信息错误'; return $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'];
            M('StocktakingGoods')->where($map)->save($savedata);
            $return['msg']='操作成功';
            $return['status']=1;
            return $return;
        }else{
            $return['msg']='操作失败';
            return $return;
        }
    }

    /**
     * 格式化App和pad传过来的商品数据
     * @param string $str
     * @return array
     */
    public function StrToparamArray($str=''){
        $str=html_entity_decode($str);
        if(is_string($str)&&!empty($str)){
            $data = array();
            $arr = explode('^',$str);
            foreach ($arr as $val) {
                if(empty($val))continue;
                $d = array();
                $d = explode('/=/',$val);
                if(is_string($d[1])){
                    $tobj = array();
                    $tarr = explode('@',$d[1]);
                    foreach ($tarr as $v) {
                        if(empty($v))continue;
                        $dt = explode('___',$v);
                        $tobj[$dt[0]] = $dt[1];
                    }
                    $data[$d[0]] = $tobj;
                }else{
                    $data[$d[0]] = $d[1];
                }
            }
            return $data;
        }
        return array();
    }
    //获取退款数据
    public function get_return_order($postdata){
        $return=array('status'=>0,'msg'=>'');
        if(empty($postdata['shop_id'])){$return['msg']='参数错误'; return $return;}
        $map=array();
        $map['shop_id']=$postdata['shop_id'];
        $all_return_order=page_list('RefundOrder',$map,'addtime desc',true,10);
        if(empty($all_return_order['list'])){$return['status']=2;$return['msg']='没有更多的数据了';return $return;}       
        foreach($all_return_order['list'] as $k => $v){
            $all_return_order['list'][$k]['addtime']=time_format($v['addtime']);
            $all_return_order['list'][$k]['goods_info']['number']=0;
            if($v['order_id'])$all_return_order['list'][$k]['order_sn']=idtoname($v['order_id'],'OrderInfo','order_sn','id');
            if($v['order_type']==13) {
                $all_return_order['list'][$k]['tag']='线下';
            }
            if($v['order_type']==14) {$all_return_order['list'][$k]['tag']='线上';}
            $map=array();
            $map['_string']= "(rorder_id > 0 AND rorder_id =".$v['id'].") OR (rorder_id = 0 AND order_id > 0  AND order_id =".$v['order_id'].")";
            //$map['type'] = $v['type'];
            $goods_info=M('ReturnGoods')->where($map)->field('goods_info')->select();
            foreach($goods_info as $key => $val) {
                $attr = array();
                $attr = unserialize($val['goods_info']);
                $all_return_order['list'][$k]['number'] += floatval($attr['number']);
                $all_return_order['list'][$k]['goods_info']['number'] += floatval($attr['number']);
            }
        }
        $return['status']=1;
        $return['list']=$all_return_order['list'];
        return $return;
    }
    //获取退货数据
    public function get_return_goods($postdata){
        $return=array('status'=>0,'msg'=>'');
        if(empty($postdata['shop_id'])) {$return['msg']='参数错误'; return $return;}
        $map=array();
        $map['shop_id']=$postdata['shop_id'];
        $map['id']=$postdata['order_id'];
        $order_info['infos']=M('RefundOrder')->where($map)->field(true)->find();
        $order_info['infos']['real_money']=format_decimal($order_info['infos']['refund_money']+$order_info['infos']['refund_scores']+$order_info['infos']['refund_web']+$order_info['infos']['refund_cash']);
        if(empty($order_info['infos'])){$return['msg']='退货单信息错误'; return $return;}
        if($order_info['infos']['uid']){
            $username=show_user_name($order_info['infos']['uid']);
            $shop_id=$postdata['shop_id'];
            if($shop_id && $username && strlen($username)==11){
                $is_hide_phone=idtoname($shop_id,'Shops','is_hide_phone');
                if($is_hide_phone==1){$username=str_cutmobile($username);}
            }
            $order_info['infos']['username']=$username;
        }
        if($order_info['infos']['order_type']==13) {
            $order_info['infos']['tui_type']='线下';$order_info['infos']['tag']='线下';
            if($order_info['infos']['type']==0) $order_info['infos']['tui_source']='线下直接退';
            else $order_info['infos']['tui_source']='线下订单退';
        }
        if($order_info['infos']['order_type']==14) {
            $order_info['infos']['tui_type']='线上';$order_info['infos']['tag']='线上';
            $order_info['infos']['tui_source']='线上订单退';
        }
        if($order_info['infos']['order_id'] && $postdata['type']!=0)$order_info['infos']['order_sn']=idtoname($order_info['infos']['order_id'],'OrderInfo','order_sn','id');
        $order_info['infos']['add_time'] =$order_info['infos']['addtime'] = time_format($order_info['infos']['addtime']);
        $order_info['infos']['update_time'] =$order_info['infos']['update_time']?time_format($order_info['infos']['update_time']):'';
        $map=array();
        /*if($postdata['type']==0) $map['rorder_id'] = $order_info['infos']['id'];
        else $map['order_id'] = $order_info['infos']['order_id'];*/
        $map['_string']= "(rorder_id > 0 AND rorder_id =".$order_info['infos']['id'].") OR (rorder_id = 0 AND order_id > 0 AND order_id =".$order_info['infos']['order_id'].")";
        $order_goods=M('ReturnGoods')->where($map)->field(true)->select();
        $goods_list=array();
        if($order_goods){
            foreach($order_goods as $k => $v){
                $attr=$goods_info=$goods_attr=array();
                $attr=unserialize($v['goods_info']);
                $attr_name=attr_key2name($attr['goods_attr'],$attr['goods_id']);
                $goods_list[$k]=$v;
                $goods_list[$k]['goods_number']=floatval($attr['number']);//退款数量
                if($order_info['infos']['type']==0) {//线下直接退
                    //有属性的商品价格
                    if ($attr['goods_attr']) {
                        $map = array();
                        $map['goods_id'] = $attr['goods_id'];
                        $map['attr_key'] = $attr['goods_attr'];
                        $goods_attr=M('GoodsAttrStock')->where($map)->field('attr_price,goods_attr_sn')->find();
                        $goods_list[$k]['goods_price'] = $goods_attr['attr_price'];
                        $goods_list[$k]['goods_sn'] = $goods_attr['goods_attr_sn'];
                    }
                    $map = array();
                    $map['id'] = $attr['goods_id'];
                    $goods_info=M('Goods')->where($map)->field('goods_name,shop_price,goods_sn')->find();
                    if (empty($goods_list[$k]['goods_price'])) {
                        $goods_list[$k]['goods_price'] = $goods_info['shop_price'];
                    }
                    if(empty($goods_list[$k]['goods_sn'])) $goods_list[$k]['goods_sn']=$goods_info['goods_sn'];
                    $goods_list[$k]['goods_name']=$goods_info['goods_name'];
                }else{//线上、线下订单退
                    $map=array();
                    $map['id']=$v['org_id'];
                    $map['order_id']=$order_info['infos']['order_id'];
                    $goods_info=M('OrderGoods')->where($map)->field('goods_name,goods_sn,attr_price,goods_price')->find();
                    $goods_list[$k]['goods_sn']=$goods_info['goods_sn'];
                    $goods_list[$k]['goods_name']=$goods_info['goods_name'];
                    $goods_list[$k]['goods_price']=$goods_info['goods_price'];
                    $map=array('id'=>$order_info['infos']['order_id']);
                    $order_sn=M('OrderInfo')->where($map)->getField('order_sn');
                }
                $goods_list[$k]['goods_name']=str_replace("•","·",$goods_list[$k]['goods_name']);
                $goods_list[$k]['goods_name']=$goods_list[$k]['goods_name'].$attr_name;
                $goods_list[$k]['all_price']=format_decimal($attr['number']*$goods_list[$k]['goods_price']);
                $order_info['infos']['total_num']+= floatval($goods_list[$k]['goods_number']);
                if(empty($order_info['infos']['reason'])) $order_info['infos']['reason']=$v['reason'];
            }
        }
        $order_info['goods_list']=$goods_list;
        $return['status']=1;
        $return['data']=$order_info;
        return $return;
    }

    //jxr start
    /**
     * 添加订单
     * jxr 2018.10.26
     */
    public function add_order($postdata){
        $return=array('status'=>0,'msg'=>'');
        if(empty($postdata['shop_id'])){$return['status']=3;$return['msg']='参数错误';}
        //判断支付方式
        $pay_type=$postdata['pay_type'];
        if(empty($pay_type)){$return['msg']='支付方式错误';return $return;}
        $online_type=intval(idtoname(intval($postdata['shop_id']),'Shops','online_type','id',false));
        if(empty($postdata['cart_list']) && floatval($postdata['total_price'])<=0){ $return['msg']='请选择商品或输入金额';return $return;}
        $shop_id_in=intval($postdata['shop_id_in']);
        $shop_id_out=intval($postdata['shop_id_out']);
        if($shop_id_in<=0 && $shop_id_out<=0){$return['msg']='请选择门店';return $return;}
        $now_time=NOW_TIME;
        $type=empty($postdata['type'])?0:intval($postdata['type']);//货单类型（0门店订货.1进货.2普通出库.3门店退货.4门店调货-出）
        $status=empty($postdata['status'])?0:intval($postdata['status']);//状态（0待审核.1配货中.2待入库.3已完成4.已拒绝5已作废.）
        $mtype=empty($postdata['mtype'])?0:intval($postdata['mtype']);//操作人类型（0后台1门店）
        $cashier_id=empty($postdata['cashier_id'])?0:intval($postdata['cashier_id']);//如果是门店操作需要记录操作员id
        $best_time=empty($postdata['best_time'])?0:strtotime($postdata['best_time']);//期望发货时间
        $i=0;
        foreach($postdata['cart_list'] as $k => $v){
            $infos['goods_id'][$i]=$v['id'];
            if($v['goods_attr_sn']) $infos['goods_sn'][$i]=$v['goods_attr_sn'];
            else $infos['goods_sn'][$i]=$v['goods_sn'];
            $infos['goods_attr_sn'][$i]=$v['attr_key'];
            $infos['freight_num'][$i]=empty($v['freight_num'])?0:$v['freight_num'];
            if($postdata['type']==1){
                $infos['fact_num'][$i]=$v['freight_num'];
            }elseif($postdata['type']==4){
                $infos['fact_num'][$i]=empty($v['fact_num'])?$v['freight_num']:$v['fact_num'];
            }else{
                $infos['request_num'][$i]=empty($v['request_num'])?0:$v['request_num'];
                $infos['fact_num'][$i]=empty($v['fact_num'])?0:$v['fact_num'];
            }
            $i++;
        }
        $all_count=0;
        $request_num=empty($infos['request_num'])?$infos['freight_num']:$infos['request_num'];//请求量
        foreach($request_num as $k => $v){$all_count+=$v;}//计算订单总请求量
        
        if($type==2 || $type==3 || $type==4){//涉及门店出货的需要验证库存
            foreach($infos['goods_id'] as $k => $v){
                $num = D('Common/Cart')->shopgoodsstock($v,$postdata['shop_id_out'],$infos['goods_attr_sn'][$k]);
                if($num['goods_number'] <= 0 || $num['goods_number'] < $infos['freight_num'][$k]){
                    $return['msg'] = '库存不足！';
                    return $return;
                }
            }
        }
        $shop_id=intval($postdata['shop_id']);
        if($shop_id){
            $map=array();
            $map['id']=$shop_id;
            $map['status']=1;
            $total_revenues=M('Shops')->where($map)->getField('total_revenues');
        }
        $check_usermoney=false;//是否检查店铺账户余额
        foreach($pay_type as $k => $v){
            switch($v){
                case "2"://2 余额支付
                    if($postdata['is_recharge']==1){$return['msg']='该业务不支持余额支付!';return $return;}
                    //赊账判断
                    if($total_revenues<=0){$return['msg']='账户余额不足!';return $return;}
                    if($online_type!=1 && $online_type!=2){$return['msg']='暂未开通余额支付!';return $return;}
                    $check_usermoney=true;
                    break;
                case "3"://3 扫码支付（主扫）
                    if($online_type!=3 && $online_type!=2){$return['msg']='暂未开通扫码支付!';return $return;}
                    break;
                case "9"://5 货到付款
                    $o_type=array('2','4','9');
                    if(!in_array($online_type,$o_type)){$return['msg']='暂未开通线下支付';return $return;}
                    //if($online_type!=9 && $online_type!=4 && $online_type!=2){$return['msg']='暂未开通线下支付!';return $return;}
                    break;
            }
        }
        $data=$this->count_total($postdata);
        // $return['sshkshkjhk']=$data;
        // return $return;
        if($data['status']==0){$return['msg']=$data['msg']; return $return;}
        if($check_usermoney && $data['total_info']['use_money']>$total_revenues){//检查店铺余额是否
            $return['msg']='账户余额不足!';
            return $return;
        }
        if($postdata['start_price']>0){
            $start_price=format_decimal(C('STARTING_PRICE'));
            $real_price=format_decimal($data['total_info']['total_price']-$data['total_info']['rebate_money']);
            if($start_price>$real_price){
                $return['status']=3;$return['msg']='订货总金额应大于起订金额';
                return $return;
            }
        }
        $order=array();
        //是否生成订单号，订货之外的订单下单有订单号
        if(($type>0 && $status>0)) $order['sn']=$this->invoicing_sn();
        $order['type'] = $type;//货单类型
        $order['mtype'] = $mtype;
        $order['pre_money'] = $pre_money;//预付款
        $order['goods_allmoney'] = $data['total_info']['total_price'];//商品总价
        $order['all_money'] = $data['total_info']['total_price']-$data['total_info']['rebate_money'];//订单实际金额(减去额外折扣的) 没减限时促销
        $order['rebate_money'] = $data['total_info']['rebate_money'];//额外折扣总额（单项优惠）
        $order['discount'] = $data['total_info']['discount'];//折扣金额//额外折扣总额+限时促销
        $order['profit'] =0;//利润
        $order['is_pay'] =1;//是否需要支付
        /*每个支付方式支付的钱数end*//*每个支付方式支付的钱数start*/
        $order['money'] = $data['total_info']['use_money'];//使用余额支付的钱
        $order['online_money'] = $data['total_info']['scan_money'];//扫码支付的钱
        $order['offline_money'] = $data['total_info']['offline_money'];//扫码支付的钱
        /*每个支付方式支付的钱数end*/
        $order['pay_amount'] = $data['total_info']['pay_price'];//在线支付的金额
        $order['pay_amount_type'] = $data['total_info']['pay_amount_type'];//在线支付方式的类型
        $order['pay_code'] = $data['total_info']['payment_info']['code'];//支付方式id
        $order['assist_code'] =$data['total_info']['payment_info']['assist_code'];//支付方式辅助code
        $order['payment_id'] = $data['total_info']['payment_info']['id'];//支付方式id
        $order['pay_status'] = 1;//支付状态 未支付
        $order['count'] = floatval($all_count);//货流量
        $order['shop_id_in'] = $shop_id_in;//入库门店id
        $order['shop_id_out'] = $shop_id_out;//货单类型
        $order['cashier_id'] = $cashier_id;//操作人
        $order['add_time'] = $now_time;
        $order['status'] = $status;
        $order['remarks'] = $postdata['remarks'];
        $order['update_time'] = $now_time;
        $order['best_time'] = $best_time;
        $order_id=M('InvoicingOrder')->add($order);
        if(empty($order_id)) {$return['msg']='添加订单失败';return $return;}
        $goods_status=empty($postdata['goods_status'])?0:intval($postdata['goods_status']);
        //如果有商品添加商品
        if($data['data']){
            foreach($data['data'] as $index=> $vv){
                $order_goods = array();
                $goodsinfo= idtoname($vv['goods_id'],'Goods','staff_comm,money,is_referral,commission,supply_price','id',false);
                $order_goods['order_id'] = $order_id;
                $order_goods['goods_id']=$vv['goods_id'];
                $order_goods['goods_name']=$vv['goods_name'];
                $order_goods['goods_sn'] = $vv['goods_sn'];
                $order_goods['goods_attr_sn']=(empty($vv['goods_attr_sn']) || $vv['goods_attr_sn']=='null')?'':$vv['goods_attr_sn'];
                $order_goods['price']   = $vv['price'];
                $order_goods['supply_price']=$vv['supply_price'];
                $order_goods['shop_id']=empty($shop_id_in)?$shop_id_out:$shop_id_in;
                $order_goods['supplier_id']=empty($vv['supplier_id'])?0:$vv['supplier_id'];
                $order_goods['storage_id']=empty($vv['storage_id'])?1:$vv['storage_id'];
                $order_goods['order_cashier_id']=$cashier_id;
                $order_goods['pre_money']=format_decimal($postdata['all_pre_money']);
                $order_goods['all_money']=empty($vv['all_money'])?0:$vv['all_money'];//小计
                $order_goods['request_num']=empty($vv['request_num'])?0:floatval($vv['request_num']);
                if($type==2 || $type==3){//出库
                    $order_goods['freight_num']=empty($vv['freight_num'])?0:floatval($vv['freight_num']);
                    $order_goods['fact_num']=empty($vv['fact_num'])?$order_goods['freight_num']:floatval($vv['fact_num']);
                }elseif($type==4){
                    $order_goods['request_num']=$vv['freight_num'];
                    $order_goods['freight_num']=$vv['freight_num'];
                    $order_goods['fact_num']=empty($vv['fact_num'])?$order_goods['freight_num']:floatval($vv['fact_num']);
                }else {
                    $order_goods['freight_num'] = empty($vv['freight_num']) ? 0 : floatval($vv['freight_num']);
                    $order_goods['fact_num'] = empty($vv['fact_num']) ? 0 : floatval($vv['fact_num']);
                }
                $order_goods['status']=$goods_status;
                $order_goods['order_time']=$now_time;
                $order_goods['update_time']=$now_time;
                if($type==1 && $mtype==1) $order_goods['send_time']=$now_time;//门店进货，直接填写发货时间
                if(!empty($data['total_info']['promat_goods'][$index])){
                    $promat_goods=$data['total_info']['promat_goods'][$index];
                    if(!empty($promat_goods['discount_extra']))$order_goods['discount_extra']=$promat_goods['discount_extra'];//额外折扣金额(单个)
                }     
                M('InvoicingGoods')->add($order_goods);
            }
        }
        $return=$this->payorder($order_id,$postdata['number'],$pay_type);//去支付
        return $return;
    }
    /**
     * 支付订单
     * $number 扫码支付扫到的码
     * $code 优惠券号
     */
    public function payorder($order_id,$number,$pay_type){
        $return=array('status'=>0,'msg'=>'');
        if(empty($order_id)){$return['msg']='订单信息错误!';return $return;}
        $map=array();
        $map['id']=$order_id;
        $map['pay_status']=1;
        $order_info=M('InvoicingOrder')->where($map)->field(true)->find();
        if(empty($order_info)){$return['msg']='订单信息错误!';return $return;}
        $pay_code=strtoupper($order_info['pay_code']);
        $payment_info=array();
        $payment_info['order_id']         =$order_id;
        $payment_info['type']             =30;
        $payment_info['order_sn']         =createOrderNo();
        $payment_info['shop_id_in'] = $order_info['shop_id_in'];
        /*每个支付方式支付的钱数start*/
        $payment_info['use_money']     = $order_info['money'];//使用余额支付的钱
        $payment_info['scan_money']     = $order_info['online_money'];//扫码支付的钱
        /*每个支付方式支付的钱数end*/
        $payment_info['need_pay']         =$order_info['pay_amount'];//还需支付的金额
        $payment_info['offline_money'] =$order_info['offline_money'];//货到付款金额
        $payment_info['order_total_price']=$order_info['all_money'];//订单实际支付的金额=商品总价+总运费-活动折扣-红包折扣
        $payment_info['payment_id']       =$order_info['payment_id'];//支付方式
        $payment_info['pay_amount']       =$order_info['pay_amount'];//
        $payment_info['pay_amount_type'] =$order_info['pay_amount_type'];
        $payment_info['pay_code']         =$pay_code;//支付code
        $payment_info['is_paid']          =0;
        $payment_info['create_time']      =NOW_TIME;
        //生成支付单
        $pay_log_id=M('PayLog')->add($payment_info);
        if(empty($pay_log_id)){$return['msg']='支付单信息错误!';return $return;}
        //余额支付判断以及查询会员信息
        if($order_info['shop_id_in'] && in_array(2,$pay_type)){
            $map=array();
            $map['id']=$order_info['shop_id_in'];
            $total_revenues=M('Shops')->where($map)->getField('total_revenues');
        }
        $is_payed=0;
        foreach($pay_type as $k => $v) {
            switch ($v) {
                case '2'://余额支付
                    if ($total_revenues >= $order_info['money']) {
                        // shop_balance_log($order_info['shop_id_in'],-$order_info['money'],1,10,'门店订货','','');
                        shop_balance_log($order_info['shop_id_in'],-$order_info['money'],1,10,'门店订货',$order_info,'');

                        $is_payed = 1;
                    }else{
                        $return['msg']='账户余额不足!';
                        return $return;
                    }
                    break;
                case '3'://双乾C扫B接口、B扫C接口
                    $is_payed = 0;
                    $return['status'] = 2;
                    $return['pay'] = $pay_log_id;
                    break;
                case '9'://货到付款
                    $is_payed = 0;
                    $is_daofu=1;
                    break;
                default:
                    $return['msg'] = '支付方式错误!';
                    return $return;
                    break;
            }
        }
        $pay_info=array();
        if($return['status']==2 && $is_payed==0){
            $snpay=$this->scan_pay($pay_log_id,$number);//扫码支付
            return $snpay;
        }
        if($is_payed){
            //处理订单
            if(empty($pay_info['out_trade_no']))$pay_info['out_trade_no']=$payment_info['order_sn'];
            $pay_info['type']=$payment_info['type'];
            $res=$this->endorder($pay_info);
            if($res['status']==1){
                $return['status']=1;
                $return['order_id']=$order_id;
                $return['is_success']=1;
                $return['msg']=$res['msg'];
            }else{
                $return['msg']=$res['msg'];
                return $return;
            }
        }else{
            if($is_daofu==1){
                if(empty($pay_info['out_trade_no']))$pay_info['out_trade_no']=$payment_info['order_sn'];
                $pay_info['is_daofu']=1;
                $pay_info['type']=$payment_info['type'];
                $in_info=$this->endorder($pay_info);
                $return['msg'] = $in_info['msg'];
                $return['status'] = $in_info['status'];
                $return['order_id']=$order_id;
                $return['is_daofu'] = 1;
                return $return;
            }else{
                $return['msg']='支付失败!';return $return;
            }
        }
        return $return;
    }
    /**
     * 计算总价
     */
    public function count_total($postdata){
        $return=array('status'=>0,'msg'=>'');
        $total_price=$pay_price=$account_money=$rebate_money=$discount=$promote_discount=0;
        $pay_type=$postdata['pay_type'];//支付方式
        // $cash_money=floatval($postdata['cash_receivable']);//应收现金
        // $cash_in_hand=floatval($postdata['cash_money']);//实收现金
        // $back_money=floatval($postdata['back_money']);//找零现金
        $scan_money=floatval($postdata['scan_money']);//扫码金额
        $money=floatval($postdata['money']);//余额
        $huodao_money=floatval($postdata['huodao_money']);//货到付款金额
        $is_mix=intval($postdata['is_mix']);//是否组合支付
        /*处理商品相关信息计算总价格start*/
        if(!empty($postdata['cart_list'])) {
            //如果是app商品列表不用做处理
            if($postdata['is_app']==1){$cart_list = $postdata['cart_list'];}
            else{$cart_list = json_decode(htmlspecialchars_decode($postdata['cart_list']), true);}
            //循环选中的商品列表得到需要的数据
            foreach ($cart_list as $k => $v) {
                $karr = explode('-', $k);//得到属性值
                $is_sanhuo = 0;
                $goods_id = intval($karr[0]);

                $postdata['goods_list'][$k]['goods_id'] = $goods_id;
                $postdata['goods_list'][$k]['goods_name'] = $v['goods_name'];
                if($v['goods_attr_sn']) $postdata['goods_list'][$k]['goods_sn']=$v['goods_attr_sn'];
                else $postdata['goods_list'][$k]['goods_sn']=$v['goods_sn'];
                $postdata['goods_list'][$k]['goods_attr_sn']=$v['attr_key'];
                $postdata['goods_list'][$k]['supplier_id']=$v['suppliers_id'];
                $postdata['goods_list'][$k]['storage_id']=1;
                $postdata['goods_list'][$k]['all_money']=$v['all_money'];
                $postdata['goods_list'][$k]['freight_num'] =empty($v['freight_num'])?0:$v['freight_num'];
                if($postdata['type']==1){
                    $postdata['goods_list'][$k]['fact_num']=$v['freight_num'];
                }elseif($postdata['type']==4){
                    $postdata['goods_list'][$k]['fact_num']=empty($v['fact_num'])?$v['freight_num']:$v['fact_num'];
                }else{
                    $postdata['goods_list'][$k]['request_num']=empty($v['request_num'])?0:$v['request_num'];
                    $postdata['goods_list'][$k]['fact_num']=empty($v['fact_num'])?0:$v['fact_num'];
                }
                $postdata['goods_list'][$k]['shop_id']=$postdata['shop_id'];
            }
        }
        $promat_goods=array();
        if($postdata['goods_list']){
            $result=$this->goods_info($postdata['goods_list'],$postdata['shop_id']);
            if($result['status']==0){ $return['msg']=$result['info']; return $return;}
            $goods_list=$result['info']['goods_list'];
            $promat_goods=$result['info']['promat_goods'];//单品优惠详情
            $yingshou=$result['info']['total_price'];//优惠后的价格
            $total_price=$result['info']['goods_amount'];//总价
            $rebate_money=$result['info']['rebate_money'];//额外折扣总金额
        }
        $type=empty($postdata['type'])?0:$postdata['type'];//货单类型
        $pay_total_price=format_decimal($total_price-$rebate_money-$promote_discount);//实付款金额
        $discount=$rebate_money+$promote_discount;//所有优惠的价格

        /*计算支付金额参数start*/
        $pay_list=array();
        $pay_list['is_mix']=$is_mix;//是否混合支付
        $pay_list['pay_type']=$pay_type;//支付方式
        $pay_list['pay_total_price']=$pay_total_price;//需要支付的总钱数
        // $pay_list['cash_money']=$cash_money;//现金支付钱数
        $pay_list['scan_money']=$scan_money;//扫码支付钱数
        $pay_list['money']=$money;//余额支付钱数
        $pay_list['huodao_money']=$huodao_money;//余额支付钱数
        // $pay_list['cash_in_hand']=$cash_in_hand;//实收现金
        // $pay_list['back_money']=$back_money;
        $pay_list['number']=$postdata['number'];//扫码支付的编号
        /*判读是否是混合支付得到需要的钱数start*/
        if(in_array(2,$pay_type)){
            $pay_data=$this->only_paytype($pay_list);
            $paymentinfo=$pay_data['data']['payment_info'];
        }
        if(in_array(3,$pay_type)){
            $pay_data=$this->only_paytype($pay_list);
            $paymentinfo=$pay_data['data']['payment_info'];
        }
        if(in_array(9,$pay_type)){
            $pay_data=$this->only_paytype($pay_list);
            $paymentinfo=$pay_data['data']['payment_info'];
        }
        if($pay_data['status']==0){$return['msg']=$pay_data['msg']; return $return;}
        $payment_info=array();
        $payment_info=$paymentinfo;
        $use_money=$pay_data['data']['use_money'];
        // $cash_money=$pay_data['data']['cash_money'];//现金
        // $act_cash_in_hand=$pay_data['data']['cash_in_hand'];//实收现金
        // $act_back_money=$pay_data['data']['back_money'];
        $scan_money=$pay_data['data']['scan_money'];
        $offline_money=$pay_data['data']['offline_money'];
        $pay_price=$pay_data['data']['pay_price'];
        $pay_amount_type=$pay_data['data']['pay_amount_type'];
        /*判断是否是混合支付得到需要的钱数end*/
        /*计算支付金额参数end*/
        $return['status']=1;
        $return['data']=$goods_list;
        $return['ids_arr'] = $ids_arr;
        $return['total_info']=array(
            'total_price'=>$total_price,//商品总价
            'pay_price'=>$pay_price,//线上支付价格
            'pay_amount_type'=>$pay_amount_type,
            'discount'=>$discount,//总优惠价格
            'promat_goods'=>$promat_goods,//单品优惠详情
            'payment_info'=>$payment_info,//使网银支付信息
            'pay_total_price'=>$pay_total_price,//订单实际支付的金额=商品总价-额外折扣-限时促销
            'rebate_money'=>$rebate_money,//额外折扣总金额
            // 'cash_in_hand'=>$act_cash_in_hand,//实收现金
            // 'cash_money'=>$cash_money,//现金支付金额
            // 'back_money'=>$act_back_money,//找零现金
            'scan_money'=>$scan_money,//扫码支付金额
            'use_money'=>$use_money,//余额支付金额
            'offline_money'=>$huodao_money,//货到支付金额
            'type'=>$type,//货单类型
        );
        return $return;
    }

    /**
     * 获取商品详情
     */
    public function goods_info($goods_list,$shop_id){
        $return=array('status'=>0,'info'=>'');
        if(empty($goods_list)){$return['info']='商品无效!';return $return;}
        $goodsids=array();
        foreach($goods_list as $v){
            if($v['goods_id'])$goodsids[]=$v['goods_id'];
        }
        $map=array();
        if(!empty($goodsids)) {//非无码商品
            $map['id'] = array('in', $goodsids);
            $map['status'] = 1;
            $map['publish_wait'] = 1;
            $map['is_delete'] = 0;
            $map['goods_type'] = 5;
            $lists = M('Goods')->where($map)->field('id,goods_sn,goods_name,suppliers_id,supply_price,shop_price,purchase_price,is_promote,promote_price,promote_start_time,promote_end_time,promote_id')->select();
            if (empty($lists)) {
                $return['info'] = '商品无效!';
                return $return;
            }
            
            $new_lists = array();
            foreach ($lists as $v) {
                $new_lists[$v['id']] = $v;
            }
        }      
        $total_price=0;//实际收款总金额
        $goods_amount=0;//商品总金额
        $rebate_money=0;//额外折扣金额（额外打折单项优惠金额）
        // $promote_discount=0;//限时促销
        $promat_goods=array();
        foreach($goods_list as $k=> $v){
            $promat_goods[$k]=array('discount_extra'=>0,'discount_xianshi'=>0,);
            
            if($v['goods_id'])$goods_info=$new_lists[$v['goods_id']];
            else {
                $goods_info=$goods_list[$v['goods_sn']];
                unset($goods_list[$k]['goods_attr']);
            }
            if(empty($goods_info)){unset($goods_list[$k]);continue;}
            $discount_price=$this->get_min_price($shop_id,$goods_info['id'],$v['goods_attr_sn']);
            //额外折扣
            if($discount_price['price_type']==1){
                $realprice = $discount_price['goods_price'];
                $promat_goods[$k]['discount_extra']=$discount_price['price']-$realprice;
                $rebate_money+=format_decimal(($discount_price['price']-$realprice))*$v['request_num'];
            }
            $goods_list[$k]['goods_name']=$goods_info['goods_name'];
            $att_map=array();
            $att_map['goods_id']=$goods_info['id'];
            if($v['goods_attr_sn']==0) $att_map['attr_key']='';
            else $att_map['attr_key']=$v['goods_attr_sn'];
            $goods_attr_sn=M('GoodsAttrStock')->where($att_map)->getField('goods_attr_sn');
            if($goods_attr_sn)$goods_list[$k]['goods_sn']=$goods_attr_sn;
            else $goods_list[$k]['goods_sn']=$goods_info['goods_sn'];
            $goods_list[$k]['price']=$discount_price['price'];//不同类型下的商品单价（加属性）
            $goods_list[$k]['supply_price']=$realprice;//实际价格
            $goods_list[$k]['shop_id']=$v['shop_id'];
            $goods_list[$k]['supplier_id']=$goods_info['suppliers_id'];
            $total_price+=$realprice*$v['request_num'];
            $goods_amount+=$discount_price['price']*$v['request_num'];//商品总金额
        }
        $data=array();
        $data['goods_list'] =$goods_list;
        $data['promat_goods'] =$promat_goods;
        $data['total_price']=$total_price;//实际付款总金额
        $data['goods_amount']=$goods_amount;//商品总金额
        $data['rebate_money']=$rebate_money;//额外折扣金额（额外打折单项优惠金额）
        $return['status']=1;
        $return['info']=$data;
        return $return;
    }

    /**
     * 获取商品最小价格
     */
    public function get_min_price($shop_id,$goods_id,$attr_key=''){
        if(empty($goods_id))return false;
        $name='Goods';
        $map=$where=$tl_map=$return=array();$map['id']=$goods_id;
        $goods_info = M($name)->where($map)->field('id,shop_price,supply_price,purchase_price,promote_id,promote_price,goods_type')->find();
        $where['id']=$shop_id;
        $where['status']=1;
        $shop_info=M('Shops')->where($where)->field('send_price,extra_discount')->find();
        if(floatval($shop_info['extra_discount'])>0)$extra_discount=$shop_info['extra_discount'];
        else $extra_discount=100;
        //默认
        $return['price_type']=1;
        if($attr_key){
            $map=array();
            $map['goods_id']=$goods_id;
            $map['attr_key']=$attr_key;
            $shop_price=M('GoodsAttrStock')->where($map)->getField('attr_price');
            $goods_info['shop_price']=$shop_price; 
        }
        //如果订货价是销售价则考虑属性价格
        switch($shop_info['send_price']){
            case 1://进货价
                if(floatval($goods_info['purchase_price'])<=0)$goods_info['purchase_price']=$goods_info['shop_price'];
                $return['price']=$goods_info['purchase_price'];
                $return['goods_price']=format_decimal($goods_info['purchase_price']*$extra_discount/100);
                break;
            case 2://售价
                $return['price']=$goods_info['shop_price'];
                $return['goods_price']=format_decimal($goods_info['shop_price']*$extra_discount/100);
                break;
            default:
                if(floatval($goods_info['supply_price'])<=0)$goods_info['supply_price']=$goods_info['shop_price'];
                $return['price']=$goods_info['supply_price'];
                $return['goods_price']=format_decimal($goods_info['supply_price']*$extra_discount/100);
                break;
        }
        return $return;
    }

    /**
     * 混合支付
     */
    public function only_paytype($pay_info){
        $return=array('status'=>0,'msg'=>'');
        $use_money=$scan_money=$offline_money=0;
        // $cash_money=$use_money=$scan_money=$bank_money=$card_money=$cash_in_hand=$back_money=0;
        $pay_amount_type=0;
        if(!in_array($pay_info['pay_type'],array(3))){
            $site_paytype=check_re_pay();
            switch($site_paytype){
                case "1":
                    $pay_codepos='MMSCAN';
                    $pay_code='MMSCAN';
                    break;
                case "2":
                    $pay_codepos='STARPOS';
                    $pay_code='STARPOS';
                    break;
                case "3":
                    $pay_codepos='CHINAUMSPOS';
                    $pay_code='CHINAUMS';
                    break;
                default:
                    $return['msg']='您还没有认证，请先认证';
                    return $return;
                    break;
            }
        }
        foreach($pay_info['pay_type'] as $k => $v){
            switch($v){
                case "9"://货到付款
                    //判断现金支付金额是否小于0，若小于等于0则这个支付方式直接跳过
                    if($pay_info['huodao_money']<0){ continue;}
                    $offline_money=$pay_info['huodao_money'];
                    $payment_info=array('id'=>9,'code'=>'HANCHAO_DAOFU','assist_code'=>'HANCHAO_DAOFU','name'=>'货到付款');
                    break;
                case "3"://3 扫码支付 主扫
                    //判断扫码支付金额是否小于0，若小于等于0则这个支付方式直接跳过
                    if($pay_info['scan_money']<0){ continue;}
                    //$site_paytype=check_re_pay();
                    $scan_money=$pay_info['scan_money'];
                    $pay_price=$pay_info['scan_money'];
                    if(intval($pay_info['number'])){
                        $pay_first=substr($pay_info['number'],0,1);
                        if($pay_first==1){//微信
                            $payment_info=array('id'=>'20','code'=>$pay_codepos,'assist_code'=>'HANCHAO_S_WEIXIN','name'=>'微信支付');
                        }
                        if($pay_first==2){//支付宝
                            $payment_info=array('id'=>'20','code'=>$pay_codepos,'assist_code'=>'HANCHAO_S_ALIPAY','name'=>'支付宝支付');
                        }
                    }
                    $pay_amount_type=2;//线上支付扫码支付类型
                    break;
                case "2"://2 余额支付
                    //判断余额支付金额是否小于0，若小于等于0则这个支付方式直接跳过
                    if($pay_info['money']<0){ continue;}
                    if($pay_info['is_recharge']==1){
                        $return['msg']='该业务不支持余额支付';
                        return $return;
                    }
                    $use_money=$pay_info['money'];
                    $payment_info=array('id'=>1,'code'=>'HANCHAO','assist_code'=>'HANCHAO','name'=>'余额支付');
                    break;
            }
        }

        $total_money=$scan_money+$use_money+$offline_money;
        if(($total_money+0.1)<$pay_info['pay_total_price']){
            $return['msg']='输入的支付金额不能小于总金额';
            return $return;
        }
        if($total_money-0.1>$pay_info['pay_total_price'] && !in_array(1,$pay_info['pay_type'])){
            $return['msg']='输入的支付金额不能大于总金额';//.$total_money.'<'.$pay_info['pay_total_price']
            return $return;
        }
        $return['status']=1;
        $return['data']['payment_info']=$payment_info;
        $return['data']['use_money']=$use_money;//余额支付金额
        $return['data']['scan_money']=$scan_money;//扫码支付金额
        $return['data']['offline_money']=$offline_money;//扫码支付金额
        $return['data']['pay_price']=$pay_price;//线上支付总金额
        $return['data']['pay_amount_type']=$pay_amount_type;//线上支付方式类型0没有线上支付 1台卡支付 2 扫码支付
        return $return;
    }

    /**
     * 处理进销存订单
     */
    public function endorder($info){
        $return=array('status'=>0,'msg'=>'');
        if(empty($info)){$return['msg']='支付单信息错误!';return $return;}
        $map=array();
        $map['order_sn'] = $info['out_trade_no'];
        $pay_info = M("PayLog")->where($map)->field(true)->find();
        $all_money=format_decimal($pay_info['use_money']+$info['money']+$pay_info['offline_money']);
        $order_total_price=format_decimal($pay_info['order_total_price']);
        $differ_price=format_decimal($order_total_price-$all_money);
        if($differ_price<0.1 && $differ_price>-0.1){
            $map=array();
            $map['id']=$pay_info['order_id'];
            $order_info=M('InvoicingOrder')->where($map)->field('type,mtype,pre_money,shop_id_in,shop_id_out')->find();
            if($info['is_daofu']!=1){
                $paylogsave['is_paid'] = 1;
                $paylogsave['pay_sn'] = $info['pay_sn'];
                $paylogsave['update_time'] = NOW_TIME;
                $paylogwhere['is_delete'] = 0;
                $paylogwhere['order_sn'] = $info['out_trade_no'];
                $res = M('PayLog')->where($paylogwhere)->save($paylogsave);
                if ($res) {
                    $orderwhere=$updatedata=array();
                    $orderwhere['id'] = $pay_info['order_id'];
                    $orderwhere['pay_status'] = array('neq',3);
                    $orderwhere['status'] = array('lt',3);
                    $updatedata['pay_status'] =3;
                    if($info['pay_sn'])$updatedata['pay_sn'] = $info['pay_sn'];//支付接口返回的订单号
                    if($info['money'])$updatedata['pay_amount'] = $info['money'];//线上支付
                    if($info['pay_code'])$updatedata['assist_code'] = $info['pay_code'];
                    $updatedata['pay_time'] = NOW_TIME;
                    M('InvoicingOrder')->where($orderwhere)->save($updatedata);
                }
            } 
            if($info['type']==30){
               $return=array('status'=>1,'msg'=>'已成功为门店进货','id'=>$pay_info['order_id']);
                //加入订单对账表
                if($order_info['type']==1 && $order_info['mtype']==1){
                    //门店进货添加供货商对账状态为待对账
                    D('Common/InvoicingOrder')->add_invoicing_detail($pay_info['order_id'],1,0,$order_info['pre_money']);//添加供货商对账单
                    D('Common/InvoicingOrder')->add_storage($pay_info['order_id']);//添加库存
                }elseif($order_info['type']==1 && $order_info['mtype']==0){//后台进货
                    D('Common/InvoicingOrder')->add_invoicing_detail($pay_info['order_id'],0,0,$order_info['pre_money']);//添加供货商对账单
                    FrieghtPushSend($order_info['shop_id_in']);//极光推送（app/pad）
                }elseif($order_info['type']==2 || $order_info['type']==3){//后台出库2普通出库3门店退货
                    D('Common/InvoicingOrder')->reduce_storage($pay_info['order_id']);//减少库存并记录出库记录
                    if($order_info['type']==3 && $order_info['mtype']==0) D('Common/InvoicingOrder')->add_invoicing_detail($pay_info['order_id'],1,0,array(),1);//减少供货商对账单
                    $return=array('status'=>1,'msg'=>'已成功为门店出货','id'=>$pay_info['order_id']);
                }elseif($order_info['type']==4){//调货
                    if($order_info['mtype']==0){
                        FrieghtPushSend($order_info['shop_id_out']);
                        $return=array('status'=>1,'msg'=>'已成功向门店发起调货通知','id'=>$pay_info['order_id']);
                    }elseif($mtype==1){
                        FrieghtPushSend($order_info['shop_id_in']);
                        $return=array('status'=>1,'msg'=>'成功给门店'.$order_info['shop_id_in'].'调货');
                        D('Common/InvoicingOrder')->reduce_storage($pay_info['order_id']);//减少库存
                    }
                }else{
                    $return=array('status'=>1,'msg'=>'已成功为门店订货','id'=>$pay_info['order_id']);
                }
            }
        }
        return $return;
    }
    //jxr end
    /**
     * 多种接口的扫码支付共用方法
     * @param string $pay_log_id  paylog表的id 用来查询所有的订单信息
     * @param string $number B扫C的时候获取到用户的支付码
     * @return array
     */
    private function scan_pay($pay_log_id='',$number=''){
        $return=array('status'=>0,'msg'=>'');
        $pay_log_id=intval($pay_log_id);//格式化pay_log_id
        if(empty($pay_log_id)){$return['msg']='支付单信息错误!';return $return;}
        $where=array();
        $where['id']=$pay_log_id;
        $where['is_paid']=array('neq',1);
        $pay_info = M('PayLog')->where($where)->field(true)->find();//查询符合条件的支付单信息
        if(empty($pay_info['order_sn'])){$return['msg']='支付单信息错误!';return $return;}
        $pay_code=ucfirst(strtolower($pay_info['pay_code']));//转化支付方式code为首字母大写其他小写
        if(empty($pay_code)){$return['msg']='支付方式错误!';return $return;}
        $p_map=array();
        $p_map['status']=1;
        $p_map['code']=$pay_code;
        $payconfig=M('Payment')->where($p_map)->field(true)->find();
        if(empty($payconfig) || empty($payconfig['config_account'])){$return['msg']='支付通道未开通！'; return $return;}
        $paycode=strtoupper($pay_info['pay_code']);
        $return['paycode']=$paycode;
        switch($paycode){
            case 'CHINAUMS'://银联C扫B接口
                $pay = new \Common\Vendor\Pay($pay_code,$payconfig);
                $vo = new \Common\Vendor\Pay\PayVo();
                $vo->setFee($pay_info['bank_money'])
                    ->setOrderNo($pay_info['order_sn'])
                    ->setParam($pay_info);
                $RequestForm=$pay->buildRequestForm($vo);
                if($RequestForm['status']){
                    $return['status']=1;
                    $pay_save = array();
                    $pay_save['serial_number'] = $RequestForm['url'];
                    $map = array();
                    $map['order_sn'] = $pay_info['order_sn'];
                    M('PayLog')->where($map)->save($pay_save);
                    $return['order_id']=$pay_info['order_id'];
                    $url= $RequestForm['url'];
                    $return['url']=$url;
                    return $return;
                }else{
                    return $RequestForm;
                }
                break;
            case 'CHINAUMSPOS'://银联B扫C接口
                if(empty($number)){$return['msg']='付款码错误!';return $return;}
                $payconfig['is_app']=1;//是否是APP
                $pay = new \Common\Vendor\Pay($pay_code,$payconfig);
                $vo = new \Common\Vendor\Pay\PayVo();
                $title_name='收银';
                $vo->setBody($title_name)
                    ->setFee($pay_info['need_pay'])
                    ->setTitle($title_name)
                    ->setOrderNo($pay_info['order_sn'])
                    ->setParam($payconfig)
                    ->setProduct_id($number);
                $RequestForm=$pay->buildRequestForm($vo);
                $return['status']=$RequestForm['status'];
                $return['order_id']=$pay_info['order_id'];
                return $return;
                break;
            case 'MMSCAN'://双乾C扫B接口、B扫C接口调用接口类
                $map=array();
                $map['id']=$pay_info['order_id'];
                $assist_code=M('OrderInfo')->where($map)->getField('assist_code');//获取辅助码
                //支付接口用到的支付类型
                if($assist_code=='HANCHAO_S_ALIPAY'){//支付宝支付
                    $pay_info['pay_type']='ZFBZF';
                }
                if($assist_code=='HANCHAO_S_WEIXIN'){//微信支付
                    $pay_info['pay_type']='WXZF';
                }
                if($assist_code=='HANCHAO_S_ALIPAY' || $assist_code=='HANCHAO_S_WEIXIN'){
                    if(empty($number)){$return['msg']='付款码错误!';return $return;}
                    $pay_info['tran_code']='SMZF003';//B扫C接口编号
                    $pay_info['scene']=1;
                }else{
                    $pay_info['tran_code']='SMZF010';
                    $pay_info['user_id']=get_openid();
                }
                //标题
                $title_name=$pay_info['order_sn']."扫码支付";
                $pay = new \Common\Vendor\Pay($pay_code,$payconfig);
                $vo = new \Common\Vendor\Pay\PayVo();
                $vo->setBody($title_name)
                    ->setFee($pay_info['need_pay'])
                    ->setTitle($title_name)
                    ->setOrderNo($pay_info['order_sn'])
                    ->setParam($pay_info)
                    ->setProduct_id($number);
                $RequestForm=$pay->buildRequestForm($vo);
                $snpay=json_decode($RequestForm);
                //print_r($snpay);exit;
                if($snpay[0]->respCode=='88'){
                    $return['is_success']=1;
                    $return['status']=1;
                    //$return['data']['status']=1;
                    if($assist_code=='HANCHAO_S_WEIXIN'){
                        $return['content']='微信到账'.$pay_info['need_pay'].'元';
                    }
                    if($assist_code=='HANCHAO_S_ALIPAY'){
                        $return['content']='支付宝到账'.$pay_info['need_pay'].'元';
                    }
                    $return['order_id']=$pay_info['order_id'];
                    return $return;
                }elseif($snpay[0]->respCode=='100000' || $snpay[0]->respCode=='200000' || $snpay[0]->respCode=='000000'){
                    $return['status']=1;
                    $return['order_id']=$pay_info['order_id'];
                    return $return;
                }else{
                    $return['msg']=$snpay[0]->respMess;
                    return $return;
                }
                break;
            default:
                $return['msg']='支付方式错误!';return $return;
                break;
        }
    }
    /**
     * 实时监测是否付款成功
     */
    public function check_paysuccess($order_id){
        $return=array('status'=>1,'msg'=>'');
        if(empty($order_id)){$return['msg']='订单不存在'; $return['status']=0; return $return;}
        $map=array();
        $map['id']=intval($order_id);
        $order_info=M('InvoicingOrder')->where($map)->field('pay_status,pay_code,assist_code,sn,id')->find();
        $pay_code=strtoupper($order_info['pay_code']);
        if($pay_code!='MMSCAN'){
            $map=array();
            $map['order_id']=$order_info['id'];
            $map['type']=30;
            $order_sn=M('PayLog')->where($map)->getField('order_sn');
            if($order_info['pay_status']==1){
                if($pay_code=='HANCHAO_SWEIXIN' || $pay_code=='HANCHAO_S_WEIXIN'){$note='微信';}
                if($pay_code=='HANCHAO_SALIPAY' || $pay_code=='HANCHAO_S_ALIPAY'){$note='支付宝';}
                $return['data']['info']='扫码成功，正在'.$note.'支付';
                if($pay_code=='CHINAUMSPOS'){
                    $p_map=array();
                    $p_map['status']=1;
                    $p_map['code']=ucfirst(strtolower($pay_code));
                    $payconfig=M('Payment')->where($p_map)->field(true)->find();
                    $pay = new \Common\Vendor\Pay($p_map['code'],$payconfig);
                    $pay->check();
                    $queryResult = $pay->query($order_sn);
                    if($queryResult['errCode']=='00'){
                        if($queryResult['queryResCode']=='0'){
                            $info = $pay->getInfo();
                            $result=$this->endorder($info);
                        }
                        if($queryResult['queryResCode']=='5'){
                            $return['status']=0;
                            $return['msg']='支付失败';
                            return $return;
                        }
                    }
                }
            }
        }
        if($order_info['pay_status']==3 || $order_info['pay_code']=='HANCHAO_DAOFU'){
            $return['data']['info']='支付成功';
            $return['data']['status']=1;
            $return['data']['content']='';
            /*if($pay_code=='MMSCAN' || $pay_code=='CHINAUMSPOS' || $pay_code=='CHINAUMS'){
                if($order_info['assist_code']=='HANCHAO_S_WEIXIN'){
                    $return['data']['content']='微信到账'.$order_info['pay_amount'].'元';
                }
                if($order_info['assist_code']=='HANCHAO_S_ALIPAY'){
                    $return['data']['content']='支付宝到账'.$order_info['pay_amount'].'元';
                }
            }*/
            $return['msg']='支付成功';
            return $return;
        }else{
            $return['data']['info']='正在支付。。';
            $return['data']['status']=1;
            $return['msg']='支付成功';
            return $return;
        }
    }

}