<?php
/**
 * 门店收银
 * @Copyright (C) 2017 汉潮 All rights reserved.
 * @License http://www.hanchao9999.com
 * @Author xiaogg <xiaogg@sina.cn>
 */
 
namespace Shop\Model;
use Think\Model;
class OrderInfoModel extends Model{
    //添加订单
    public function addorder($postdata){
        $return=array('status'=>0,'info'=>'');
        $pay_type=intval($postdata['pay_type']);
        if(empty($pay_type)){$return['info']='支付方式错误';return $return;}
        $uid=intval($postdata['uid']);
        $cash_jifen=intval($postdata['cash_jifen']);
        $cash_youhuiquan=trim($postdata['cash_youhuiquan']);
        $cart_list=json_decode(htmlspecialchars_decode(trim($postdata['cart_list'])),true);
        if(empty($cart_list)){$return['info']='请先选择商品再支付!';return $return;}
        $userinfo=array();
        if($uid){            
            $map=array();
            $map['id']=$uid;
            $map['status']=1;
            $userinfo=M('Member')->where($map)->field('id,username,nickname,mobile,email,paypassword,money,usepoints,salt')->find();
            if(empty($userinfo)){$return['info']='该会员不存在!';return $return;}
        }
        if($cash_jifen>0 && $cash_jifen>$userinfo['usepoints']){$return['info']='该会员积分不足!';return $return;}
        $check_usermoney=false;
        switch($pay_type){
            case "1"://1 现金支付
            break;
            case "2"://2 扫码支付
            $number=trim($postdata['number']);
            if(empty($number)){$return['info']='请填写付款码!';return $return;} 
            break;
            case "3"://3 余额支付
            if(empty($uid)){$return['info']='请选择余额支付的会员!';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['info']='该会员余额不足!';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;            
            case "4"://4 到付
            if(empty($postdata['add_name'])){$return['info']='请填写联系人!';return $return;} 
            if(empty($postdata['add_mobile'])){$return['info']='请填写联系电话!';return $return;} 
            if(empty($postdata['add_address'])){$return['info']='请填写详细地址!';return $return;} 
            if(!empty($postdata['user_money'])){
                if(empty($userinfo['money'])){$return['info']='该会员余额不足!';return $return;}     
                $check_usermoney=true;
            }
            if($postdata['psfs']!=0 && empty($postdata['user_money'])){
                $return['info']='使用第三方配送仅支持会员余额支付!';return $return;
            }
            if($postdata['psfs'] && (empty($postdata['xpoint']) || empty($postdata['ypoint']))){
                $return['info']='请先选择配送坐标!';return $return;
            }
            break;
        }
        //开始处理商品
        $goods_list=$goodsids=array();
        
        $cashier_code=C('CASHIER_CODE');//散货标识
        //检测库存
        foreach($cart_list as $k=>$v){
            $karr=explode('-',$k);$is_sanhuo=0;
            $goods_id=$karr[0];
            if($cashier_code && strpos('*'.$goods_id,$cashier_code)==1){$goods_id=substr($goods_id,count($cashier_code));$is_sanhuo=1;}
            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);}
                $check_stock=D('ShopsGoodsStock')->checkstock($goods_id,$goods_attr_key,$postdata['shop_id'],$v['goods_num']);
                if(empty($check_stock)){                    
                    $goods_name=idtoname($goods_id,'Goods','goods_name');
                    if(!empty($goods_attr['name']))$goods_name.=$goods_attr['name'];
                    $return['info']=$goods_name.'库存不足';return $return;
                }
            }
            
            $goodsids[]=$goods_id;
            $goods_list[$k]=array(
                'goods_id'=> $goods_id,
                'goods_number'=> $v['goods_num'],
                'goods_attr'=> serialize($goods_attr),
                'is_sanhuo'=> $is_sanhuo,
            );
        }
        if(empty($goodsids)){$return['info']='商品无效!';return $return;}
        $postdata['goodsids']=$goodsids;
        $postdata['goods_list']=$goods_list;
        $data=$this->count_total($postdata);
        if($check_usermoney && $data['total_info']['account_money']>$userinfo['money']){//检查会员余额是否足够支付
            $return['info']='该会员余额不足!';return $return;
        }
        $source=intval($postdata['source']);
        $order=array();
        $order['order_sn']        = createOrderNo();
        $order['type']            = $data['total_info']['order_type'];
        $order['uid']             = $userinfo['id'];
        $order['consignee']       = $userinfo['nickname']?$userinfo['nickname']:$userinfo['username'];//收货人
        $order['mobile']          = $userinfo['mobile'];//电话
        $order['email']           = $userinfo['email'];//邮件
        $order['shop_id']         = $postdata['shop_id'];//商家id
        $order['sign_building']   = $postdata['login_name'];//借用字段记录当前收银员用户名
        $order['shipping_status'] = 4;//配送状态
        $order['pay_code']        = $data['total_info']['payment_info']['code'];//支付方式id
        $order['payment_id']      = $data['total_info']['payment_info']['id'];//支付方式id
        $order['pay_fee']         = $data['total_info']['pay_fee'];//支付方式id
        $order['pay_status']      = 1;//支付状态
        $order['goods_amount']    = $data['total_info']['total_price']-$data['total_info']['bonu_money'];//商品实际金额(减去折扣的) 没减红包
        $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']['active_money'];//折扣金额
        $order['bonus_money']     = $data['total_info']['bonu_money'];//使用红包金额
        $order['bonus_id']        = $data['total_info']['bonus_id'];//使用红包id
        $order['delivery_fee']    = 0;//运费
        $order['promot_id']       = $data['total_info']['act_ids'];//店铺下所有商品参与的活动id(以逗号分隔)
        $order['status']          = 1;//订单状态
        $order['used_money']      = $data['total_info']['account_money'];//使用余额
        $order['used_score']      = $data['total_info']['use_score'];//使用积分
        $order['used_score_money']= $data['total_info']['use_score_money'];//使用积分对应金额
        $order['addtime']         = NOW_TIME;
        $order['source']          = $source;//来源0电脑，1手机版，2app
        if($pay_type==4){//到付
            $order['consignee']  = $postdata['add_name'];//收货人的姓名 
            $order['province']   = $postdata['province'];//收货人的省份 
            $order['city']       = $postdata['city_id'];//收货人的城市 
            $order['district']   = $postdata['district'];//收货人的地区 
            $order['address']    = $postdata['add_address'];//详细地址 
            $order['mobile']     = $postdata['add_mobile'];//收货人手机 
            $order['best_time']  = $postdata['add_time'];//最佳送货时间 
            $order['distribute'] = $postdata['psfs'];//配送物流
            $order['xpoint']     = $postdata['xpoint'];//配送经度
            $order['ypoint']     = $postdata['ypoint'];//配送纬度 
        }
        $order_id=M('OrderInfo')->add($order);
        if(empty($order_id)){$return['info']='添加订单失败!';return $return;}
        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);
        }
        if($pay_type==4 && empty($postdata['user_money'])){
            $return['status']=1;
            $return['data']=$order_id;
            $return['order_sn']=$order['order_sn'].'(到付)';
            $return['printhtml']=$this->printhtml($order_id);//打印
        }else{
            $return=$this->payorder($order_id,$number,$postdata['code']);//去支付
        }
        return $return;        
    }
    //支付订单
    public function payorder($order_id,$number='',$code=''){
        $return=array('status'=>0,'info'=>'');
        if(empty($order_id)){$return['info']='订单信息错误!';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['info']='订单信息错误!';return $return;}
        
        $pay_code=strtoupper($order_info['pay_code']);
        $payment_info=array();
        $payment_info['order_id']         =$order_id;
        $payment_info['user_id']          =$order_info['uid'];
        $payment_info['shop_id']          =$order_info['shop_id'];
        $payment_info['type']             =$order_info['order_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']       =0;//
        $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['info']='支付单信息错误!';return $return;}
        $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;  
        if($order_info['uid'] && $order_info['used_score']){
            account_change($order_info['uid'],-$order_info['used_score'],4,4,'收银商品支付(订单:'.$order_info['order_sn'].')');
        }
        switch($pay_code){
            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;
            case 'HANCHAO_XIANJIN'://现金付
                $is_payed=1;
            break;
            case 'WEIXINMICROPAY'://微信刷卡支付
                $return['pay']=$pay_log_id;
                $return['status']=2;
            break;
            case 'ALIBARPAY'://支付宝当面付
            $return['info']='暂未开通支付宝当面付!';return $return;
                $return['pay']=$pay_log_id;
                $return['status']=2;
            break;
            default:
                $return['info']='支付方式错误!';return $return;
            break;
        }
        if($order_info['bonus_id']){//核销优惠券
            D('CouponsGet')->confirm_coupons($order_info['bonus_id'],$order_info['shop_id'],1,$code);
        }
        $pay_info=array();
        if($return['status']==2 && $is_payed==0){
            $snpay=$this->snpay($pay_log_id,$number);
            if($snpay['status']==0)return $snpay;
            $is_payed=1;
            $pay_info=$snpay['info'];
        }
        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['data']=$order_id;
                $return['order_sn']=$order_info['order_sn'];
                $printhtml=$this->printhtml($order_id);//打印
                if(is_array($printhtml)){
                    $return['printstatus']=1;
                    $return['printhtml']=$printhtml['info'];
                }else{
                    $return['printstatus']=0;
                    $return['printhtml']=$printhtml;
                }
                
                if(C('DIS_TRIBUTE')==1 && $order_info['distribute']){
                    $disdata=$order_info;
                    $disdata['order_id']=$order_id;
                    $disdata['wuliu']=$order_info['distribute'];
                    $req=D('Common/Distribute')->add_order($disdata);
                    if($req['status'] == 1){
                        $save_data=array();
                        $save_data['accept_time'] = NOW_TIME;
                        M('OrderInfo')->where('id='.$order_id)->save($save_data);
                    }else{$return['status']=0;
                        $return['info'] = $req['msg'];return $return;
                    }
                }
                return $return;
            }else{
                $return['info']=$res['info'];
                return $return;
            }
        }else{
            $return['info']='支付失败!';return $return;
        }
    }
    private function printhtml($order_id){
        $order_id=intval($order_id);
        if(empty($order_id))return false;
        $map=array();
        $map['id']=$order_id;
        $map['type']=13;
        $map['pay_status']=3;
        $map['is_delete']=0;
        $order=$this->where($map)->field(true)->find();
        if(empty($order) || empty($order['shop_id']))return false;
        $order['choujiang']=U('Mobile/Member/receipt_draw',array('order_id'=>$order['id']),true,true);
        $map=array();
        $map['order_id']=$order_id;
        $goods=M('OrderGoods')->where($map)->field(true)->cache(true)->select();
        
        $map=array();
        $map['id']=$order['shop_id'];
        $shop=M('Shops')->where($map)->field('name,contacts,phone,contacts_phone,qq,weixin,address,machine_code,print_template')->cache(true)->find();
        
        $yunprint=C('PRINT_APPID');//云打印
        if($yunprint && $shop['machine_code']){
            $return=array('status'=>0,'info'=>'');
            $order['goods_amount']=format_price($order['goods_amount']);
            $order['order_amount']=format_price($order['order_amount']);//订单价格
            $order['delivery_fee']=format_price($order['delivery_fee']);//配送费
            $order['discount']=format_price($order['discount']);            
            $order['addtime']=time_format($order['addtime']);
            $order['all_num']=0;
            $order['num']=count($goods); 
            $order['location_name']=$shop['name'];
            foreach($shop as $k=>$v){
               $order['shop_'.$k] =$v;
            }
            $order['list']=$goods;
            foreach ($order['list'] as $k => $v) {
              $order['list'][$k]['goods_price']=format_price($v['goods_price']);
              $order['all_num']+=$v['goods_number'];
            }
            //打印模板
            $tplhtml=$locationinfo['print_template'];
            //if(empty($tplhtml))$tplhtml=C('PRINT_TEMPLATE');
            $tplhtml=trim(htmlspecialchars_decode($tplhtml));
            if(empty($tplhtml)){$return['info']='云打印失败(打印模板未设置)';return $return;}
            $View= new \Common\Vendor\TplView();
            $View->assign('time',time_format(NOW_TIME));
            $View->assign($order);
            $View->assign('WEB_SITE_NAME',$WEB_SITE_NAME);
            $content=$View->fetch('',$tplhtml);       
            return doPrint($shop['machine_code'],$content,$order['order_sn']);            
        }else{
            $tpl_print='./Application/Shop/View/'.get_default_theme('Shop').'/Cashier/tpl_print.html';
            $html=oaofile($tpl_print);
            if($html){
                $order['addtime_format']=time_format($order['addtime'],"Y/m/d H:i:s");
                $View= new \Common\Vendor\TplView();
                $View->assign('order',$order);
                $View->assign('goods',$goods);
                $View->assign('shop',$shop);
                $content=$View->fetch('',$html);
            }
            return $content;
        }
        
        
    }
    //扫码支付
    private function snpay($paylod_id='',$number=''){
        $paylod_id=intval($paylod_id);
        $return=array('status'=>0,'info'=>'');
        if(empty($paylod_id)){$return['info']='支付单信息错误!';return $return;}
        if(empty($number)){$return['info']='付款码错误!';return $return;}
		$where['id']=$paylod_id;
        $where['is_paid']=array('neq',1);
		$pay_info = M('PayLog')->where($where)->field(true)->find();
        $pay_code=$pay_info['pay_code'];
        if(empty($pay_info['order_sn'])){$return['info']='支付单信息错误!';return $return;}
		$title_name=$pay_info['order_sn']."扫码支付";
        $p_map=array();
        $p_map['status']=1;
        $p_map['code']=$pay_code;
		$payconfig=M('Payment')->where($p_map)->field(true)->find();
		if(empty($pay_code)){$return['info']='支付方式付款码错误!';return $return;}
		$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);
        return $RequestForm;
    }
    //结束订单支付
    private function endorder($info){        
        $return=array('status'=>0,'info'=>'');
        if(empty($info)){$return['info']='支付单信息错误!';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'] + $pay_info['use_score_money'] + $info['money']) >= format_decimal($pay_info['order_total_price'])) {            
            $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'];//线上支付
                $updatedata['pay_time'] = NOW_TIME;
                $updatedata['status'] = 3;
				$updatedata['confirm_time'] = NOW_TIME;
                M('OrderInfo')->where($orderwhere)->save($updatedata);  
                //减库存
                $this->lessstock($pay_info['order_id']);
                //增加商家未结算金额
				$shop_unsettled = $this->shopbalancechange($pay_info['order_id']);
				if (!$shop_unsettled) {$return['info'] = "增加商户待结算金额失败";return $return;}
				//会员待分成记录
				if(C('EXTENSION_SETTING')){$affiliate = affiliate($pay_info['order_id']);}
				if($pay_info['user_id'] && $info['money']>0){account_change($pay_info['user_id'],$info['money'], 1, 1, "会员支付（平台入账）",'0',false,3);}//平台入账日志
                //消费赠积分
                if($pay_info['user_id']>0){
                    $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);
                }
            }
        }
        $return['status']=1;
        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')->find();
        if (!$order_info) {return false;}
		$price_info=get_balance_price($order_id);//获取订单的结算价
		// shop_balance_log($order_info['shop_id'], $price_info['price'], 1,3,'订单'.$order_info['order_sn'].'付款,营业额增加', $order_info);
		shop_balance_log($order_info['shop_id'], $price_info['price'], 6,3,'订单'.$order_info['order_sn'].'付款,销售总额增加', $order_info);
        return true;
    }
    //减库存
    public function lessstock($order_id=''){
        $return=array('status'=>0,'info'=>'');
        $order_id=intval($order_id);
        if(empty($order_id)){$return['info'] = "参数错误";return $return;}
        $map=array();
        $map['id']=$order_id;
        $map['pay_status']=3;
        $map['type']=array('in','14,13,6,3');
        $order_info=M('OrderInfo')->where($map)->field('order_sn,type,bonus_id,shop_id')->find();
        if(empty($order_info)){$return['info'] = "订单不存在";return $return;}
        
        $map=array();
        $map['order_id']=$order_id;
        $map['status']=array('in','0,1');
        $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=$type_map=array();
            $map['shop_id']=$v['shop_id'];
            $map['goods_id']=$v['goods_id'];
			$type_map['id'] = $v['goods_id'];
            $sale_type = M('Goods')->where($type_map)->getField('sale_type');
            if($sale_type == 1){//组合商品
                $this->group_goods($map,$v,$order_id);
            }else{
                $this->reduce_stock($map,$v,$order_id);
            }

        }
        $return['status']=1;
        $return['info'] = "操作成功";
        return $return;
    }
	//取消订单加库存
    public function addstock($order_id=''){
        $return=array('status'=>0,'info'=>'');
        $order_id=intval($order_id);
        if(empty($order_id)){$return['info'] = "参数错误";return $return;}
        $map=array();
        $map['id']=$order_id;
        $map['pay_status']=3;
        $map['type']=array('in','14,13,6');
        $order_info=M('OrderInfo')->where($map)->field('order_sn,type,bonus_id,shop_id')->find();
        if(empty($order_info)){$return['info'] = "订单不存在";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();
        foreach($goods as $v){
            $map=$data=array();
            $map['shop_id']=$v['shop_id'];
            $map['goods_id']=$v['goods_id'];
            $sale_type = idtoname($v['goods_id'],'Goods','sale_type');
            if($sale_type == 1){//组合商品
                $this->add_group_goods($map,$v,$order_id,0);
            }else{
                $this->add_stock($map,$v,$order_id);
            }

        }
        $return['status']=1;
        $return['info'] = "操作成功";
        return $return;
    }
    /**
     * 获取商品详情
     * @param $uid
     * @param array $goods_list=
     * array (
          '245-' => 
          array (
            'goods_id' => '245',
            'goods_number' => '1',
            'goods_attr' => '',
            'is_sanhuo' => 0,
          ),
          '246-' => 
          array (
            'goods_id' => '246',
            'goods_number' => '1',
            'goods_attr' => '',
            'is_sanhuo' => 0,
          ),
        )
     */
    public function goods_info($goods_list,$uid=0){
        $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'];
        }
        if(empty($goodsids)){$return['info']='商品无效!';return $return;}
        $map=array();
        $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,market_price,supply_price')->select();
        if(empty($lists)){$return['info']='商品无效!';return $return;}
        $new_lists=array();
        foreach($lists as $v){$new_lists[$v['id']]=$v;}
        $uid=intval($uid);$total_price=0;$goods_amount=0;$member_discount=0;
        foreach($goods_list as $k=> $v){
            $goods_info=$new_lists[$v['goods_id']];
            if(empty($goods_info)){unset($goods_list[$k]);continue;}
            $realprice=$this->getgoodsprice($goods_info,$uid,$v['goods_attr']);
            $goods_list[$k]['goods_name']=$goods_info['goods_name'];
            $goods_list[$k]['goods_sn']=$goods_info['goods_sn'];
            $goods_list[$k]['attr_price']=$goods_info['market_price'];//实际价格
            $goods_list[$k]['goods_price']=$realprice;//实际价格
            $goods_list[$k]['shop_id']=$postdata['shop_id'];
            $goods_list[$k]['suppliers_id']=$goods_info['suppliers_id'];
            $goods_list[$k]['is_sanhuo']=$v['is_sanhuo'];
            
            $total_price+=$realprice*$v['goods_number'];
            $goods_amount+=$goods_info['market_price']*$v['goods_number'];
        }
        $member_discount=format_decimal($goods_amount-$total_price);
        $data=array();
        //$data['goodsids']   =$goodsids;
        $data['goods_list'] =$goods_list;
        $data['total_price']=$total_price;
        $data['goods_amount']=$goods_amount;
        $data['member_discount']=$member_discount;
        $return['status']=1;
        $return['info']=$data;
        return $return;
    }
    //格式商品数据获取 订单的总金额等数据
    public function count_total($postdata){
        $return=array('status'=>0,'info'=>'');  
        $goods_list=$postdata['goods_list'];        
        if(empty($goods_list)){$return['info']='商品无效!';return $return;}
        $uid=intval($postdata['uid']);
        
        
        $total_price=$pay_price=$pay_fee=$use_score=$use_score_money=$bonu_money=$active_money=$account_money=$bonus_id='0';
        $payment_info=array();$address='';
        
        $result=$this->goods_info($goods_list,$uid);
        if($result['status']==0)return $result;
        $goods_list=$result['info']['goods_list'];
        $total_price=$result['info']['total_price'];
        $cash_jifen=intval($postdata['cash_jifen']);
        $cash_youhuiquan=trim($postdata['cash_youhuiquan']);
        $pay_type=intval($postdata['pay_type']);
        if($cash_jifen>0 && $uid){
            $use_score=$cash_jifen;
            $use_score_money=format_decimal($use_score*(C('WEB_INTEGRAL_RATIO')/100));//积分抵扣钱
        }
        if($cash_youhuiquan){
            $cash_result= D('CouponsGet')->check($cash_youhuiquan,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'];
                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;
                    }
                }
                
            }
        }
        
        $pay_total_price=$total_price+$pay_fee-$use_score_money-$active_money-$bonu_money;
        switch($pay_type){
            case "1"://1 现金支付
            $payment_info=array('id'=>'0','code'=>'HANCHAO_XIANJIN','name'=>'现金支付');            
            $account_money=$pay_total_price;
            break;
            case "2"://2 扫码支付
            $pay_price=$pay_total_price;
            $pay_first=substr($postdata['number'],0,1);
            if($pay_first==1){//微信
                $payment_info=idtoname('Weixinmicropay','Payment','*','code');
            }
            if($pay_first==2){//支付宝
                $payment_info=idtoname('Alibarpay','Payment','*','code');
            }
            break;
            case "3"://3 余额支付
            $account_money=$pay_total_price;
            $paymentid=idtoname('Hanchao','Payment','id','code');
            $payment_info=array('id'=>$paymentid,'code'=>'HANCHAO','name'=>'余额支付');  
            break;
            
            case "4"://3 到付
            $account_money=$pay_total_price;
            if(!empty($postdata['user_money'])){
                $paymentid=idtoname('Hanchao','Payment','id','code');
                $payment_info=array('id'=>$paymentid,'code'=>'HANCHAO','name'=>'余额支付'); 
            }else{
                $payment_info=array('id'=>'0','code'=>'HANCHAO_XIANJIN','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),//手续费
			'use_score'=>$use_score,//使用的积分
			'use_score_money'=>$use_score_money,//积分抵扣的价格
			'bonu_money'=>$bonu_money,//红包/优惠抵扣的价格
			'active_money'=>$active_money,//活动优惠
			'account_money'=>$account_money,//使用余额
			'payment_info'=>$payment_info,//使网银支付信息
            'pay_total_price'=>$pay_total_price	,//订单实际支付的金额=商品总价+总运费-活动折扣-红包折扣
			'address_info'=>$address,//配送地址
            'bonus_id'=>$bonus_id,//红包 ID
            'act_ids'=>'',//参与的活动ID;
			'order_type'=>13,//订单类型
		);
        return $return;        
    }    
    /**
     * 获取实际商品价格
     */
    public function getgoodsprice($goods_info,$uid='',$goods_attr='',$cache=false){
        if(empty($goods_info))return 0;
        $price=$goods_info['market_price'];
        if($goods_attr){
            $map=array();
            $map['goods_id']=$goods_info['id'];
            $map['attr_key']=$goods_attr;
            $attrprice=M('GoodsAttrStock')->where($map)->getField('attr_price');
            if($attrprice>0)$price=$attrprice;
        }
        $uid=intval($uid);
        if($uid){
            $map=array();
            $map['m.status']=1;
            $map['m.id']=$uid;
            $rank_rate=M('Member')->alias('m')->join('__MEMBER_RANK__ r on m.rank_id=r.id')->where($map)->cache($cache)->getField('r.goods_price');
            $rank_rate=floatval($rank_rate);
            if($rank_rate>0){
                $price=$price*$rank_rate/100;
            }
        }
        return format_decimal($price);
    }
    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 returnordergoods($postdata){        
        $return=array('status'=>0,'info'=>'');
        if(empty($postdata['order_id'])){$return['info']='订单ID错误';return $return;}
        if(empty($postdata['goods'])){$return['info']='请选择要退货的商品';return $return;}
        $refund_scores=intval($postdata['tuiorderjifen']);
        $refund_money=floatval($postdata['tuigoodsmoney']);
        $order_id=intval($postdata['order_id']);
        if(empty($refund_money) || $refund_money<=0){$return['info']='退款金额错误';return $return;}
        $goods=array_filter(json_decode(htmlspecialchars_decode(trim($postdata['goods'])),true));
        if(empty($goods)){$return['info']='请选择要退货的商品';return $return;}
        $map=array();
        $map['id']=$order_id;
        $map['pay_status']=3;
        $order_info=$this->where($map)->field(true)->find();
        if(empty($order_info)){$return['info']='请选择要退货的订单';return $return;}
        if($refund_scores<0 || ($refund_scores>0 && $refund_scores>$order_info['used_score'])){
            $return['info']='订单积分不满足退货积分要求!';return $return;
        }
        if($refund_money>$order_info['goods_allmoney']){
            $return['info']='退款金额超过商品总金额不能退款!';return $return;
        }
        $org_id=array_keys($goods);
        $str_orgids=implode(',',$org_id);
        $map=array();
        $map['order_id']=$order_id;
        $map['id']=array('in',$org_id);
        $map['status']=array('in','2,6');
        $ordergoods=M('OrderGoods')->where($map)->field(true)->select();$goods_info=array();
        if(empty($ordergoods)){$return['info']='请选择要退货的商品';return $return;}
        foreach($ordergoods as $k=>$v){
            if($v['goods_number']<$goods[$v['id']]){
                $return['info']=$v['goods_name'].'退货数量错误';return $return;
            }
            $goods_info[f]['goods_id']=$v['goods_id'];
            $goods_info[$i]['number']=$goods[$v['id']];
        }
        //修改order_goods状态
        foreach($ordergoods as $k=>$v){
            $map=$data=array();
            $map['id']=$v['id'];
            if($v['goods_number']==$goods[$v['id']]){//全退
                $data['status']=4;//4已退货已退款                
            }else{//部分退
                $data['status']=6;//6部分退货 
                $data['original_num']=$v['goods_number'];
                $data['goods_number']=$v['goods_number']-$goods[$v['id']];
            }
            M('OrderGoods')->where($map)->save($data);
            //增加库存
            $map=$data=array();
            $map['shop_id']=$order_info['shop_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); 
        }
        
        //修改order_info状态
        $map=array();
        $map['order_id']=$order_id;
        $map['status']=array('in','2,6');
        $check=M('OrderGoods')->where($map)->count();
        
        $map=$data=array();
        $map['id']=$order_id;
        if(empty($check)){
            $data['status']=9; //9已退货 
        }//goods_amount	goods_allmoney	order_amount	order_money
        $data['goods_amount']=array('exp','goods_amount-'.$refund_money);
        $data['goods_allmoney']=array('exp','goods_allmoney-'.$refund_money);
        $data['order_amount']=array('exp','order_amount-'.$refund_money);
        $data['order_money']=array('exp','order_money-'.$refund_money);
        if($refund_scores && $order_info['used_score']>0)$data['used_score']=array('exp','used_score-'.$refund_money);
        if(str_exists(strtolower($order_info['pay_code']),'hanchao') && $refund_money && $order_info['used_money']>0)$data['used_money']=array('exp','used_money-'.$refund_money);
        $this->where($map)->save($data);
        
        
        $refund_data=array();
        $refund_data['order_id']=$order_id;
		$refund_data['order_goods']=$str_orgids;
		$refund_data['money']=$refund_money;
		$refund_data['refund_money']=$refund_money;
		$refund_data['refund_scores']=$refund_scores;
		$refund_data['refund_web']=0;
		$refund_data['payment_id']=$order_info['payment_id'];
		$refund_data['payment_code']=$order_info['pay_code'];
		$refund_data['reason']='收银退货';
		$refund_data['addtime']=$refund_data['update_time']=NOW_TIME;
		$refund_data['uid']=$order_info['uid'];
        $refund_data['type']=0;
        $refund_data['status']=1;
		$refund_data['shop_id']=$order_info['shop_id'];
		$result=M("RefundOrder")->add($refund_data);
        
        
        //添加退货单
        $add['org_id']=$str_orgids;
        $add['uid']=$order_info['uid'];
        $add['shop_id']=$order_info['shop_id'];
        $add['order_id']=$order_id;
        $add['rorder_id']=$result;
        $add['goods_info']=serialize($goods_info);
        $add['reason']='收银退货';
        $add['money']=$refund_money;
		$add['add_time']=$add['update_time']=NOW_TIME;
        $add['type']=0;
        $add['status']=1;
        $res=M('ReturnGoods')->add($add);
        
        //退现金
        if($order_info['pay_code']!='HANCHAO_XIANJIN' && $order_info['uid']){
            if($refund_money>0)account_change($order_info['uid'],-$refund_money,1,4,'收银订单退货'.$order_info['order_sn']);
            if($refund_scores>0)account_change($order_info['uid'],-$refund_scores,4,4,'收银订单退货'.$order_info['order_sn']);
        }
        
        //作废支付单
        $p_where=$o_data=array();
        $p_where['is_delete'] = 0;
        $p_where['order_id'] = array("like", "%," . $order_id. ",%");
        $o_data['is_delete']=1;
        M("PayLog")->where($p_where)->save($o_data);       
                
        //取消订单分成
        $where=$data=array();
        $where['order_id']=$order_id;
        $data['is_separate']=2;
        M("AffiliateLog")->where($where)->save($data);
        //已分成订单退还
        $map=array();        
        $map['order_id']=$order_id;
        $map['is_separate']=1;
        $afflist=M("AffiliateLog")->where($map)->field('uid,money,point')->select();
        if($afflist){
            foreach($afflist as $v){                
                if($v['money']>0)account_change($v['uid'],-$v['money'],1,4,'收银订单退货,退回分成'.$order_info['order_sn']);
                if($v['point']>0)account_change($v['uid'],-$v['point'],4,4,'收银订单退货,退回分成'.$order_info['order_sn']);
            }
        }        
        //减少店铺待结算金额
        // shop_balance_log($order_info['shop_id'], -$refund_money, 2,3,'收银订单' . $order_info['order_sn'] . '退款,未结算总额减少', $order_info);
        shop_balance_log($order_info['shop_id'], -$refund_money, 6,3,'收银订单' . $order_info['order_sn'] . '退款,销售总额减少', $order_info);
        $return['status']=1;
        $return['info']='成功退款:'.$refund_money;
        if($refund_scores>0)$return['info'].=' 积分:'.$refund_scores;
        return $return;
    }
    public function group_goods($map,$v,$order_id){//组合商品减库存
        $mapg=array();
        $mapg['goodsid'] = $v['goods_id'];
        $group = M('GroupGoods')->where($mapg)->select();
        $info=array();
        foreach($group as $kk=>$vv){
            $info['goods_attr']=$vv['attr_key'];
            $info['goods_number'] = $v['goods_number'] * $vv['ratio'];
            $map['goods_id'] = $vv['linkid'];
            $this->reduce_stock($map,$info,$order_id,1);
        }
    }
	public function add_group_goods($map,$v,$order_id,$tui){//组合商品加库存
        $mapg=array();
        $mapg['goodsid'] = $v['goods_id'];
        $group = M('GroupGoods')->where($mapg)->select();
        $info=array();
        foreach($group as $kk=>$vv){
            $info['goods_attr']=$vv['attr_key'];
            $info['goods_number'] = $v['goods_number'] * $vv['ratio'];
            $map['goods_id'] = $vv['linkid'];
            $this->add_stock($map,$info,$order_id,1,$tui);
        }
    }
    public function reduce_stock($map,$v,$order_id,$type=0){//减库存
        if($v['goods_attr'] && $type==0){
            $shops_goods_attr = unserialize($v['goods_attr']);
            $map['goods_stock']=$shops_goods_attr['key'];
        }
        if($v['goods_attr'] && $type==1){
            $map['goods_stock']=$v['goods_attr'];
        }
        $map['goods_stock']=$map['goods_stock']?$map['goods_stock']:0;
        $pre_num=M('ShopsGoodsStock')->where($map)->getField('goods_number');
        if(empty($pre_num)){
            unset($map['goods_stock']);
            $pre_info=M('ShopsGoodsStock')->where($map)->order('goods_number desc')->field('id,goods_number')->find();
            if($pre_info['id']){
                $map['id']=$pre_info['id'];
                $pre_num=$pre_info['goods_number'];
            }
        }
        $order_sn=idtoname($order_id,'OrderInfo','order_sn');
        $attr_key=empty($map['goods_stock'])?'':$map['goods_stock'];
        if($pre_num<$v['goods_number']){

            $g_map=array();
            $g_map['gp.sid']=$map['goods_id'];
            if($map['goods_stock']){
                $g_map['s.goods_stock']=$map['goods_stock'];
                $g_map['gp.sattr_key']=$map['goods_id'].'-'.$map['goods_stock'];
            }
            $p_info=M('GoodsPackage')->alias('gp')->where($g_map)->JOIN('LEFT JOIN __SHOPS_GOODS_STOCK__ s ON s.goods_id=gp.pid')->field('s.goods_number,gp.ratio,gp.pid')->find();
            if($p_info){
                $big_num = ceil(($v['goods_number']-$pre_num)/$p_info['ratio']);//需要大单位商品的量
                $mapb=$datab=array();
                $mapb['goods_id']=$p_info['pid'];
                $mapb['shop_id']=$map['shop_id'];
                if($map['goods_stock'])$mapb['goods_stock']=$map['goods_stock'];
                $datab['updatetime']=NOW_TIME;
                $datab['goods_number']=array('exp','goods_number-'.$big_num);
                $resb=M('ShopsGoodsStock')->where($mapb)->save($datab);
                if($resb){
                    $desc='大单位拆包';
                    change_stock_log($map['shop_id'],$order_id,$p_info['goods_number'],$p_info['pid'],$big_num,1,$desc,10,$attr_key);
                }
                $datas=array();
                $datas['updatetime']=NOW_TIME;
                $s_num=$big_num*$p_info['ratio'];
                $datas['goods_number']=array('exp','goods_number+'.$s_num);
                $ress=M('ShopsGoodsStock')->where($map)->save($datas);
                if($ress){
                    $desc='小单位入库';
                    change_stock_log($map['shop_id'],$order_id,$pre_num,$map['goods_id'],$big_num*$p_info['ratio'],0,$desc,10,$attr_key);
                }
            }
        }
        $data['updatetime']=NOW_TIME;
        $data['goods_number']=array('exp','goods_number-'.$v['goods_number']);
        $data['sell_count']=array('exp','sell_count+'.$v['goods_number']);
        $res=M('ShopsGoodsStock')->where($map)->save($data);

        if($res){
            //增加存库存变更日志
            $desc='订单'.$order_sn.'下单成功扣库存';
            change_stock_log($map['shop_id'],$order_id,$pre_num+$s_num,$map['goods_id'],$v['goods_number'],1,$desc,1,$attr_key);
        }
    }    
    /* 加库存 bxn
    * @param $type  0直接传属性组合值，1传的值为order_goods表里面的属性    
    * @param $tui 0 取消订单加库存 1退货加库存
    */
    public function add_stock($map,$v,$order_id,$type=0,$tui=0){//加库存
        if($v['goods_attr'] && $type==0){
            $shops_goods_attr = unserialize($v['goods_attr']);
            $map['goods_stock']=$shops_goods_attr['key'];
        }
        if($v['goods_attr'] && $type==1){
            $map['goods_stock']=$v['goods_attr'];
        }
        $pre_num=M('ShopsGoodsStock')->where($map)->getField('goods_number');
        $data['updatetime']=NOW_TIME;
        $data['goods_number']=array('exp','goods_number+'.$v['goods_number']);
        $data['sell_count']=array('exp','sell_count-'.$v['goods_number']);
        $res=M('ShopsGoodsStock')->where($map)->save($data);
        $order_sn=idtoname($order_id,'OrderInfo','order_sn');
        if($res){
            if($tui==1){
                $desc="订单".$order_sn."退货库存增加";
            }else{
                $desc="订单".$order_sn."取消库存增加";
            }
            $attr_key=empty($map['goods_stock'])?'':$map['goods_stock'];
            change_stock_log($map['shop_id'],$order_id,$pre_num,$map['goods_id'],$v['goods_number'],0,$desc,11,$attr_key);
        }
    }
}
?>