<?php
namespace app\mainapp\controller;

use think\facade\Session;
use think\facade\Log;
use app\mainapp\BaseController;

use app\common\model\User as UserModel;
use app\common\model\MallOrder as MallOrderModel;
use app\common\model\UserIntegral as UserIntegralModel;

use echowx\WxPay; 

class Notify extends BaseController
{
  
	// 订单处理
	public function setOrder($ordersn, $payinfo)
	{
		$snfirst = substr($ordersn , 0 , 1);
		if ($snfirst==="M"){
			// 聘豆商城订单
			$order = MallOrderModel::where('ordersn','=',$ordersn)->findOrEmpty();
			if ($order->isEmpty()){
				return false;
			}elseif ($order->status>2){
				return true;
			}
			$order->save([
				'status'	=> 3,
				'payinfo'	=> $payinfo
			]);
			return true;
		
		}elseif($snfirst==="R") {
			// 聘豆充值
			$order = UserIntegralModel::where('remark','=',$ordersn)->findOrEmpty();
			if ($order->isEmpty()){
				return false;
			}elseif ($order->itype!=2 || $order->status!=1){
				return true;
			}
			$order->save([
				'status'	=> 2
			]);
			$user = UserModel::findOrEmpty($order->userid);
			$integral = intval($user->integral) + $order->intvalue;
			$inttotal = intval($user->inttotal) + $order->intvalue;
			$user->save([
				'integral' => $integral,
				'inttotal' => $inttotal
			]);
			return true;
			
		}else{
			return false;
		}
	}


	//微信支付
    public function orderWechat()
    {
		$wxpay = new WxPay();
		$verify = $wxpay->notify();
		if ($verify['status']!=1){
			Log::pay($verify['data']); 
		}else{
			$ordersn = $verify['data']['out_trade_no'];
			$log = $ordersn.':::::::'.mb_convert_encoding(json_encode(gbk2utf8($verify['data'])), 'UTF-8', 'auto');
			Log::pay($log);
			if ($verify['data']['return_code'] == 'SUCCESS' && $verify['data']['result_code'] == 'SUCCESS') {
				$payinfo = array(
					'cash_fee'			=> $verify['data']['cash_fee'],
					'openid'			=> $verify['data']['openid'],
					'out_trade_no'		=> $verify['data']['out_trade_no'],
					'transaction_id'	=> $verify['data']['transaction_id'] 
				);
				$result = $this->setOrder($ordersn, $payinfo); 
				if ($result == true){
					$wxpay->reply_notify();
				}
			}
		}
    }

}
