<?php
/** 收银订单
 * @Copyright (C) 2016 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author lss <lss@qq.com>
 */

namespace App\Model;
use Think\Model;
class OrderInfoModel extends Model{

    //计算订单的总金额等数据
    public function count_total($postdata){
        $return=array('status'=>0,'msg'=>'');
        $total_price=$pay_price=$pay_fee=$account_money=$bonu_money=$bonus_id=$member_discount=$custom_discount=$single_discount=$discount='0';
        $uid=intval($postdata['uid']);//会员id（不是必须的用来查询会员的折扣率）
        $coupon_id=intval($postdata['coupon_id']);//优惠券id
        $coupon_code=trim($postdata['coupon_code']);//优惠券号
        $code_type=intval($postdata['code_type']);//优惠券检查方式 1是code，2是id
        $single_discount=floatval($postdata['custom_discount']);//自定义优惠
        $single_type=intval($postdata['single_type']);//自定义优惠类型
        $pay_type=intval($postdata['pay_type']);//支付方式
        $cash_in_hand=floatval($postdata['cash_in_hand']);//应收现金
        $use_score=intval($postdata['use_score']);
		$postdata['is_recharge']=intval($postdata['is_recharge']);//是否为充值订单
		$postdata['is_package']=intval($postdata['is_package']);//是否为充值订单
        $payment_info=array();
        if($postdata['cart_list']) {
            $cart_list = json_decode(htmlspecialchars_decode($postdata['cart_list']), true);
            foreach ($cart_list as $k => $v) {
                $karr = explode('-', $k);
                $is_sanhuo = 0;
                $goods_id = $karr[0];
                if (empty($goods_id)) continue;
                if ($is_sanhuo == 0) {
                    $goods_attr = array();
                    $goods_attr_key = $goods_attr['key'] = $karr[1];
                    if ($goods_attr_key) $goods_attr['name'] = attr_key2name($goods_attr_key, $goods_id);
                }
                $postdata['goods_list'][$k]['goods_name'] = $v['goods_name'];
                $postdata['goods_list'][$k]['goods_number'] = $v['num'];
                $postdata['goods_list'][$k]['market_price'] = $v['price'];
                $postdata['goods_list'][$k]['goods_id'] = $goods_id;
                if ($goods_attr_key) $postdata['goods_list'][$k]['goods_attr'] = serialize($goods_attr);
            }
        }
        if($postdata['goods_list']){
            $result=D('Shop/OrderInfo')->goods_info($postdata['goods_list'],$uid);
            if($result['status']==0){ $return['msg']=$result['info']; return $return;}
            $goods_list=$result['info']['goods_list'];
            $yingshou=$result['info']['total_price'];//优惠后的价格
            $total_price=$result['info']['goods_amount'];//总价
            $member_discount=$result['info']['member_discount'];//折扣价格
        }else if($postdata['is_package'] != 0){
			$result=$this->package_info($postdata['is_package']);
			$goods_list=$result['info']['goods_list'];
            if($result['status']==0){ $return['msg']=$result['info']; return $return;}
			$total_price=floatval($postdata['total_price']);//订单总金额
		}else{
            $total_price=floatval($postdata['total_price']);//订单总金额
        }
        //如果不是充值的订单就计算优惠
        if($postdata['is_recharge'] ==1) {
			$order_type=2;
		}else if($postdata['is_package'] !=0){
			$order_type=12;
		}else{
            $yingshou = $total_price;
            if(empty($postdata['goods_list'])){
                //会员优惠金额
                if ($uid) {
                    $user_discount = $this->count_member_discount($uid, $yingshou);//获取会员优惠金额
                    if ($user_discount['status']) {
                        $member_discount = $user_discount['user_discount'];
                        $yingshou = $yingshou - $member_discount;//计算优惠后的实付金额
                    } else {
                        $return['msg'] = $user_discount['msg'];
                        return $return;
                    }
                }
            }
            //优惠券优惠金额
            if ($coupon_id) {
                $coupon_discount = $this->count_coupon_discount($coupon_id, $coupon_code, $yingshou, $code_type);//获取优惠的价格
                if ($coupon_discount['status']) {
                    $bonu_money = $coupon_discount['coupon_discount']['bonu_money'];
                    $bonus_id = $coupon_discount['coupon_discount']['bonus_id'];
                    $yingshou = $yingshou - $bonu_money;//计算优惠后的实付金额
                } else {
                    $return['msg'] = $coupon_discount['msg'];
                    return $return;
                }
            }
            //自定义优惠
            if ($single_discount > 0) {
                $defined_discount = $this->count_custom_discount($single_type, $single_discount, $yingshou);//获取优惠金额
                if ($defined_discount['status']) {
                    $custom_discount = $defined_discount['custom_discount'];
                    $yingshou = $yingshou - $custom_discount;//计算优惠后的实付金额
                } else {
                    $return['msg'] = $custom_discount['msg'];
                    return $return;
                }
            }
            //如果使用积分计算积分抵扣的钱
            if ($use_score && $uid > 0) {
                $map['id'] = $uid;
                $map['status'] = 1;
                $count = M('Member')->where($map)->count();
                if ($count) {
                    $score = M('Member')->where($map)->getField('usepoints');
                    if ($score > 0) {
                        $order_score = intval($yingshou * (C('INTGRAL_PAY_RATIO') / 100) * 100 / C('WEB_INTEGRAL_RATIO'));
                        if ($score >= $order_score) {
                            $use_score_money = $order_score * (C('WEB_INTEGRAL_RATIO') / 100);//钱
                            $use_score_num = intval($order_score);//分

                        } else {
                            $use_score_money = $score * (C('WEB_INTEGRAL_RATIO') / 100);
                            $use_score_num = intval($score);
                        }
                        $yingshou = $yingshou - $use_score_money;
                    } else {
                        $return['msg'] = '积分不足';
                        return $return;
                    }
                }
            }
            $order_type=13;
        }
        $pay_total_price=$total_price+$pay_fee-$bonu_money-$member_discount-$custom_discount-$use_score_money;//加上手续费后的实付款金额
        $discount=$bonu_money+$member_discount+$custom_discount;//所有优惠的价格
		
		if(!in_array($pay_type,array(1,3,4))){
			$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;
			}
		}
        switch($pay_type){
            case "1"://1 现金支付
                $payment_info=array('id'=>'9','code'=>'HANCHAO_XIANJIN','assist_code'=>'HANCHAO_XIANJIN','name'=>'现金支付');
                $account_money=$pay_total_price;
                break;
            case "2"://2 扫码支付
                $pay_price=$pay_total_price;
                if(intval($postdata['number'])){
                    $pay_first=substr($postdata['number'],0,1);
                    if($pay_first==1){//微信
                        $payment_info=array('id'=>'13','code'=>$pay_codepos,'assist_code'=>'HANCHAO_S_WEIXIN','name'=>'微信支付');
                    }
                    if($pay_first==2){//支付宝
                        $payment_info=array('id'=>'13','code'=>$pay_codepos,'assist_code'=>'HANCHAO_S_ALIPAY','name'=>'支付宝支付');
                    }
                }
                break;
            case "6":
                $pay_price=$pay_total_price;
                $payment_info=array('id'=>'13','code'=>$pay_code,'assist_code'=>$pay_code,'name'=>'扫码支付');
                break;
            case "3"://3 收款码支付
                if($postdata['coupon_type']==0){//支付宝收款码
                    $payment_info=array('id'=>'10','code'=>'HANCHAO_AliPay','assist_code'=>'HANCHAO_AliPay','name'=>'支付宝收款码支付');
                }
                if($postdata['coupon_type']==1){
                    $payment_info=array('id'=>'11','code'=>'HANCHAO_WEIXIN','assist_code'=>'HANCHAO_WEIXIN','name'=>'微信收款码支付');
                }
                if($postdata['coupon_type']==2){
                    $payment_info=array('id'=>'12','code'=>'HANCHAO_OTHER','assist_code'=>'HANCHAO_OTHER','name'=>'其他收款码支付');
                }
                $account_money=$pay_total_price;
                break;
            case "4"://4 余额支付
                if($postdata['is_recharge']==1){
                    $return['msg']='该业务不支持余额支付';
                    return $return;
                }
                $account_money=$pay_total_price;
                $paymentid=idtoname('Hanchao','Payment','id','code');
                $payment_info=array('id'=>$paymentid,'code'=>'HANCHAO','assist_code'=>'HANCHAO','name'=>'余额支付');
                break;
        }
        $return['status']=1;
        $return['data']=$goods_list;
        $return['total_info']=array(
            'total_price'=>$total_price,//商品总价
            'pay_price'=>$pay_price,//线上支付价格
            'pay_fee'=>format_decimal($pay_fee),//手续费
            'discount'=>$discount,//总优惠价格
            'payment_info'=>$payment_info,//使网银支付信息
            'pay_total_price'=>$pay_total_price,//订单实际支付的金额=商品总价+总运费-活动折扣-红包折扣-积分抵扣
            'bonus_id'=>$bonus_id,//红包 ID
            'bonu_money'=>$bonu_money,//红包/优惠抵扣的价格
            'member_discount'=>$member_discount,//会员折扣价格
            'custom_discount'=>$custom_discount,//自定义折扣价格
            'cash_in_hand'=>$cash_in_hand,//实收金额
            'use_money'=>$account_money,
            'used_score'=>$use_score_num,
            'used_score_money'=>$use_score_money,
            'order_type'=>$order_type,//订单类型
        );
        //print_r($return['data']);exit;
        return $return;
    }
    //添加订单
    public function add_order($postdata){
        $return=array('status'=>0,'msg'=>'');
        //判断支付方式
        $pay_type=intval($postdata['pay_type']);
        if(empty($pay_type)){$return['msg']='支付方式错误';return $return;}
        $total_price=floatval($postdata['total_price']);
        if($total_price<0){ $return['msg']='请输入正确的金额';return $return;}
        $uid=intval($postdata['uid']);
        $userinfo=array();
        if($uid){
            $map=array();
            $map['id']=$uid;
            $map['status']=1;
            //$map['is_tmp']=0;
            $userinfo=M('Member')->where($map)->field('id,username,nickname,mobile,email,rank_id,paypassword,money,usepoints,salt,guide')->find();
            if(empty($userinfo)){$return['msg']='该会员不存在!';return $return;}
        }
        $check_usermoney=false;//是否检查会员账户余额
        switch($pay_type){
            case "1"://1 现金支付
                break;
            case "2"://2 扫码支付(主扫)
                break;
            case "6"://6 扫码支付(被扫)
                break;
            case "3"://3 收款码支付
                break;
            case "4"://4 余额支付
                if($postdata['is_recharge']==1){$return['msg']='该业务不支持余额支付!';return $return;}
                if(empty($uid)){$return['msg']='请选择余额支付的会员!';return $return;}
                //$number=trim($postdata['number']);
                //if(empty($number)){$return['info']='请填写支付密码!';return $return;}
                //if(empty($userinfo['paypassword'])){$return['info']='该会员没有设置支付密码!';return $return;}
                $userinfo['money']=floatval($userinfo['money']);$userinfo['usepoints']=intval($userinfo['usepoints']);
                if(empty($userinfo['money'])){$return['msg']='该会员余额不足!';return $return;}
                //if(empty($userinfo['paypassword'])){$return['info']='该会员没有设置支付密码!';return $return;}
                //if(creatpwd($number,'HANCHAO'.$userinfo['salt']) != $userinfo['paypassword']){$return['info']='支付密码错误';return $return;}
                $check_usermoney=true;
                break;
        }
        $data=$this->count_total($postdata);
        if($data['status']==0){$return['msg']=$data['msg']; return $return;}
        if($check_usermoney && $data['total_info']['account_money']>$userinfo['money']){//检查会员余额是否足够支付
            $return['msg']='该会员余额不足!';return $return;
        }
        $order=array();
        $order['order_sn']        = createOrderNo();//订单编号
        $order['type']            = $data['total_info']['order_type'];//订单类型
        $order['uid']             = $userinfo['id']; //会员id（可以为空，用于看是否是会员抵扣）
        $guide = intval($postdata['guide']);
      
        $order['guide']             = $guide; //导购员id（可以为空）
        $order['shop_id']         = $postdata['shop_id'];//商家id
        $order['sa_id'] = $postdata['sid'];
        $order['sign_building']   = $postdata['login_name'];//借用字段记录当前收银员用户名
        $order['shipping_status'] = 4;//配送状态
        $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_fee']         = $data['total_info']['pay_fee'];//支付手续费
        $order['pay_status']      = 1;//支付状态
        $order['goods_amount']    = $data['total_info']['total_price']-$data['total_info']['bonu_money']-$data['total_info']['member_discount']-$data['total_info']['custom_discount'];//订单实际金额(减去折扣的) 没减红包
        $order['goods_allmoney']  = $data['total_info']['total_price'];//商品总价
        $order['pay_amount']      = $data['total_info']['pay_price'];//在线支付的金额
        $order['order_amount']    = $data['total_info']['pay_total_price'];//应付款金额减去折扣和红包 订单总金额
        $order['order_money']     = $data['total_info']['pay_total_price'];//应付款金额减去折扣和红包 订单总金额
        $order['discount']        = $data['total_info']['discount'];//折扣金额
        $order['bonus_money']     = $data['total_info']['bonu_money'];//使用红包金额
        $order['bonus_id']        = $data['total_info']['bonus_id'];//使用红包id
        $order['member_discount'] = $data['total_info']['member_discount'];
        $order['custom_discount'] =$data['total_info']['custom_discount'];
        $order['cash_in_hand']=$data['total_info']['cash_in_hand'];
        $order['delivery_fee']    = 0;//运费
        $order['promot_id']       = $data['total_info']['act_ids'];//店铺下所有商品参与的活动id(以逗号分隔)
        $order['status']          = 1;//订单状态
        $order['used_money']      = $data['total_info']['use_money'];//使用现金或收款码支付的钱
        $order['used_score']      = $data['total_info']['used_score'];//使用积分
        $order['used_score_money']= $data['total_info']['used_score_money'];//使用积分对应金额
        $order['addtime']         = NOW_TIME;
        $order['source']          = 2;//来源0电脑，1手机版，2app
        $order_id=M('OrderInfo')->add($order);
        if(empty($order_id)) {$return['msg']='添加订单失败';return $return;}
        //如果有商品添加商品
        if($data['data']){
            foreach($data['data'] as $vv){
                $order_goods = array();
                $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_number'] = $vv['goods_number'];
                $order_goods['attr_price']   = $vv['attr_price'];
                $order_goods['goods_price']  = $vv['goods_price'];
                $order_goods['supplier_price']  = idtoname($vv['goods_id'],'Goods','shop_price','id',false);
                $order_goods['goods_attr']   = $vv['goods_attr'];//属性
                $order_goods['promot_id']    = 0;//活动id
                $order_goods['shop_id']      = $vv['shop_id'];//店铺id
                $order_goods['suppliers_id'] = $vv['suppliers_id'];//供货商
                $order_goods['addtime']      = NOW_TIME;
                $order_goods['status']       = 0;//商品的发货状态
                $order_goods['is_balance']   = 0;//未结算
                $order_goods['is_sanhuo']    = $vv['is_sanhuo'];//未结算
                M('OrderGoods')->add($order_goods);
            }
        }
        $return=$this->payorder($order_id,$postdata['number'],$postdata['coupon_code']);//去支付
        //print_r($return);exit;
        return $return;
    }
    //支付订单
    public function payorder($order_id,$number,$code=''){
        $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=$this->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['shop_id']          =$order_info['shop_id'];
        $payment_info['user_id']          =$order_info['uid'];
        $payment_info['type']             =$order_info['type'];
        $payment_info['order_sn']         =createOrderNo();
        $payment_info['use_money']        =$order_info['used_money'];//使用现金或收款码支付的钱
        $payment_info['need_pay']         =$order_info['pay_amount'];//还需支付的金额
        $payment_info['use_score']        =$order_info['used_score'];//积分
        $payment_info['use_score_money']  =$order_info['used_score_money'];//积分所抵的钱
        $payment_info['order_total_price']=$order_info['order_money'];//订单实际支付的金额=商品总价+总运费-活动折扣-红包折扣
        $payment_info['payment_id']       =$order_info['payment_id'];//支付方式
        $payment_info['payment_fee']      =$order_info['pay_fee'];//支付手续费
        $payment_info['pay_amount']       =$order_info['pay_amount'];//
        $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['used_score'] >0 && $order_info['uid']){
            account_change($order_info['uid'],-$order_info['used_score'],4,4,'消费支付');
        }
        //余额支付判断以及查询会员信息
        $userinfo=array();
        if($order_info['uid'] && ($pay_code=='HANCHAO' || $order_info['used_score']>0)){
            $map=array();
            $map['id']=$order_info['uid'];
            $userinfo=M('Member')->where($map)->field('money,usepoints')->find();
        }
        $is_payed=0;
        switch($pay_code){
            case 'HANCHAO_XIANJIN'://现金付
                $is_payed=1;
                break;
            case 'CHINAUMS'://银联C扫B接口
                $is_payed=0;
                $return['status']=2;
                $return['pay']=$pay_log_id;
                break;
            case 'CHINAUMSPOS'://银联B扫C接口
                $is_payed=0;
                $return['status']=2;
                $return['pay']=$pay_log_id;
                break;
            case 'MMSCAN'://双乾C扫B接口、B扫C接口
                $is_payed=0;
                $return['status']=2;
                $return['pay']=$pay_log_id;
                break;
            case 'HANCHAO_ALIPAY'://支付宝收款码支付
                $is_payed=1;
                break;
            case 'HANCHAO_WEIXIN'://微信收款码支付
                $is_payed=1;
                break;
            case 'HANCHAO_OTHER'://其他收款码支付
                $is_payed=1;
                break;
            case 'HANCHAO'://余额支付
                if($userinfo['money']>=$order_info['used_money']){
                    account_change($order_info['uid'],-$order_info['used_money'],1,4,'收银商品支付，订单'.$order_info['order_sn']);
                    $is_payed=1;
                }
                break;
            default:
                $return['msg']='支付方式错误!';return $return;
                break;
        }
        $pay_info=array();
        $pay_info['code']=$code;
        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;
            }else{
                $return['msg']=$res['msg'];
                return $return;
            }
        }else{
            $return['msg']='支付失败!';return $return;
        }
        //print_r($return);exit;
        return $return;
    }
    public function testscanpay($pay_log_id='',$number=''){
        $snpay=$this->scan_pay($pay_log_id,$number);//
        return $snpay;
    }
    /**
     * 多种接口的扫码支付共用方法
     * @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)){$return['msg']='参数设置有误！'; return $return;}
        $paycode=strtoupper($pay_info['pay_code']);
        switch($paycode){
            case 'CHINAUMS'://银联C扫B接口
                $pay = new \Common\Vendor\Pay($pay_code,$payconfig);
                $vo = new \Common\Vendor\Pay\PayVo();
                $vo->setFee($pay_info['need_pay'])
                    ->setOrderNo($pay_info['order_sn'])
                    ->setParam($pay_info);
                $RequestForm=$pay->buildRequestForm($vo);
                if($RequestForm['status']){
                    $return['status']=1;
                    $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['info']='付款码错误!';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'];
                //print_r($return);exit;
                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');*///获取辅助码
                $assist_code='HANCHAO_S_ALIPAY';
                //支付接口用到的支付类型
                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['info']='付款码错误!';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);
                if($snpay[0]->qrCode!='00000'){
                    $return['msg']=$snpay[0]->respMess;
                }
                $return['status']=1;
                $return['order_id']=$pay_info['order_id'];
                return $return;
                break;
            default:
                $return['msg']='支付方式错误!';return $return;
                break;
        }
    }
    //结束订单支付
    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();
        if (format_decimal($pay_info['use_money']+$info['money']) >= format_decimal($pay_info['order_total_price'])) {
            $map=array();
            $map['id']=$pay_info['order_id'];
            $order_info=M('OrderInfo')->where($map)->field('bonus_id,shop_id,uid')->find();
            if($order_info['bonus_id']){//核销优惠券
                D('Shop/CouponsGet')->confirm_coupons($order_info['bonus_id'],$order_info['shop_id'],1,$info['code']);
            }
            $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['is_delete'] = 0;
                $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;
                $updatedata['status'] = 3;
                $updatedata['confirm_time'] = NOW_TIME;
                M('OrderInfo')->where($orderwhere)->save($updatedata);
                shops_customer($order_info['uid'],$order_info['shop_id']);//存入门店顾客中间表
                //推送消息
                //PushReadSend($pay_info['order_id']);
                //推送消息end
				if($info['type'] == 2){//充值订单处理
                    $data=calculation($pay_info['order_total_price'],$pay_info['user_id']);
                    account_change($pay_info['user_id'], $data['data']['actual_money'], 1, 1, "会员充值");
                    $ret = give_double_points($pay_info['order_id']);//多倍积分
                    if($ret['points'] != 1){
                        $points=$data['data']['points'];//充值需要变更的会员积分数
                        if($points){account_change($pay_info['user_id'],$points,4,4,"变更积分");}                        
                    }
                    account_change($pay_info['user_id'], $pay_info['order_total_price'], 1, 1, "会员充值（平台入账）",'0',false,3);//平台入账日志
                    account_change($pay_info['user_id'],$pay_info['order_total_price'],7,1,'累计充值');//增加累计充值
                    // 变更会员等级
                    // user_ranks($pay_info['user_id']);
					/*account_change($pay_info['user_id'], $pay_info['order_total_price'], 1, 1, "会员充值");
					$ret = give_double_points($pay_info['order_id']);//多倍积分
					if($ret['points'] != 1)$this->change_member_moneys($pay_info['order_id']);
					account_change($pay_info['user_id'], $pay_info['order_total_price'], 1, 1, "会员充值（平台入账）",'0',false,3);//平台入账日志
					account_change($pay_info['user_id'],$pay_info['order_total_price'],7,1,'累计充值');//增加累计充值
					// 变更会员等级
					user_ranks($pay_info['user_id']);*/
				}else if($info['type'] == 12){
					$map = array();
					$map['order_id'] = intval($pay_info['order_id']);
					$g_id = M("OrderGoods")->where($map)->getField('goods_id');
					$service_info = M('Goods')->field(true)->find($g_id);
					$service_info['contain_service'] = json_decode($service_info['contain_service'],true);
					if($service_info['contain_service']){
						foreach($service_info['contain_service'] as $k=>$v){
							$m_package = array();
							$m_package['uid'] = $pay_info['user_id'];
							$m_package['order_id'] = intval($pay_info['order_id']);
							$m_package['service_sn'] = createOrderNo();
							$m_package['package_id'] = $g_id;
							$m_package['goods_names'] = $k;
							$m_package['service_num'] = $v;
							$m_package['service_type'] = 0;
							$m_package['use_shop'] = 0;
							$m_package['use_num'] = 0;
							$m_package['continued'] = $service_info['continued'];
							$m_package['addtime'] = NOW_TIME;
							$endtime = NOW_TIME + $service_info['continued']*86400;
							$m_package['endtime'] = $endtime;
							$m_package['package_price'] = $pay_info['order_total_price'];
							$m_package['supply_price'] = $pay_info['order_total_price'];
							$m_package['use_time'] = 0;
							M('MemberPackage')->add($m_package);
						}unset($k,$v);
					}
				}else{
					//减库存
					$this->lessstock($pay_info['order_id']);
					if($pay_info['user_id']){
						//user_ranks($pay_info['user_id']);
						$g_points = give_double_points($pay_info['order_id']);//多倍积分
						if(empty($g_points['points']))D('Common/OrderInfo')->change_member_points($pay_info['order_id']);
						else D('Common/OrderInfo')->change_member_points($pay_info['order_id'],0);
					}
				}
				//增加商家未结算金额
				$shop_unsettled = $this->shopbalancechange($pay_info['order_id']);
				if (!$shop_unsettled) {$return['info'] = "增加商户待结算金额失败";return $return;}
                
            }
        }
        $return['status']=1;
        return $return;
    }
    //减库存
    public function lessstock($order_id=''){
        $return=array('status'=>0,'msg'=>'');
        $order_id=intval($order_id);
        if(empty($order_id)){$return['msg'] = "参数错误";return $return;}
        $map=array();
        $map['id']=$order_id;
        $map['pay_status']=3;
        $map['type']=array('in','14,13');
        $order_info=M('OrderInfo')->where($map)->field('order_sn,type,bonus_id,shop_id')->find();
        if(empty($order_info)){$return['msg'] = "订单不存在";return $return;}

        $map=array();
        $map['order_id']=$order_id;
        $map['status']=0;
        $goods=M('OrderGoods')->where($map)->field('goods_id,goods_attr,shop_id,suppliers_id,goods_number')->select();
        if($order_info['type']==13){
            $data=array();
            $data['status']=2;
            M('OrderGoods')->where($map)->save($data);
        }
        foreach($goods as $v){
            if($v['is_sanhuo']==1)continue;
            $map=$data=array();
            $map['shop_id']=$v['shop_id'];
            $map['suppliers_id']=$v['suppliers_id'];
            $map['goods_id']=$v['goods_id'];
            if($v['goods_attr']){
                $shops_goods_attr = unserialize($v['goods_attr']);
                $map['goods_stock']=$shops_goods_attr['key'];
                //$map['goods_stock']=$v['goods_attr'];
            }
            $data['updatetime']=NOW_TIME;
            $data['goods_number']=array('exp','goods_number-'.$v['goods_number']);
            $data['sell_count']=array('exp','sell_count+'.$v['goods_number']);
            M('ShopsGoodsStock')->where($map)->save($data);
        }
        $return['status']=1;
        $return['msg'] = "操作成功";
        return $return;
    }
    //收银结算
    private function shopbalancechange($order_id){
        $map['id']=$order_id;
        $map['pay_status']=3;
        $order_info=$this->where($map)->field('id,order_sn,shop_id,goods_amount,pay_code,assist_code,sa_id')->find();
        if (!$order_info) {return false;}
        $do=TRUE;
        if($order_info['pay_code']=='HANCHAO_XIANJIN' || $order_info['pay_code']=='HANCHAO_AliPay' || $order_info['pay_code']=='HANCHAO_WEIXIN' || $order_info['pay_code']=='HANCHAO_OTHER'){
            $do=FALSE;
        }
        if($order_info['pay_code']=='HANCHAO_XIANJIN'){
            $note='现金';
        }
        if($order_info['pay_code']=='HANCHAO_AliPay' || $order_info['assist_code']=='HANCHAO_S_ALIPAY'){
            $note='支付宝收款';
        }
        if($order_info['pay_code']=='HANCHAO_WEIXIN' || $order_info['assist_code']=='HANCHAO_S_WEIXIN'){
            $note='微信收款';
        }
        if($order_info['pay_code']=='HANCHAO_OTHER'){
            $note='其他收款';
        }
        // shop_balance_log($order_info['shop_id'], $order_info['goods_amount'], 1,3,'订单'.$order_info['order_sn'].'('.$note.')付款,营业额增加', $order_info,'',$do);
        shop_balance_log($order_info['shop_id'], $order_info['goods_amount'], 6,3,'订单'.$order_info['order_sn'].'('.$note.')付款,销售总额增加', $order_info,'',$do);
        return true;
    }
    //根据优惠券id找优惠券的相关信息，计算优惠的金额
    public function count_coupon_discount($coupon_id,$coupon_code,$total_price,$code_type){
        $return=array('status'=>0,'msg'=>'');
        if(empty($coupon_id) && empty($coupon_code)){ $return['msg']='请选择优惠券'; return $return;}
        if($code_type==1){
            $cash_result= D('Shop/CouponsGet')->check($coupon_code,1);//获取优惠券的信息
        }else {
            $cash_result = D('Shop/CouponsGet')->check($coupon_id, 1, 1);//获取优惠券的信息
        }
        if($cash_result['status']==1){
            $cash_info=$cash_result['info'];
            $cash_type=$cash_info['type'];//优惠券的类型
            $cash_discount=$cash_info['discount'];//优惠券的折扣数或是满减金额
            $cash_min=$cash_info['min'];//满足优惠的最小消费金额
            $bonus_id=$cash_info['cash_id'];//优惠券的id
            if($cash_type==1 && $cash_discount>0){//满减
                if(($total_price>0 && $cash_min>0 && $total_price>$cash_min) || ($total_price>0 && $cash_min==0 && $cash_discount<$total_price)){
                    $bonu_money= $cash_discount;//满减的优惠金额
                }
            }
            if($cash_type==2 && $cash_discount>0){//满折
                $cash_discount_money=$total_price*(1-$cash_discount);//计算优惠券满折类型的优惠金额
                if(($total_price>0 && $cash_min>0 && $total_price>$cash_min) || ($total_price>0 && $cash_min==0 && $cash_discount_money<$total_price)){
                    $bonu_money=$cash_discount_money;//
                }
            }
        }
        $return['status']=1;
        $return['coupon_discount']['bonus_id']=$bonus_id;
        $return['coupon_discount']['bonu_money']=$bonu_money;
        return $return;
    }
    //根据会员id找到折扣率，计算会员优惠金额
    public function count_member_discount($uid,$total_price){
        $return=array('status'=>0,'msg'=>'');
        $userinfo=array();
        if($uid){
            $map=array();
            $map['id']=$uid;
            $map['status']=1;
            $map['is_tmp']=0;
            $userinfo=M('Member')->where($map)->field('id,rank_id')->find();
            if(empty($userinfo)) {$return['msg']='该会员不存在';return $return;}
            $map=array();
            $map['id']=$userinfo['rank_id'];
            $map['status']=1;
            $user_discount_rate=M('MemberRank')->where($map)->getField('goods_price');
            if(empty($user_discount_rate)) $user_discount_rate=0;
            //优惠金额
            if($total_price<0){$return['msg']='总金额不能小于0'; return $return;}
            $user_discount=$total_price*(1-$user_discount_rate/100);
            $return['user_discount']=$user_discount;
            $return['status']=1;
        }else{
            $return['msg']='请选择会员';
            return $return;
        }
        return $return;
    }
    public function count_custom_discount($single_type,$single_discount,$total_price){
        $return=array('status'=>1,'msg'=>'');
        if($single_discount>0){
            if($single_type==1){
                $custom_discount=$total_price*(1-$single_discount/10);
            }
            if($single_type==2){
                $custom_discount=$single_discount;
            }
        }
        $return['custom_discount']=$custom_discount;
        return $return;
    }
    public function count_more_score($uid,$card_no){
        $return=array('status'=>0,'msg'=>'');
        $uid=intval($uid);
        if(empty($uid) && empty($code_no)){$return['msg']='请选择会员'; return $return;}
        $map=array();
        if($card_no)$map['username|mobile']=$card_no;
        else{$map['id']=$uid;}
        $info=M('Member')->where($map)->field('id,username,nickname,mobile,rank_id,money,usepoints,header_img')->find();
        if(empty($info) && empty($uid)){//会员卡搜索
            $map=array();
            $map['card_status']=1;
            $map['status']=1;
            $map['card_sn']=$card_no;
            $info=M('Member')->where($map)->field('id,username,nickname,mobile,rank_id,money,usepoints,header_img')->find();
        }
        if(empty($info)){
            $return['msg']='没有查找到该会员';return $return;
        }else{
            $data=array();$huodong='';$huodongnum=0;$huodongmin='';
            $data['uid']=$info['id'];
            $data['nickname']=$info['nickname']?$info['nickname']:$info['username'];if(empty($data['nickname']))$data['nickname']=$info['mobile'];
            $rank_info=idtoname($info['rank_id'],'MemberRank','name,goods_price');
            $data['rankname']=$rank_info['name'];
            if($rank_info['goods_price']<100)$data['user_discount']=floatval($rank_info['goods_price']/10).'折';
            $data['rankrate']=$rank_info['goods_price'];
            $data['money']=$info['money'];
            $data['usepoints']=$info['usepoints'];
            $data['header_img']=$info['header_img']?thumb($info['header_img'],100,100):'';
            $check_double=$this->is_double_points($info['rank_id']);
            if($check_double['status']){
                $huodongnum=$check_double['info']['give_num'];
                $huodongmin=$check_double['info']['money_limit'];
                $huodong='消费';
                if($huodongmin)$huodong.='满'.floatval($huodongmin).'元 ';
                $huodong.=floatval($huodongnum).'倍积分';
            }
            $data['huodong'] =$huodong;    //活动介绍
            $data['huodongnum'] =$huodongnum;//赠送积分倍数
            $data['huodongmin'] =$huodongmin;//最小金额
            $return['status']=1;
            $return['data']=$data;
            return $return;
        }
    }
    public function is_double_points($rand_id=0){
        $return=array('status'=>0,'info'=>'');
        $rand_id=intval($rand_id);
        if(empty($rand_id))return $return;
        $map=array();
        $map['consumption_type']=2;
        $map['give_type']=2;
        $map['status']=1;
        $map['begin_time'] = array('LT',NOW_TIME);
        $map['_string'] ='(end_time >'.NOW_TIME.' or end_time = 0) and (rank_limit=0 or rank_limit='.$rand_id.')';
        $double_num=M('ManypointsRule')->where($map)->field('money_limit,give_num')->find();
        if($double_num['give_num']>1){
            $return['status']=1;
            $return['info']=$double_num;
        }
        return $return;
    }
    // 获取订单列表
    public function lists($paramdata){
        $map=array();
        $pid=idtoname($paramdata['sid'],'ShopsAccount','pid','id',false);
        if($pid > 0){
            $map['sa_id']=intval($paramdata['sid']);
        }else{
//            $mapsa=array();
//            $mapsa['pid'] = $pid;
//            $ids = M('ShopsAccount')->where($mapsa)->getField('id',true);
//            $map['sa_id']=array('in',$ids);
        }
        if($paramdata['current_id'] == 2){
            $map['pay_status']=1;
        }elseif($paramdata['current_id'] == 3){
            $map['pay_status']=3;
            $map['status']=array('not in','7');
        }elseif($paramdata['current_id'] == 4){
            $map['pay_status']=3;
            $map['status']=7;
        }
        // $map['type']=13;
		$map['type']=array('IN','13,15');
        $map['shop_id']=intval($paramdata['shop_id']);
        $pagesize=empty($pagesize)?C('WEB_ARTICLE_PAGE'):$pagesize;
        $list=page_list('OrderInfo',$map,'addtime desc','id,shop_id,pay_code,order_sn,addtime,sa_id,order_amount,pay_status,assist_code,status',$pagesize,'',1);
        foreach($list['list'] as $k=>$v){
            $list['list'][$k]['date']=time_format($v['addtime'],'y-m-d');
            $list['list'][$k]['time']=time_format($v['addtime'],'H:i:s');
			$list['list'][$k]['addtime']=time_format($v['addtime']);
            $list['list'][$k]['order_amount']=format_price($v['order_amount']);
            if($v['assist_code']){
                $list['list'][$k]['pay_name'] = D('App/ShopbalanceLog')->payname($v['assist_code']);
            }else{
                $list['list'][$k]['pay_name']=idtoname($v['pay_code'],'Payment','name','code',false)==false?'':idtoname($v['pay_code'],'Payment','name','code',false);
            }

            $list['list'][$k]['cashier_name']=idtoname($v['sa_id'],'ShopsAccount','name','id',false);
        }
        return $list['list'];

    }
	/**充值赠积分
     * @param $order_id
     * @return bool
     */
    public function change_member_moneys($order_id){
        if(empty($order_id))return false;
		$uid=idtoname($order_id,'OrderInfo','uid');
		$order_sn=idtoname($order_id,'OrderInfo','order_sn');
		
        if(empty($uid))return false;
        $sell_points=C("RECHARGE_SELL_INTEGRAL_RATE");//消费赠消费积分比例
        $order_where=array();
        $order_where['id']=$order_id;
        $order_money=M("OrderInfo")->where($order_where)->getField("order_amount");
        $gift_sell_points=format_decimal($order_money*$sell_points/100,0,2);
        account_change($uid,$gift_sell_points,4,4,"变更积分");
        return true;
    }
	public function package_info($goods_id){
        $return=array('status'=>0,'info'=>'');
        if($goods_id == 0){$return['info']='商品无效!';return $return;}
        $map=array();
        $map['id']=$goods_id;
        $map['status']=1;
        $map['publish_wait']=1;
        $map['is_delete']=0;
        $map['goods_type']=6;
        $lists=M('Goods')->where($map)->field('id,goods_sn,goods_name,goods_type,suppliers_id,supply_price,market_price,supply_price')->select();
        if(empty($lists)){$return['info']='商品无效!';return $return;}
		$goods_list = array();
        foreach($lists as $k=> $v){
			$goods_list[$k]['goods_id']=$v['id'];
            $goods_list[$k]['goods_name']=$v['goods_name'];
            $goods_list[$k]['goods_sn']=$v['goods_sn'];
            $goods_list[$k]['attr_price']=$v['market_price'];//实际价格
            $goods_list[$k]['goods_price']=$v['market_price'];//实际价格
			$goods_list[$k]['goods_number']=1;
        }
        $data=array();
        $data['goods_list'] =$goods_list;
        $return['status']=1;
        $return['info']=$data;
        return $return;
    }
        /**
     * 网上订单列表
     * @param $postdata
     * @return array
     */
    public function order_list($postdata){
        $return=array('status'=>0,'msg'=>'');
        if(empty($postdata['shop_id'])) {$return['msg']='参数错误'; return $return;}
        $map=array();
        $map['shop_id']=$postdata['shop_id'];
        $map['is_delete']=0;
        $map['type']=array('IN','6,12,14,3');
        $map['pay_status']=3;
        switch ($postdata['current_id']) {
            case '1':
                //$map['pay_status']=1;
                $map['status']=array('in','1,2');
                $map['shipping_status']=1;
                break;
            case '2':                
                $map['status']=2;
                $map['shipping_status']=1;
                break;
            case '3':
                $map['status']=2;
                $map['shipping_status']=5;
                break;
            case '4':
                // $map['pay_status']=3;
                // $map['status']=2;
                // $map['shipping_status']=3;
                break;
            case '5':
                $map['status']=7;
                break;
        }
        if($postdata['status']!=0)$map['shipping_status']=$postdata['status'];
        else unset($postdata['status']);
        if($postdata['order_sn']) $map['order_sn']=$postdata['order_sn'];
        else unset($postdata['order_sn']);
        $order_list=page_list('OrderInfo',$map,'id desc');
        if(!empty($order_list['list'])){
            foreach ($order_list['list'] as $k => $v) {
                if($v['type']==3){
                    $order_list['list'][$k]['goods_allmoney']=$v['goods_allmoney']-$v['used_score_money'];
                    $order_list['list'][$k]['order_amount']=$v['order_amount']-$v['used_score_money'];
                    $order_list['list'][$k]['goods_amount']=$v['goods_amount']-$v['used_score_money'];
                    $order_list['list'][$k]['order_money']=$v['order_money']-$v['used_score_money'];
                }
            }
        }
        if(empty($order_list['list'])){$return['status']=2;$return['msg']='暂无数据'; return $return;}
        $return['status']=1;
        $return['data']=$order_list;
        return $return;
    }
}
?>