<?php
namespace wstshop\common\model;
use think\Db;
/**
 * ============================================================================
 * WSTShop网上商店
 * 版权所有 2016-2066 广州商淘信息科技有限公司，并保留所有权利。
 * 官网地址:http://www.wstshop.net
 * 交流社区:http://bbs.shangtao.net
 * 联系QQ:153289970
 * ----------------------------------------------------------------------------
 * 这不是一个自由软件！未经本公司授权您只能在不用于商业目的的前提下对程序代码进行修改和使用；
 * 不允许对程序代码以任何形式任何目的的再发布。
 * ============================================================================
 * 订单业务处理类
 */
class Orders extends Base{
	/**
	 * 提交虚拟商品订单
	 */
	public function quickSubmit($orderSrc = 0, $uId=0){
		$deliverType = 1;
		$isInvoice = ((int)input('post.isInvoice')!=0)?1:0;
		$invoiceClient = ($isInvoice==1)?input('post.invoiceClient'):'';
		$payType = 1;
		$userId = ($uId==0)?(int)session('WST_USER.userId'):$uId;
		if($userId==0)return WSTReturn('下单失败，请先登录');
		$isUseScore = (int)input('isUseScore');
		$useScore = (int)input('useScore');
		//检测购物车
		$carts = model('common/carts')->getQuickCarts($userId);
		if(empty($carts['carts']))return WSTReturn("请选择要购买的商品");
		//使用积分金额不能超过商品金额
		$tempScoreMoney = WSTScoreToMoney($carts['goodsTotalMoney'],true);
		$useScore = ($useScore>$tempScoreMoney)?$tempScoreMoney:$useScore;
		//计算出积分
		$orderScoreMoney = $this->getOrderScoreMoney($isUseScore,$useScore,$userId);
		//生成订单
		Db::startTrans();
		try{
			//提交订单前执行钩子
			hook('beforeSubmitOrder',['carts'=>$carts,"payType"=>$payType]);
			
			$goods = current($carts['carts']);
			if($goods['goodsStock']<$goods['cartNum'])return WSTReturn("下单失败，商品库存不足");
		    //给用户分配卡券
			$cards = model('GoodsVirtuals')->where(['goodsId'=>$goods['goodsId'],'dataFlag'=>1,'isUse'=>0])->lock(true)->limit($goods['cartNum'])->select();
			if(count($cards)<$goods['cartNum'])return WSTReturn("下单失败，商品库存不足");
            //修改库存
			Db::name('goods')->where('goodsId',$goods['goodsId'])->update([
				'goodsStock'=>['exp','goodsStock-'.$goods['cartNum']],
                'saleNum'=>['exp','saleNum+'.$goods['cartNum']],
			]);
			$orderNo = WSTOrderNo(); 
			$orderScore = 0;
			//创建订单
			$order = [];
			$order['orderSrc'] = $orderSrc;
			$order['areaId'] = 0;
			$order['userName'] = '';
			$order['userAddress'] = '';
			$order['orderNo'] = $orderNo;
			$order['userId'] = $userId;
            $order['orderType'] = 1;
			$order['payType'] = $payType;
			$order['goodsMoney'] = $carts['goodsTotalMoney'];
			$order['deliverType'] = $deliverType;
			// 运费
			$order['deliverMoney'] = 0;
			$order['totalMoney'] = $order['goodsMoney'];
			//积分支付-计算分配积分和金额
			$order['scoreMoney'] = $orderScoreMoney['useMoney'];
			$order['useScore'] = $orderScoreMoney['useScore'];
			//实付金额要减去积分兑换的金额
			$order['realTotalMoney'] = $order['totalMoney'] - $order['scoreMoney'];
			$order['needPay'] = $order['realTotalMoney'];
			if($order['needPay']>0){
	            $order['orderStatus'] = -2;//待付款
				$order['isPay'] = 0; 
			}else{
				$order['orderStatus'] = 0;//待发货
				$order['isPay'] = 1;
				$order['payFrom'] = 'others';
			}
			//积分
			$orderScore = 0;
			//如果开启下单获取积分则有积分
			if(WSTConf('CONF.isOrderScore')==1){
				 $orderScore = WSTMoneyGiftScore($order['goodsMoney']);
			}
			$order['orderScore'] = $orderScore;
			$order['isInvoice'] = $isInvoice;
            if($isInvoice==1){
                $order['invoiceJson'] = model('invoices')->getInviceInfo((int)input('param.invoiceId'),$userId);// 发票信息
                $order['invoiceClient'] = $invoiceClient;
            }else{
                $order['invoiceJson'] = '';// 发票信息
                $order['invoiceClient'] = '';
            }

			$order['orderRemarks'] = input('post.remark');
			$order['dataFlag'] = 1;
			$order['createTime'] = date('Y-m-d H:i:s');
			//创建订单前执行钩子
			hook('beforeInsertOrder',['order'=>&$order,'carts'=>$carts]);
			$result = $this->data($order,true)->isUpdate(false)->allowField(true)->save($order);
			$orderId = 0;
			if(false !== $result){
				$orderId = $this->orderId;
				//标记虚拟卡券为占用状态
				$goodsCards = [];
			    foreach ($cards as $key => $card) {
				    $card->isUse = 1;
				    $card->orderId = $orderId;
				    $card->orderNo = $orderNo;
				    $card->save();
				    $goodsCards[] = ['cardId'=>$card->id];
			    }
				//创建订单商品记录
				$orderGgoods = [];
				$orderGoods['orderId'] = $orderId;
				$orderGoods['goodsId'] = $goods['goodsId'];
				$orderGoods['goodsNum'] = $goods['cartNum'];
				$orderGoods['goodsPrice'] = $goods['shopPrice'];
				$orderGoods['goodsSpecId'] = 0;
				$orderGoods['goodsSpecNames'] = '';
				$orderGoods['goodsName'] = $goods['goodsName'];
				$orderGoods['goodsImg'] = $goods['goodsImg'];
				$orderGoods['goodsCode'] = '';
				$orderGoods['goodsType'] = 1;
				$orderGoods['extraJson'] = json_encode($goodsCards);
				$orderGoods['promotionJson'] = '';
				//创建订单商品前执行钩子
			    hook('beforeInsertOrderGoods',['orderId'=>$orderId,'orderGoods'=>&$orderGoods,'carts'=>$carts]);
				Db::name('order_goods')->insert($orderGoods);
				
				//提交订单后执行钩子
				hook('afterSubmitOrder',['orderId'=>$orderId]);
				
				//创建积分流水--如果有抵扣积分就肯定是开启了支付支付
				if($order['useScore']>0){
					$score = [];
					$score['userId'] = $userId;
					$score['score'] = $order['useScore'];
					$score['dataSrc'] = 1;
					$score['dataId'] = $orderId;
					$score['dataRemarks'] = "交易订单【".$orderNo."】使用积分".$order['useScore']."个";
					$score['scoreType'] = 0;
					model('UserScores')->add($score);
				}
				//建立订单记录
				$logOrder = [];
				$logOrder['orderId'] = $orderId;
				$logOrder['orderStatus'] = -2;
				$logOrder['logContent'] = "下单成功，等待用户支付";
				$logOrder['logUserId'] = $userId;
				$logOrder['logType'] = 0;
				$logOrder['logTime'] = date('Y-m-d H:i:s');
				Db::name('log_orders')->insert($logOrder);

                //判断是否需要发送管理员短信
	            $tpl = WSTMsgTemplates('PHONE_ADMIN_SUBMIT_ORDER');
	            if((int)WSTConf('CONF.smsOpen')==1 && (int)WSTConf('CONF.smsSubmitOrderTip')==1 && $tpl['tplContent']!='' && $tpl['status']=='1'){
					$params = ['tpl'=>$tpl,'params'=>['ORDER_NO'=>$orderNo]];
					$staffs = Db::name('staffs')->where(['staffId'=>['in',explode(',',WSTConf('CONF.submitOrderTipUsers'))],'staffStatus'=>1,'dataFlag'=>1])->field('staffPhone')->select();
					for($i=0;$i<count($staffs);$i++){
						if($staffs[$i]['staffPhone']=='')continue;
						$m = new LogSms();
				        $rv = $m->sendAdminSMS(0,$staffs[$i]['staffPhone'],$params,'submit','');
				    }
	            }
	            //判断是否需要发送给管理员消息
		        if((int)WSTConf('CONF.wxenabled')==1 && (int)WSTConf('CONF.wxSubmitOrderTip')==1){
		            $params = [];
			        $params['ORDER_NO'] = $orderNo;
		            $params['ORDER_TIME'] = date('Y-m-d H:i:s');             
		            $goodsNames = $goods['goodsName']."*".$goods['cartNum'];
			        $params['GOODS'] = $goodsNames;
			        $params['MONEY'] = $order['realTotalMoney'] + $order['scoreMoney'];
			        $params['ADDRESS'] = '';
			        $params['PAY_TYPE'] = WSTLangPayType($order['payType']);
			        WSTWxBatchMessage(['CODE'=>'WX_ADMIN_ORDER_SUBMIT','userType'=>1,'userId'=>explode(',',WSTConf('CONF.submitOrderTipUsers')),'params'=>$params]);
		        }
				//虚拟商品支付完成-立即发货
				if($order['needPay']==0){
					$logOrder = [];
					$logOrder['orderId'] = $orderId;
					$logOrder['orderStatus'] = 0;
					$logOrder['logContent'] = "订单已支付，下单成功";
					$logOrder['logUserId'] = $userId;
					$logOrder['logType'] = 0;
					$logOrder['logTime'] = date('Y-m-d H:i:s');
					Db::name('log_orders')->insert($logOrder);
					$this->handleVirtualGoods($orderId);
				}
			}
			//删除已选的购物车商品
			session('TMP_CARTS',null);
			Db::commit();
			if($order['isPay']==1){
				hook("afterOrderPaySuccess",['orderId'=>$orderId,'uerSystem'=>[0,1],'printCatId'=>1]);
			}
			return WSTReturn("提交订单成功", 1,$orderId);
		}catch (\Exception $e) {
            Db::rollback();
            return WSTReturn('提交订单失败',-1);
        }
	}

	/**
	 * 虚拟商品支付处理
	 */
	public function handleVirtualGoods($orderId){
		$order= Db::name('orders')->alias('o')
				->where('orderId',$orderId)->field('orderId,orderNo,o.userId,o.realTotalMoney,o.payFrom,o.orderScore')
				->find();
		//新增订单日志
		$logOrder = [];
		$logOrder['orderId'] = $order['orderId'];
		$logOrder['orderStatus'] = 0;
		$logOrder['logContent'] = "商家已发货";
		$logOrder['logUserId'] = $order['userId'];
		$logOrder['logType'] = 0;
		$logOrder['logTime'] = date('Y-m-d H:i:s');
		Db::name('log_orders')->insert($logOrder);
		$logOrder = [];
		$logOrder['orderId'] = $order['orderId'];
		$logOrder['orderStatus'] = 0;
		$logOrder['logContent'] = "用户已收货";
		$logOrder['logUserId'] = $order['userId'];
		$logOrder['logType'] = 0;
		$logOrder['logTime'] = date('Y-m-d H:i:s');
		Db::name('log_orders')->insert($logOrder);

		//给用户增加积分
		if(WSTConf("CONF.isOrderScore")==1 && $order['orderScore']>0){
			$score = [];
			$score['userId'] = $order['userId'];
			$score['score'] = $order['orderScore'];
			$score['dataSrc'] = 1;
			$score['dataId'] = $order['orderId'];
			$score['dataRemarks'] = "交易订单【".$order['orderNo']."】获得积分".$order['orderScore']."个";
			$score['scoreType'] = 1;
			$score['createTime'] = date('Y-m-d H:i:s');
			model('UserScores')->save($score);
			// 增加用户积分
			model('Users')->where("userId",$order['userId'])->setInc('userScore',$order['orderScore']);
			// 用户总积分
			model('Users')->where("userId",$order['userId'])->setInc('userTotalScore',$order['orderScore']);
		}

		//修改订单状态
		Db::name('orders')->where('orderId',$order['orderId'])->update(['orderStatus'=>2,'deliveryTime'=>date('Y-m-d H:i:s'),'receiveTime'=>date('Y-m-d H:i:s')]);
		//分配卡券号
        $orderGoods = Db::name('order_goods')->where('orderId',$order['orderId'])->field('id,goodsName,extraJson')->find();
        $cardIds = [];
        $extraJson = json_decode($orderGoods['extraJson'],true);
        foreach ($extraJson as $ogextra) {
            $cardIds[] = $ogextra['cardId'];
        }
        $cards = model('common/GoodsVirtuals')->where(['id'=>['in',$cardIds]])->field('id,cardNo,cardPwd')->select();
        $cardmap = [];
        foreach ($cards as $card) {
            $cardmap[$card['id']] = $card;
        }
        $ogcards = [];
        $extra = json_decode($orderGoods['extraJson'],true);
        foreach ($extra as $ogextra) {
        	$ogextra['cardId'] = $cardmap[$ogextra['cardId']]['id'];
	        $ogextra['cardNo'] = $cardmap[$ogextra['cardId']]['cardNo'];
	        $ogextra['cardPwd'] = $cardmap[$ogextra['cardId']]['cardPwd'];
	        $ogextra['isUse'] = 0;
	        $ogcards[] = $ogextra;
        }
        Db::name('order_goods')->where('id',$orderGoods['id'])->update(['extraJson'=>json_encode($ogcards)]);
	    //发送一条用户信息
		$tpl = WSTMsgTemplates('ORDER_USER_AUTO_DELIVERY');
	    if($tpl['tplContent']!='' && $tpl['status']=='1'){
	        $find = ['${ORDER_NO}','${GOODS}'];
	        $replace = [$order['orderNo'],$orderGoods['goodsName']];
	        WSTSendMsg($order["userId"],str_replace($find,$replace,$tpl['tplContent']),['from'=>1,'dataId'=>$order['orderId']]);
	    }
	    //判断是否需要发送管理员短信
		$tpl = WSTMsgTemplates('PHONE_ADMIN_PAY_ORDER');
		if((int)WSTConf('CONF.smsOpen')==1 && (int)WSTConf('CONF.smsPayOrderTip')==1 && $tpl['tplContent']!='' && $tpl['status']=='1'){
			$params = ['tpl'=>$tpl,'params'=>['ORDER_NO'=>$order['orderNo']]];
			$staffs = Db::name('staffs')->where(['staffId'=>['in',explode(',',WSTConf('CONF.payOrderTipUsers'))],'staffStatus'=>1,'dataFlag'=>1])->field('staffPhone')->select();
			for($i=0;$i<count($staffs);$i++){
				if($staffs[$i]['staffPhone']=='')continue;
				$m = new LogSms();
				$rv = $m->sendAdminSMS(0,$staffs[$i]['staffPhone'],$params,'complatePay','');
			}
		}
		//微信消息-已支付
		if((int)WSTConf('CONF.wxenabled')==1){
			//判断是否需要发送给管理员消息
			if((int)WSTConf('CONF.wxPayOrderTip')==1){
				$params = [];
			    $params['ORDER_NO'] = $order['orderNo'];
				$params['PAY_TIME'] = date('Y-m-d H:i:s');             
				$params['MONEY'] = $order['realTotalMoney'];
				$params['PAY_SRC'] = WSTLangPayFrom($order['payFrom']);
				WSTWxBatchMessage(['CODE'=>'WX_ADMIN_ORDER_PAY','userType'=>1,'userId'=>explode(',',WSTConf('CONF.payOrderTipUsers')),'params'=>$params]);
			}
		} 
	}

	/**
	 * 提交订单
	 */
	public function submit($orderSrc=0, $uId=0){
		$addressId = (int)input('post.s_addressId');
		$deliverType = ((int)input('post.deliverType')!=0)?1:0;
		$isInvoice = ((int)input('post.isInvoice')!=0)?1:0;
		$invoiceClient = ($isInvoice==1)?input('post.invoiceClient'):'';
		$payType = ((int)input('post.payType')!=0)?1:0;
		$userId = ($uId==0)?(int)session('WST_USER.userId'):$uId;
		if($userId==0)return WSTReturn('下单失败，请先登录');
		$isUseScore = (int)input('isUseScore');
		$useScore = (int)input('useScore');
		//检测购物车
		$carts = model('common/carts')->getCarts(true,$userId);
		if(empty($carts['carts']))return WSTReturn("请选择要购买的商品");
		//使用积分金额不能超过商品金额
		$tempScoreMoney = WSTScoreToMoney($carts['goodsTotalMoney']-$carts['promotionMoney'],true);
		$useScore = ($useScore>$tempScoreMoney)?$tempScoreMoney:$useScore;
		if($deliverType==0){// 配送方式为快递，必须有用户地址
			//检测地址是否有效
			$address = Db::name('user_address')->where(['userId'=>$userId,'addressId'=>$addressId,'dataFlag'=>1])->find();
			if(empty($address)){
				return WSTReturn("无效的用户地址");
			}
		    $areaIds = [];
	        $areaMaps = [];
	        $tmp = explode('_',$address['areaIdPath']);
	        $address['areaId2'] = $tmp[1];//记录配送城市
	        foreach ($tmp as $vv){
	         	if($vv=='')continue;
	         	if(!in_array($vv,$areaIds))$areaIds[] = $vv;
	        }
	        if(!empty($areaIds)){
		         $areas = Db::name('areas')->where(['dataFlag'=>1,'areaId'=>['in',$areaIds]])->field('areaId,areaName')->select();
		         foreach ($areas as $v){
		         	 $areaMaps[$v['areaId']] = $v['areaName'];
		         }
		         $tmp = explode('_',$address['areaIdPath']);
		         $areaNames = [];
			     foreach ($tmp as $vv){
		         	 if($vv=='')continue;
		         	 $areaNames[] = $areaMaps[$vv];
		         	 $address['areaName'] = implode('',$areaNames);
		         }
	        }
	        $address['userAddress'] = $address['areaName'].$address['userAddress'];
		    WSTUnset($address, 'isDefault,dataFlag,createTime,userId');
	    }else{
	    	$address = [];
			$address['areaId'] = 0;
			$address['userName'] = '';
			$address['userAddress'] = '';
	    }
		
		//计算出积分
		$orderScoreMoney = $this->getOrderScoreMoney($isUseScore,$useScore,$userId);
		//生成订单
		Db::startTrans();
		try{
			//提交订单前执行钩子
			hook('beforeSubmitOrder',['carts'=>$carts,"payType"=>$payType]);
			
			$orderNo = WSTOrderNo(); 
			$orderScore = 0;
			//创建订单
			$order = [];
			$order['orderSrc'] = $orderSrc;

			$order = array_merge($order,$address);
			$order['orderNo'] = $orderNo;
			$order['userId'] = $userId;

			$order['payType'] = $payType;
			$order['goodsMoney'] = $carts['goodsTotalMoney'];
			$order['deliverType'] = $deliverType;
			// 运费
			if($carts["isFreeShipping"]){
				$order['deliverMoney'] = 0;
			}else{
				$order['deliverMoney'] = ($deliverType==1)?0:WSTOrderFreight($order['areaId2']);
			}

			$order['totalMoney'] = $order['goodsMoney']+$order['deliverMoney'];
			//积分支付-计算分配积分和金额
			$order['scoreMoney'] = $orderScoreMoney['useMoney'];
			$order['useScore'] = $orderScoreMoney['useScore'];
			//实付金额要减去积分兑换的金额
			$order['realTotalMoney'] = WSTPositiveNum($order['totalMoney'] - $order['scoreMoney'] - $carts['promotionMoney']);
			$order['needPay'] = $order['realTotalMoney'];
            if($payType==1){
                if($order['needPay']>0){
                    $order['orderStatus'] = -2;//待付款
				    $order['isPay'] = 0; 
                }else{
                    $order['orderStatus'] = 0;//待发货
				    $order['isPay'] = 1; 
				    $order['payFrom'] = 'others';
                }
			}else{
				$order['isPay'] = 0; 
			    $order['orderStatus'] = 0;//待发货
				if($order['needPay']==0){
					$order['isPay'] = 1;
					$order['payFrom'] = 'others';
				}
			}

			//积分
			$orderScore = 0;
			//如果开启下单获取积分则有积分
			if(WSTConf('CONF.isOrderScore')==1){
				$orderScore = WSTMoneyGiftScore($order['realTotalMoney']-$order['deliverMoney']);
			}
			$order['orderScore'] = $orderScore;
			$order['isInvoice'] = $isInvoice;
            if($isInvoice==1){
                $order['invoiceJson'] = model('invoices')->getInviceInfo((int)input('param.invoiceId'),$userId);// 发票信息
                $order['invoiceClient'] = $invoiceClient;
            }else{
                $order['invoiceJson'] = '';// 发票信息
                $order['invoiceClient'] = '';
            }
            $order['orderType'] = 0;
			$order['orderRemarks'] = input('post.remark');
			$order['dataFlag'] = 1;
			$order['createTime'] = date('Y-m-d H:i:s');
			//创建订单前执行钩子
			hook('beforeInsertOrder',['order'=>&$order,'carts'=>$carts]);
			$result = $this->data($order,true)->isUpdate(false)->allowField(true)->save($order);
			$orderId = 0;
			if(false !== $result){
				$orderId = $this->orderId;
				$orderTotalGoods = [];
				foreach ($carts['carts'] as $gkey =>$goods){
					//创建订单商品记录
					$orderGgoods = [];
					$orderGoods['orderId'] = $orderId;
					$orderGoods['goodsId'] = $goods['goodsId'];
					$orderGoods['goodsNum'] = $goods['cartNum'];
					$orderGoods['goodsPrice'] = $goods['shopPrice'];
					$orderGoods['goodsSpecId'] = $goods['goodsSpecId'];
					if(!empty($goods['specNames'])){
						$specNams = [];
						foreach ($goods['specNames'] as $pkey =>$spec){
							$specNams[] = $spec['catName'].'：'.$spec['itemName'];
						}
						$orderGoods['goodsSpecNames'] = implode('@@_@@',$specNams);
					}else{
						$orderGoods['goodsSpecNames'] = '';
					}
					$orderGoods['goodsName'] = $goods['goodsName'];
					$orderGoods['goodsImg'] = $goods['goodsImg'];
					$orderGoods['goodsCode'] = '';
					$orderGoods['goodsType'] = 0;
					$orderGoods['extraJson'] = '';
					$orderGoods['promotionJson'] = '';
					$orderTotalGoods[] = $orderGoods;
					//修改库存
					if($goods['goodsSpecId']>0){
					    Db::name('goods_specs')->where('id',$goods['goodsSpecId'])->update([
					    	'specStock'=>['exp','specStock-'.$goods['cartNum']]
					    ]);
					}
					Db::name('goods')->where('goodsId',$goods['goodsId'])->update([
						'goodsStock'=>['exp','goodsStock-'.$goods['cartNum']]
					]);
				}
				//创建订单商品前执行钩子
			    hook('beforeInsertOrderGoods',['orderId'=>$orderId,'orderGoods'=>&$orderTotalGoods,'carts'=>$carts]);
				Db::name('order_goods')->insertAll($orderTotalGoods);
				
				//提交订单后执行钩子
				hook('afterSubmitOrder',['orderId'=>$orderId]);
				
				//创建积分流水--如果有抵扣积分就肯定是开启了支付支付
				if($order['useScore']>0){
					$score = [];
					$score['userId'] = $userId;
					$score['score'] = $order['useScore'];
					$score['dataSrc'] = 1;
					$score['dataId'] = $orderId;
					$score['dataRemarks'] = "交易订单【".$orderNo."】使用积分".$order['useScore']."个";
					$score['scoreType'] = 0;
					model('UserScores')->add($score);
				}
				//建立订单记录
				$logOrder = [];
				$logOrder['orderId'] = $orderId;
				$logOrder['orderStatus'] = ($payType==1 && $order['needPay']==0)?-2:$order['orderStatus'];
				$logOrder['logContent'] = ($payType==1)?"下单成功，等待用户支付":"下单成功";
				$logOrder['logUserId'] = $userId;
				$logOrder['logType'] = 0;
				$logOrder['logTime'] = date('Y-m-d H:i:s');
				Db::name('log_orders')->insert($logOrder);
				if($payType==1 && $order['needPay']==0){
					$logOrder = [];
					$logOrder['orderId'] = $orderId;
					$logOrder['orderStatus'] = 0;
					$logOrder['logContent'] = "订单已支付，下单成功";
					$logOrder['logUserId'] = $userId;
					$logOrder['logType'] = 0;
					$logOrder['logTime'] = date('Y-m-d H:i:s');
					Db::name('log_orders')->insert($logOrder);
				}
				//判断是否需要发送管理员短信
	            $tpl = WSTMsgTemplates('PHONE_ADMIN_SUBMIT_ORDER');
	            if((int)WSTConf('CONF.smsOpen')==1 && (int)WSTConf('CONF.smsSubmitOrderTip')==1 && $tpl['tplContent']!='' && $tpl['status']=='1'){
				    $params = ['tpl'=>$tpl,'params'=>['ORDER_NO'=>$orderNo]];
				    $staffs = Db::name('staffs')->where(['staffId'=>['in',explode(',',WSTConf('CONF.submitOrderTipUsers'))],'staffStatus'=>1,'dataFlag'=>1])->field('staffPhone')->select();
					for($i=0;$i<count($staffs);$i++){
						if($staffs[$i]['staffPhone']=='')continue;
						$m = new LogSms();
				        $rv = $m->sendAdminSMS(0,$staffs[$i]['staffPhone'],$params,'submit','');
				    }
	            }
	            //判断是否需要发送给管理员消息
		        if((int)WSTConf('CONF.wxenabled')==1 && (int)WSTConf('CONF.wxSubmitOrderTip')==1){

		            $params = [];
		            $params['ORDER_NO'] = $orderNo;
	                $params['ORDER_TIME'] = date('Y-m-d H:i:s');             
		            $goodsNames = [];
		            foreach ($carts['carts'] as $gkey =>$goods){
	                    $goodsNames[] = $goods['goodsName']."*".$goods['cartNum'];
		            }
		            $params['GOODS'] = implode(',',$goodsNames);
		            $params['MONEY'] = $order['realTotalMoney'] + $order['scoreMoney'];
		            $params['ADDRESS'] = $order['userAddress']." ".$order['userName'];
		            $params['PAY_TYPE'] = WSTLangPayType($order['payType']);
			        WSTWxBatchMessage(['CODE'=>'WX_ADMIN_ORDER_SUBMIT','userType'=>1,'userId'=>explode(',',WSTConf('CONF.submitOrderTipUsers')),'params'=>$params]);
		        }
			}
			//删除已选的购物车商品
			Db::name('carts')->where(['userId'=>$userId,'isCheck'=>1])->delete();
			Db::commit();
			if($order['isPay']==1){
				hook("afterOrderPaySuccess",['orderId'=>$orderId,'uerSystem'=>[0,1],'printCatId'=>1]);
			}
			return WSTReturn("提交订单成功", 1,$orderId);
		}catch (\Exception $e) {
            Db::rollback();
            return WSTReturn('提交订单失败',-1);
        }
	}
	
	/**
	 * 计算可用积分和抵扣金额
	 */
	public function getOrderScoreMoney($isUseScore, $useScore, $uId=0){
		$userId = ($uId==0)?(int)session('WST_USER.userId'):$uId;
		if((int)WSTConf('CONF.isOpenScorePay')==1 && $isUseScore){
			$uses = model('common/users')->getFieldsById($userId,'userScore');
			//如果又要积分支付又传个0或者负数就默认全部用完...
			if($useScore<=0)$useScore = $uses['userScore'];
			if($uses['userScore']<$useScore)$useScore = $uses['userScore'];
			$money = WSTScoreToMoney($useScore);
			return ['useScore'=>$useScore,'useMoney'=>$money];
		}
		return ['useScore'=>0,'useMoney'=>0];
	}
	
	/**
	 * 根据订单唯一流水获取订单信息
	 */
	public function getByUnique($payfor = '',$uId=0, $orderId=0){
		if($orderId==0)$orderId = input('id/d',0);
		$userId = (int)session('WST_USER.userId');

		if($uId>0){
			$userId = $uId;
			$orderId = input('orderNo');
		}

		$rs = $this->where(['userId'=>$userId,'orderId'=>$orderId])->field('orderId,orderNo,payType,needPay,deliverMoney,userName,userAddress,userPhone')->find();
		if(empty($rs))return [];
		$data = [];
		$data['deliverMoney'] = $rs['deliverMoney'];
		$data['orderNo'] = $rs['orderNo'];
		$data['userName'] = $rs['userName'];
		$data['userAddress'] = $rs['userAddress'];
		$data['userPhone'] = $rs['userPhone'];
		$data['orderId'] = $orderId;
		$data['totalMoney'] = $rs['needPay'];
		$data['payType'] = $rs['payType'];
		//获取商品信息
		$goods = Db::name('order_goods')->where(['orderId'=>$orderId])->select();
		foreach ($goods as $key =>$v){
			if($v['goodsSpecNames']!=''){
				$v['goodsSpecNames'] = explode('@@_@@',$v['goodsSpecNames']);
			}else{
				$v['goodsSpecNames'] = [];
			}
			$data['goods'][] = $v;
		}
		//如果是在线支付的话就要加载支付信息
		if($data['payType']==1){
			//获取支付信息
			$payments = model('payments')->where(['isOnline'=>1,'enabled'=>1])->where("find_in_set ($payfor,payFor)")->order('payOrder asc')->select();
			$data['payments'] = $payments;
		}
		return $data;
	}
	
	/**
	 * 获取用户订单列表
	 */
	public function userOrdersByPage($orderStatus,$isAppraise = -1,$uId=0){
		$userId = ($uId==0)?(int)session('WST_USER.userId'):$uId;
		$orderNo = input('post.orderNo');
		$userName = input('post.userName');
		$isRefund = (int)input('post.isRefund',-1);
		$where = ['o.userId'=>$userId,'o.dataFlag'=>1];
		if(is_array($orderStatus)){
			$where['orderStatus'] = ['in',$orderStatus];
		}else{
			$where['orderStatus'] = $orderStatus;
		}
		if($isAppraise!=-1)$where['isAppraise'] = $isAppraise;
		if($orderNo!=''){
			$where['o.orderNo'] = ['like',"%$orderNo%"];
		}
		if($userName!=''){
			$where['o.userName'] = ['like',"%$userName%"];
		}
		if(in_array($isRefund,[0,1])){
			$where['isRefund'] = $isRefund;
		}

		$page = $this->alias('o')
		             ->join('__ORDER_REFUNDS__ orf','orf.orderId=o.orderId and orf.refundStatus!=-1','left')
		             ->where($where)
		             ->field('o.noticeDeliver,o.userName,o.orderId,o.orderNo,o.goodsMoney,o.totalMoney,o.realTotalMoney,
		              o.orderStatus,o.deliverType,deliverMoney,isPay,payType,payFrom,o.orderStatus,needPay,isAppraise,isRefund,orderSrc,o.createTime,o.expressId,o.expressNo,orf.id refundId')
			         ->order('o.createTime', 'desc')
			         ->paginate(input('pagesize/d'))->toArray();
	    if(count($page['Rows'])>0){
	    	 $orderIds = [];
	    	 foreach ($page['Rows'] as $v){
	    	 	 $orderIds[] = $v['orderId'];
	    	 }
	    	 $goods = Db::name('order_goods')->where('orderId','in',$orderIds)->select();
	    	 $goodsMap = [];
	    	 foreach ($goods as $v){
	    	 	 $v['goodsSpecNames'] = str_replace('@@_@@','、',$v['goodsSpecNames']);
	    	 	 $goodsMap[$v['orderId']][] = $v;
	    	 }
	    	 foreach ($page['Rows'] as $key => $v){
	    	 	 $page['Rows'][$key]['hasExpress'] = ($v['expressId']!='' && $v['expressNo']!='')?true:false;
	    	 	 $page['Rows'][$key]['list'] = $goodsMap[$v['orderId']];
	    	 	 $page['Rows'][$key]['payTypeName'] = WSTLangPayType($v['payType']);
	    	 	 $page['Rows'][$key]['deliverType'] = WSTLangDeliverType($v['deliverType']==1);
	    	 	 $page['Rows'][$key]['status'] = WSTLangOrderStatus($v['orderStatus']);
	    	 	 if($v["orderStatus"]==-2){
					$page['Rows'][$key]['pkey'] = WSTBase64urlEncode($v["orderId"]);
				}
	    	 }
	    	hook('afterQueryUserOrders',['page'=>&$page]);
	    }
	    return $page;
	}

	/**
	 * 用户收货
	 */
	public function receive($orderId=0, $uId=0){
		$orderId = ($orderId==0)?(int)input('post.id'):$orderId;
		$userId = ($uId==0)?(int)session('WST_USER.userId'):$uId;
		$order = $this->where(['userId'=>$userId,'orderId'=>$orderId,'orderStatus'=>1])
		              ->field('orderId,orderNo,payType,orderScore')->find();
		if(!empty($order)){
			Db::startTrans();
		    try{
				$data = ['orderStatus'=>2,'receiveTime'=>date('Y-m-d H:i:s')];
			    $result = $this->where('orderId',$order['orderId'])->update($data);
				if(false != $result){
					//确认收货后执行钩子
					hook('afterUserReceive',['orderId'=>$orderId]);
					
					//修改商品成交量
					$goodss = Db::name('order_goods')->where('orderId',$order['orderId'])->field('goodsId,goodsNum,goodsSpecId')->select();
					foreach($goodss as $key =>$v){
						Db::name('goods')->where('goodsId',$v['goodsId'])->setInc('saleNum', $v['goodsNum']);
						if($v['goodsSpecId']>0){
							Db::name('goods_specs')->where('id',$v['goodsSpecId'])->setInc('saleNum', $v['goodsNum']);
						}
					}
					//新增订单日志
					$logOrder = [];
					$logOrder['orderId'] = $orderId;
					$logOrder['orderStatus'] = 2;
					$logOrder['logContent'] = "用户已收货";
					$logOrder['logUserId'] = $userId;
					$logOrder['logType'] = 0;
					$logOrder['logTime'] = date('Y-m-d H:i:s');
					Db::name('log_orders')->insert($logOrder);
					//给用户增加积分
					if(WSTConf("CONF.isOrderScore")==1){
						$score = [];
						$score['userId'] = $userId;
						$score['score'] = $order['orderScore'];
						$score['dataSrc'] = 1;
						$score['dataId'] = $orderId;
						$score['dataRemarks'] = "交易订单【".$order['orderNo']."】获得积分".$order['orderScore']."个";
						$score['scoreType'] = 1;
						$score['createTime'] = date('Y-m-d H:i:s');
						model('UserScores')->save($score);
						// 增加用户积分
						model('Users')->where("userId=$userId")->setInc('userScore',$order['orderScore']);
						// 用户总积分
						model('Users')->where("userId=$userId")->setInc('userTotalScore',$order['orderScore']);
					}
					Db::commit();
					return WSTReturn('操作成功',1);
				}
		    }catch (\Exception $e) {
	            Db::rollback();
	            return WSTReturn('操作失败',-1);
	        }
		}
		return WSTReturn('操作失败，请检查订单状态是否已改变');
	}
	/**
	 * 用户取消订单
	 */
	public function cancel($uId=0){
		$orderId = (int)input('post.id');
		hook('beforeCancelOrder',['orderId'=>$orderId]);
		$reason = (int)input('post.reason');
		$content = input('post.content');
		$userId = ($uId==0)?(int)session('WST_USER.userId'):$uId;
		$order = $this->where(['userId'=>$userId,'orderId'=>$orderId,'orderStatus'=>['in',[-2,0]]])
		              ->field('orderId,orderNo,realTotalMoney,orderStatus,payType,isPay,useScore,orderCode,scoreMoney')->find();
		$reasonData = WSTDatas('ORDER_CANCEL',$reason);
		if(empty($reasonData))return WSTReturn("无效的取消原因");
		if(!empty($order)){
			Db::startTrans();
		    try{
				$data = ['orderStatus'=>-1,'cancelReason'=>$reason];
			    //如果是货到付款的话，则把实付金额设置为0
				if($order['payType']==0 || ($order['orderStatus']==-2 && $order['payType']==1))$data['realTotalMoney'] = 0;
			    $result = $this->where('orderId',$order['orderId'])->update($data);
			    //echo $this->getLastSql();
				if(false != $result){
					//返还商品库存
					$goods = Db::name('order_goods')->alias('og')->join('__GOODS__ g','og.goodsId=g.goodsId','inner')
					           ->where('orderId',$orderId)->field('og.*,g.isSpec')->select();
					foreach ($goods as $key => $v){
						if($order['orderCode']=='order'){
							//修改库存
							if($v['isSpec']>0){
						        Db::name('goods_specs')->where('id',$v['goodsSpecId'])->setInc('specStock',$v['goodsNum']);
							}
							Db::name('goods')->where('goodsId',$v['goodsId'])->setInc('goodsStock',$v['goodsNum']);
					    }
					}
					//新增订单日志
					$logOrder = [];
					$logOrder['orderId'] = $orderId;
					$logOrder['orderStatus'] = -1;
					$logOrder['logContent'] = "用户取消订单，取消原因：".$reasonData['dataName'];
					$logOrder['logUserId'] = $userId;
					$logOrder['logType'] = 0;
					$logOrder['logTime'] = date('Y-m-d H:i:s');
					Db::name('log_orders')->insert($logOrder);
					//判断是否需要发送管理员短信
					$tpl = WSTMsgTemplates('PHONE_ADMIN_CANCEL_ORDER');
					if((int)WSTConf('CONF.smsOpen')==1 && (int)WSTConf('CONF.smsCancelOrderTip')==1 && $tpl['tplContent']!='' && $tpl['status']=='1'){
						$params = ['tpl'=>$tpl,'params'=>['ORDER_NO'=>$order['orderNo']]];
						$staffs = Db::name('staffs')->where(['staffId'=>['in',explode(',',WSTConf('CONF.cancelOrderTipUsers'))],'staffStatus'=>1,'dataFlag'=>1])->field('staffPhone')->select();
						for($i=0;$i<count($staffs);$i++){
							if($staffs[$i]['staffPhone']=='')continue;
							$m = new LogSms();
							$rv = $m->sendAdminSMS(0,$staffs[$i]['staffPhone'],$params,'cancel','');
						}
					}
					//判断是否需要发送给管理员消息
		            if((int)WSTConf('CONF.wxenabled')==1 && (int)WSTConf('CONF.wxCancelOrderTip')==1){
		                $params = [];
			            $params['ORDER_NO'] = $order['orderNo'];            
			            $goodsNames = [];
			            foreach ($goods as $gkey =>$g){
		                    $goodsNames[] = $g['goodsName']."*".$g['goodsNum'];
			            }
			            $params['REASON'] = $reasonData['dataName'];
			            $params['GOODS'] = implode(',',$goodsNames);
			            $params['MONEY'] = $order['realTotalMoney'] + $order['scoreMoney'];
			            WSTWxBatchMessage(['CODE'=>'WX_ADMIN_ORDER_CANCEL','userType'=>1,'userId'=>explode(',',WSTConf('CONF.cancelOrderTipUsers')),'params'=>$params]);
		            }
					//有支付或者有使用积分
					if(($order['payType']==1 && $order['isPay']==1) || $order['useScore']>0){
						$data = [];
					    $data['orderId'] = $orderId;	
		                $data['refundTo'] = 0;
		                $data['refundReson'] = 10000;
		                $data['refundOtherReson'] = '【用户取消订单】：'.$reasonData['dataName'];
		                if($reason==10000)$data['refundOtherReson'] = $content;
		                $data['backMoney'] = ($order['isPay']==1)?$order['realTotalMoney']:0;
		                $data['backScore'] = $order['useScore'];
		                $data['createTime'] = date('Y-m-d H:i:s');
		                $data['refundRemark'] = $reasonData['dataName'].(($reason==10000)?"-".$data['refundOtherReson']:'');
		                $data['refundStatus'] = 0;
		                Db::name('order_refunds')->insert($data);
		                //判断是否需要发送管理员短信
						$tpl = WSTMsgTemplates('PHONE_ADMIN_REFUND_ORDER');
						if((int)WSTConf('CONF.smsOpen')==1 && (int)WSTConf('CONF.smsRefundOrderTip')==1 && $tpl['tplContent']!='' && $tpl['status']=='1'){
							$params = ['tpl'=>$tpl,'params'=>['ORDER_NO'=>$order['orderNo']]];
							$staffs = Db::name('staffs')->where(['staffId'=>['in',explode(',',WSTConf('CONF.refundOrderTipUsers'))],'staffStatus'=>1,'dataFlag'=>1])->field('staffPhone')->select();
							for($i=0;$i<count($staffs);$i++){
								if($staffs[$i]['staffPhone']=='')continue;
								$m = new LogSms();
								$rv = $m->sendAdminSMS(0,$staffs[$i]['staffPhone'],$params,'shoprefund','');
							}
						}
						//判断是否需要发送给管理员消息
					    if((int)WSTConf('CONF.wxenabled')==1 && (int)WSTConf('CONF.wxRefundOrderTip')==1){
			                $reasonData = WSTDatas('REFUND_TYPE',$data['refundReson']);
			                $params = [];
							$params['ORDER_NO'] = $order['orderNo'];
						    $params['REASON'] = $reasonData['dataName'].(($data['refundReson']==10000)?" - ".$data['refundOtherReson']:"");           
							$params['MONEY'] = $data['backMoney'].(($order['useScore']>0)?("【退回积分：".$order['useScore']."】"):"");
				            WSTWxBatchMessage(['CODE'=>'WX_ADMIN_ORDER_REFUND','userType'=>1,'userId'=>explode(',',WSTConf('CONF.refundOrderTipUsers')),'params'=>$params]);
						}
	                }
	                
					Db::commit();
					return WSTReturn('订单取消成功',1);
				}
			}catch (\Exception $e) {
		        Db::rollback();
	            return WSTReturn('操作失败',-1);
	        }
		}
		return WSTReturn('操作失败，请检查订单状态是否已改变');
	}
	/**
	 * 用户拒收订单
	 */
	public function reject($uId=0){
		$orderId = (int)input('post.id');
		$reason = (int)input('post.reason');
		$content = input('post.content');
		$userId = ($uId==0)?(int)session('WST_USER.userId'):$uId;
		$order = $this->where(['userId'=>$userId,'orderId'=>$orderId,'orderStatus'=>1])
		              ->field('orderId,orderNo,realTotalMoney,payType,isPay,scoreMoney,userAddress,userName,useScore')->find();
		$reasonData = WSTDatas('ORDER_REJECT',$reason);
		if(empty($reasonData))return WSTReturn("无效的拒收原因");
		if($reason==10000 && $content=='')return WSTReturn("请输入拒收原因");
		if(!empty($order)){
			Db::startTrans();
		    try{
				$data = ['orderStatus'=>-3,'rejectReason'=>$reason];
				if($order['payType']==0)$data['realTotalMoney'] = 0;
				if($reason==10000)$data['rejectOtherReason'] = $content;
			    $result = $this->where('orderId',$order['orderId'])->update($data);
				if(false != $result){
					//新增订单日志
					$logOrder = [];
					$logOrder['orderId'] = $orderId;
					$logOrder['orderStatus'] = -3;
					$logOrder['logContent'] = "用户拒收订单，拒收原因：".$reasonData['dataName'].(($reason==10000)?"-".$content:"");
					$logOrder['logUserId'] = $userId;
					$logOrder['logType'] = 0;
					$logOrder['logTime'] = date('Y-m-d H:i:s');
					Db::name('log_orders')->insert($logOrder);
					//判断是否需要发送管理员短信
					$tpl = WSTMsgTemplates('PHONE_ADMIN_REJECT_ORDER');
					if((int)WSTConf('CONF.smsOpen')==1 && (int)WSTConf('CONF.smsRejectOrderTip')==1 && $tpl['tplContent']!='' && $tpl['status']=='1'){
						$params = ['tpl'=>$tpl,'params'=>['ORDER_NO'=>$order['orderNo']]];
						$staffs = Db::name('staffs')->where(['staffId'=>['in',explode(',',WSTConf('CONF.rejectOrderTipUsers'))],'staffStatus'=>1,'dataFlag'=>1])->field('staffPhone')->select();
						for($i=0;$i<count($staffs);$i++){
							if($staffs[$i]['staffPhone']=='')continue;
							$m = new LogSms();
							$rv = $m->sendAdminSMS(0,$staffs[$i]['staffPhone'],$params,'cancel','');
						}
					}
					//判断是否需要发送给管理员消息
		            if((int)WSTConf('CONF.wxenabled')==1 && (int)WSTConf('CONF.wxRejectOrderTip')==1){
		                $params = [];
			            $params['ORDER_NO'] = $order['orderNo'];  
		                $goods = Db::name('order_goods')->where('orderId',$order['orderId'])->select();           
			            $goodsNames = [];
			            foreach ($goods as $gkey =>$goods){
		                    $goodsNames[] = $goods['goodsName']."*".$goods['goodsNum'];
			            }
			            $params['GOODS'] = implode(',',$goodsNames);
			            $params['MONEY'] = $order['realTotalMoney'] + $order['scoreMoney'];
			            $params['ADDRESS'] = $order['userAddress']." ".$order['userName'];
			            $params['REASON'] = $reasonData['dataName'].(($reason==10000)?"-".$content:"");
			            WSTWxBatchMessage(['CODE'=>'WX_ADMIN_ORDER_REJECT','userType'=>1,'userId'=>explode(',',WSTConf('CONF.rejectOrderTipUsers')),'params'=>$params]);
		            }
					//如果是在线支付并且已经支付了的订单还要生成退款单
					if(($order['payType']==1 && $order['isPay']==1) || $order['useScore']>0){
						$data = [];
					    $data['orderId'] = $orderId;	
		                $data['refundTo'] = 0;
		                $data['refundReson'] = $reason;
		                if($reason==10000)$data['refundOtherReson'] = $content;
		                $data['backMoney'] = ($order['payType']==1)?$order['realTotalMoney']:0;
		                $data['backScore'] = $order['useScore'];
		                $data['createTime'] = date('Y-m-d H:i:s');
		                $data['refundStatus'] = 0;
		                Db::name('order_refunds')->insert($data);
		                //判断是否需要发送管理员短信
						$tpl = WSTMsgTemplates('PHONE_ADMIN_REFUND_ORDER');
						if((int)WSTConf('CONF.smsOpen')==1 && (int)WSTConf('CONF.smsRefundOrderTip')==1 && $tpl['tplContent']!='' && $tpl['status']=='1'){
							$params = ['tpl'=>$tpl,'params'=>['ORDER_NO'=>$order['orderNo']]];
							$staffs = Db::name('staffs')->where(['staffId'=>['in',explode(',',WSTConf('CONF.refundOrderTipUsers'))],'staffStatus'=>1,'dataFlag'=>1])->field('staffPhone')->select();
							for($i=0;$i<count($staffs);$i++){
								if($staffs[$i]['staffPhone']=='')continue;
								$m = new LogSms();
								$rv = $m->sendAdminSMS(0,$staffs[$i]['staffPhone'],$params,'shoprefund','');
							}
						}
						//判断是否需要发送给管理员消息
					    if((int)WSTConf('CONF.wxenabled')==1 && (int)WSTConf('CONF.wxRefundOrderTip')==1){
			                $reasonData = WSTDatas('REFUND_TYPE',$data['refundReson']);
			                $params = [];
							$params['ORDER_NO'] = $order['orderNo'];
						    $params['REASON'] = $reasonData['dataName'].(($data['refundReson']==10000)?" - ".$data['refundOtherReson']:"");           
							$params['MONEY'] = $data['backMoney'].(($order['useScore']>0)?("【退回积分：".$order['useScore']."】"):"");
				            WSTWxBatchMessage(['CODE'=>'WX_ADMIN_ORDER_REFUND','userType'=>3,'userId'=>explode(',',WSTConf('CONF.refundOrderTipUsers')),'params'=>$params]);
						}
		            }
					Db::commit();
					return WSTReturn('操作成功',1);
				}
			}catch (\Exception $e) {
		        Db::rollback();
	            return WSTReturn('操作失败',-1);
	        }
		}
		return WSTReturn('操作失败，请检查订单状态是否已改变');
	}
	/**
	 * 获取订单价格
	 */
	public function getMoneyByOrder($orderId = 0){
		$orderId = ($orderId>0)?$orderId:(int)input('post.id');
		return $this->where('orderId',$orderId)->field('orderId,goodsMoney,deliverMoney,totalMoney,realTotalMoney')->find();
	}
	


	
	/**
	 * 获取订单详情
	 */
	public function getByView($orderId,$uId=0){
		$userId = ($uId==0)?(int)session('WST_USER.userId'):$uId;
		$shopId = (int)session('WST_USER.shopId');
		$orders = $this->alias('o')->join('__EXPRESS__ e','o.expressId=e.expressId','left')
		               ->join('__ORDER_REFUNDS__ orf ','o.orderId=orf.orderId and orf.refundStatus=1','left')
		               ->where('o.dataFlag=1 and o.orderId='.$orderId.' and ( o.userId='.$userId.')')
		               ->field('o.*,e.expressName,orf.refundRemark,orf.refundTime,orf.backMoney')->find();
		if(empty($orders))return WSTReturn("无效的订单信息");
		$orders = $orders->toArray();
		//获取订单信息
		$orders['log'] =Db::name('log_orders')->where('orderId',$orderId)->order('logId asc')->select();
		//获取订单商品
		$orders['goods'] = Db::name('order_goods')->where('orderId',$orderId)->order('id asc')->select();
		//如果是虚拟商品
		if($orders['orderType']==1){
			foreach ($orders['goods'] as $key => $v) {
				$orders['goods'][$key]['extraJson'] = json_decode($v['extraJson'],true);
			}
		}
		hook('beforeViewOrderDetail',['order'=>&$orders]);
		return $orders;
	}



	/**
	* 根据订单id获取 商品信息跟商品评价
	*/
	public function getOrderInfoAndAppr($uId=0){
		$orderId = (int)input('oId');
		$userId = ($uId==0)?(int)session('WST_USER.userId'):$uId;

		$goodsInfo = Db::name('order_goods')
					->field('id,orderId,goodsName,goodsId,goodsSpecNames,goodsImg,goodsSpecId,goodsCode')
					->where(['orderId'=>$orderId])
					->select();
		//根据商品id 与 订单id 取评价
		$alreadys = 0;// 已评价商品数
		$count = count($goodsInfo);//订单下总商品数
		if($count>0){
			foreach($goodsInfo as $k=>$v){
				$goodsInfo[$k]['goodsSpecNames'] = str_replace('@@_@@', ';', $v['goodsSpecNames']);
				$appraise = Db::name('goods_appraises')
							->field('goodsScore,serviceScore,timeScore,content,images,createTime')
							->where(['goodsId'=>$v['goodsId'],
							         'goodsSpecId'=>$v['goodsSpecId'],
									 'orderId'=>$orderId,
									 'dataFlag'=>1,
									 'userId'=>$userId,
									'orderGoodsId'=>$v['id']
									 ])->find();
				if(!empty($appraise)){
					++$alreadys;
					$appraise['images'] = ($appraise['images']!='')?explode(',', $appraise['images']):[];
				}
				$goodsInfo[$k]['appraise'] = $appraise;
			}
		}
		return ['count'=>$count,'Rows'=>$goodsInfo,'alreadys'=>$alreadys];

	}
	
	/**
	 * 检查订单是否已支付
	 */
	public function checkOrderPay ($uId=0,$orderId=0){
		$userId = ($uId==0)?(int)session('WST_USER.userId'):$uId;
		if($orderId==0)$orderId = input("id/d",0);
		$rs = array();
		$where = ["userId"=>$userId,"dataFlag"=>1,"orderStatus"=>-2,"isPay"=>0,"payType"=>1];
		$where['orderId'] = $orderId;
		
		$rs = $this->field('orderId,orderNo')->where($where)->select();
		if(count($rs)>0){
			return WSTReturn('',1);
		}else{
			return WSTReturn('订单已支付',-1);
		}
	}
	/**
	* 获取用户各订单状态数
	*/
	public function getOrderStatusNum(){
		$userId = session('WST_USER.userId');
		$data = [];
		//  -3:用户拒收 -2:未付款的订单  -1：用户取消 0:待发货 1:配送中 2:用户确认收货
		$data['waitPay'] = Db::name('orders')->where(['userId'=>$userId,'orderStatus'=>-2,'dataFlag'=>1])->count();
		$data['waitSend'] = Db::name('orders')->where(['userId'=>$userId,'orderStatus'=>0,'dataFlag'=>1])->count();
		$data['waitReceive'] = Db::name('orders')->where(['userId'=>$userId,'orderStatus'=>1,'dataFlag'=>1])->count();
		$data['waitAppr'] = Db::name('orders')->where(['userId'=>$userId,'orderStatus'=>2,'isAppraise'=>0,'dataFlag'=>1])->count();
		$data['reject'] = Db::name('orders')->where(['userId'=>$userId,'orderStatus'=>-3,'dataFlag'=>1])->count();
		return $data;
	}
	

	/**
	 * 完成支付订单
	 */
	public function complatePay ($obj){
		$trade_no = $obj["trade_no"];
		$orderId = $obj["out_trade_no"];
		$userId = (int)$obj["userId"];
		$payFrom = $obj["payFrom"];
		$payMoney = (float)$obj["total_fee"];
	
		if($payFrom!=''){
			$cnt = model('orders')
			->where(['payFrom'=>$payFrom,"userId"=>$userId,"tradeNo"=>$trade_no])
			->count();
			if($cnt>0){
				return WSTReturn('订单已支付',-1);
			}
		}
		$where = ["userId"=>$userId,"dataFlag"=>1,"orderStatus"=>-2,"isPay"=>0,"payType"=>1,"needPay"=>[">",0]];
		$where['orderId'] = $orderId;
		
		$order = model('orders')->where($where)->find();
	    $needPay = $order->needPay;
		if($needPay>$payMoney){
			return WSTReturn('支付金额不正确',-1);
		}
		Db::startTrans();
		try{
			//修改订单状态
			$order->needPay = 0;
			$order->isPay = 1;
			$order->orderStatus = 0;
			$order->tradeNo = $trade_no;
			$order->payFrom = $payFrom;
			$rs = $order->save();
				
			//新增订单日志
			$logOrder = [];
			$logOrder['orderId'] = $orderId;
			$logOrder['orderStatus'] = 0;
			$logOrder['logContent'] = "支付成功，等待商家发货";
			$logOrder['logUserId'] = $userId;
			$logOrder['logType'] = 0;
			$logOrder['logTime'] = date('Y-m-d H:i:s');
			Db::name('log_orders')->insert($logOrder);
            
            //创建一条充值流水记录
			$lm = [];
			$lm['targetType'] = 0;
			$lm['targetId'] = $order->userId;
			$lm['dataId'] = $orderId;
			$lm['dataSrc'] = 1;
			$lm['remark'] = '交易订单【'.$order->orderNo.'】充值¥'.$needPay;
			$lm['moneyType'] = 1;
			$lm['money'] = $needPay;
			$lm['payType'] = $payFrom;
			$lm['tradeNo'] = $trade_no;
			$lm['createTime'] = date('Y-m-d H:i:s');
			model('LogMoneys')->create($lm);

			//创建一条支出流水记录
			$lm = [];
			$lm['targetType'] = 0;
			$lm['targetId'] = $userId;
			$lm['dataId'] = $orderId;
			$lm['dataSrc'] = 1;
			$lm['remark'] = '交易订单【'.$order->orderNo.'】支出¥'.$needPay;
			$lm['moneyType'] = 0;
			$lm['money'] = $needPay;
			$lm['payType'] = 0;
			$lm['createTime'] = date('Y-m-d H:i:s');
			model('LogMoneys')->create($lm);
            //虚拟商品处理
	        if($order->orderType==1){
	            $this->handleVirtualGoods($orderId);
	        }else{
	        	//判断是否需要发送管理员短信
		        $tpl = WSTMsgTemplates('PHONE_ADMIN_PAY_ORDER');
		        if((int)WSTConf('CONF.smsOpen')==1 && (int)WSTConf('CONF.smsPayOrderTip')==1 && $tpl['tplContent']!='' && $tpl['status']=='1'){
					$params = ['tpl'=>$tpl,'params'=>['ORDER_NO'=>$order->orderNo]];
					$staffs = Db::name('staffs')->where(['staffId'=>['in',explode(',',WSTConf('CONF.payOrderTipUsers'))],'staffStatus'=>1,'dataFlag'=>1])->field('staffPhone')->select();
					for($i=0;$i<count($staffs);$i++){
						if($staffs[$i]['staffPhone']=='')continue;
						$m = new LogSms();
					    $rv = $m->sendAdminSMS(0,$staffs[$i]['staffPhone'],$params,'complatePay','');
					}
		        }
				//判断是否需要发送给管理员消息
			    if((int)WSTConf('CONF.wxenabled')==1 && (int)WSTConf('CONF.wxPayOrderTip')==1){
			        $params = [];
			        $params['ORDER_NO'] = $order->orderNo;
					$params['PAY_TIME'] = date('Y-m-d H:i:s');             
					$params['MONEY'] = $needPay;
					$params['PAY_SRC'] = WSTLangPayFrom($payFrom);
				    WSTWxBatchMessage(['CODE'=>'WX_ADMIN_ORDER_PAY','userType'=>1,'userId'=>explode(',',WSTConf('CONF.payOrderTipUsers')),'params'=>$params]);
				}
	        }
			Db::commit();
			return WSTReturn('支付成功',1);
		}catch (\Exception $e) {
			Db::rollback();
			return WSTReturn('操作失败',-1);
		}
	}
	
	/**
	 * 获取支付订单信息
	 */
	public function getPayOrders ($obj){
		$userId = (int)$obj["userId"];
		$orderId = $obj["orderId"];
		$needPay = 0;
		$where = ["userId"=>$userId,"dataFlag"=>1,"orderStatus"=>-2,"isPay"=>0,"payType"=>1,"needPay"=>[">",0]];
		$where['orderId'] = $orderId;
		$data = array();
		$data["needPay"] = model('orders')->where($where)->sum('needPay');
		$data["payRand"] = model('orders')->where($where)->max('payRand');
		return $data;
	}
	
	/**
	 * 余额支付
	 */
	public function payByWallet($uId=0){
		$payPwd = input('payPwd');
		$pkey = input('pkey');
        $orderId = (int)WSTBase64urlDecode($pkey);
		if($orderId==0){
			$orderId = input("id/d");
		}
		$userId = (int)session('WST_USER.userId');
		/*************************** 处理APP *******************************/
		if($uId>0){
			$userId = $uId;
			$orderId = (int)input('orderNo');
		}
		//判断是否开启余额支付
		$isEnbalePay = model('common/payments')->isEnablePayment('wallets');
		if($isEnbalePay==0)return WSTReturn('非法的支付方式',-1);
		//判断订单状态
		$where = ["userId"=>$userId,"dataFlag"=>1,"orderStatus"=>-2,"isPay"=>0,"payType"=>1];
		$where['orderId'] = $orderId;
		$orders = $this->field('orderId,orderNo,orderType,needPay,payFrom,realTotalMoney')->where($where)->find();
		if(empty($orders))return WSTReturn('您的订单已支付',-1);
		//判断订单金额是否正确
		$needPay = $orders['needPay'];
		//获取用户钱包
		$user = model('users')->get($userId);
		if($user->payPwd=='')return WSTReturn('您未设置支付密码，请先设置密码',-1);
		if($user->payPwd!=md5($payPwd.$user->loginSecret))return WSTReturn('您的支付密码不正确',-1);
		if($needPay > $user->userMoney)return WSTReturn('您的钱包余额不足',-1);
		$rechargeMoney = $user->rechargeMoney;
		Db::startTrans();
		try{
			//处理订单信息
			$tmpNeedPay = $orders->needPay;
			$lockCashMoney = ($rechargeMoney>$tmpNeedPay)?$tmpNeedPay:$rechargeMoney;
			$orders->needPay = 0;
			$orders->isPay = 1;
			$orders->orderStatus = 0;
			$orders->payFrom = 'wallets';
			$orders->lockCashMoney = $lockCashMoney;
			$result = $orders->save();
			if(false != $result){
				//新增订单日志
				$logOrder = [];
				$logOrder['orderId'] = $orders->orderId;
				$logOrder['orderStatus'] = 0;
				$logOrder['logContent'] = "支付成功，等待商家发货";
				$logOrder['logUserId'] = $userId;
				$logOrder['logType'] = 0;
				$logOrder['logTime'] = date('Y-m-d H:i:s');
				Db::name('log_orders')->insert($logOrder);
				//创建一条支出流水记录
				$lm = [];
				$lm['targetId'] = $userId;
				$lm['dataId'] = $orders->orderId;
				$lm['dataSrc'] = 1;
				$lm['remark'] = '交易订单【'.$orders->orderNo.'】支出¥'.$tmpNeedPay;
				$lm['moneyType'] = 0;
				$lm['money'] = $tmpNeedPay;
				$lm['payType'] = 'wallets';
				model('LogMoneys')->add($lm);
				//修改用户充值金额
				model('users')->where(["userId"=>$userId])->setDec("rechargeMoney",$lockCashMoney);
				//虚拟商品处理
		        if($orders->orderType==1){
		            $this->handleVirtualGoods($orderId);
		        }else{
					//判断是否需要发送管理员短信
		            $tpl = WSTMsgTemplates('PHONE_ADMIN_PAY_ORDER');
		            if((int)WSTConf('CONF.smsOpen')==1 && (int)WSTConf('CONF.smsPayOrderTip')==1 && $tpl['tplContent']!='' && $tpl['status']=='1'){
						$params = ['tpl'=>$tpl,'params'=>['ORDER_NO'=>$orders->orderNo]];
						$staffs = Db::name('staffs')->where(['staffId'=>['in',explode(',',WSTConf('CONF.payOrderTipUsers'))],'staffStatus'=>1,'dataFlag'=>1])->field('staffPhone')->select();
						for($i=0;$i<count($staffs);$i++){
							if($staffs[$i]['staffPhone']=='')continue;
						    $m = new LogSms();
					        $rv = $m->sendAdminSMS(0,$staffs[$i]['staffPhone'],$params,'payByWallet','');
					    }
		            }
					//判断是否需要发送给管理员消息
					if((int)WSTConf('CONF.wxenabled')==1 && (int)WSTConf('CONF.wxPayOrderTip')==1){					    
			            $params = [];
			            $params['ORDER_NO'] = $orders->orderNo;
						$params['PAY_TIME'] = date('Y-m-d H:i:s');             
					    $params['MONEY'] = $orders->realTotalMoney;
						$params['PAY_SRC'] = WSTLangPayFrom($orders->payFrom);
				        WSTWxBatchMessage(['CODE'=>'WX_ADMIN_ORDER_PAY','userType'=>1,'userId'=>explode(',',WSTConf('CONF.payOrderTipUsers')),'params'=>$params]);
					}
	            }
			}
			Db::commit();
			if(false != $result)hook("afterOrderPaySuccess",['orderId'=>$orders["orderId"],'uerSystem'=>[0,1],'printCatId'=>1]);
			return WSTReturn('订单支付成功',1);
		}catch (\Exception $e) {
			Db::rollback();
			return WSTReturn('订单支付失败');
		}
	}
	/**
	 * 获取订单金额以及用户钱包金额
	 */
	public function getOrderPayInfo($obj){
        $userId = (int)$obj["userId"];
		$orderId = $obj["orderNo"];
		$isBatch = (int)$obj["isBatch"];
		$needPay = 0;
		$where = ["userId"=>$userId,"dataFlag"=>1,"orderStatus"=>-2,"isPay"=>0,"payType"=>1,"needPay"=>[">",0]];
		$where['orderId'] = $orderId;
		$orders = model('orders')->where($where)->field('needPay,payRand')->select();
		if(empty($orders))return [];
		$needPay = 0;
		$payRand = 0;
		foreach($orders as $order){
            $needPay += $order['needPay'];
            if($payRand<$order['payRand'])$payRand = $order['payRand'];
		}
		$data = array();
		$data["needPay"] = $needPay;
		$data["payRand"] = $payRand;
		return $data;
	}
	/**
	 * 检查订单是否已支付【APP】
	 */
	public function checkOrderPay2 ($obj){
		$userId = $obj["userId"];
		$orderNo = $obj["orderId"];
		$rs = array();
		$where = ["userId"=>$userId,"dataFlag"=>1,"orderStatus"=>-2,"isPay"=>0,"payType"=>1];
		$where['orderId'] = $orderNo;
		$rs = $this->field('orderId,orderNo')->where($where)->select();
		if(count($rs)>0){
			return WSTReturn('',1);
		}else{
			return WSTReturn('订单已支付',-1);
		}
	}
	public function getOrderPayFrom($out_trade_no){
		$rs = $this->where(['dataFlag'=>1,'orderId'=>$out_trade_no])->field('orderId,userId')->find();
		if(!empty($rs)){
			$rs['isBatch'] = ($rs['orderId'] == $out_trade_no)?1:0;
		}
		return $rs;
	}
	/**
	* 用户-提醒发货
	*/
	public function noticeDeliver($uId=0){
		$orderId = (int)input('id');
		$userId = ($uId==0)?(int)session('WST_USER.userId'):$uId;
		$rs = $this->where(['userId'=>$userId,'orderId'=>$orderId])->setField('noticeDeliver',1);
		if($rs!==false){
			return WSTReturn('提醒成功',1);
		}
		return WSTReturn('提醒失败',-1);
	}

}
