<?php

namespace App\Http\Controllers\Wechat\Pay;

use EasyWeChat\Payment\Order;
use App\Http\Requests;
use App\Http\Controllers\WechatController;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Message\Text;

/**
 * 微信支付
 */
class PaysController extends WechatController
{
	public $payment;
	public $options;
	public function __construct()
	{
		$this->options = array();
		parent::__construct();
	}
	
	function set_options($appid){
	    $this->options = [];
		
		return $this->options;
	}
	
    /**
     * 接收微信回调
     * @return Response
     */
    public function index(Request $request)
    {
//     	if($request->has('echostr')) exit($request->input('echostr'));echostr
    	v('start_check_sign');
    	v($request->all());
    	$echostr = $request->get('echostr');
    	if(!empty($echostr)){
    		echo $echostr;exit();
    	}
        if(!$this->checkSignature($request)){
        	v('return_fail:');
//         	exit;
        }else{
        	v('return_success:');
        }
    	
    	v('start_setmessagehander:'.$this->local_test);
    	
    	if(env('DEVELOP_MODE') == 'local'){
    		$notify = $this->get_fake_data();
    		$res = $this->deal_callback($notify,true);
    	}else{
    		v('start-payment');
			$response = $this->payment->handleNotify(function($notify, $successful){
			    return $this->deal_callback($notify,$successful);
			});
			return $response;
    	}
    	
		v('last_echo');
    }
    
    function deal_callback($notify,$successful){
    	    v('wxpay_deal_callback_in');
    	    v('notify:');v($notify);v('successful:'.$successful);
			return true; // 返回处理完成
    }
    
    function notify(Request $request){
    	v('wxpay_notify');v($request->all());
    	echo 'success';
    }

    
    /**
     * @api {get} /create_wxpay_order?body=:body&detail=:detail&total_fee=:total_fee&open_id=:open_id 创建交易订单
     * @apiName create_wxpay_order
     * @apiGroup Bag
     * @apiDescription
     * 创建订单，返回的是支付的config数组
     * @apiParam {String} body 支付简要描述.
     * @apiParam {String} detail 支付详细描述.
     * @apiParam {String} total_fee 支付金额（单位分）.
     * @apiParam {String} open_id 用户open_id.

     * @apiSuccess {String} appId .
     * @apiSuccess {String} nonceStr  .
     * @apiSuccess {String} package  .
     * @apiSuccess {String} signType  .
     * @apiSuccess {String} paySign .
     * @apiSuccess {String} timestamp  .
     */
  /**
http://auth.aizhuishu.com/pay/create_wxpay_order?out_trade_no=2017120917571001&body=%E6%B5%8B%E8%AF%95%E4%B8%8B%E8%80%8C%E5%B7%B2&detail=%E6%B5%8B%E8%AF%95%E4%B8%8B%E7%88%B1%E8%BF%BD%E4%B9%A6%E5%BE%AE%E4%BF%A1%E6%94%AF%E4%BB%98&total_fee=1&appid=wx2538d0bc2ea3089e&open_id=oc5mg0xkIlKEMDkQL39RSLXhfatM&notify_url=http%3A%2F%2Fpay.aizhuishu.com%2Fpay%2Fnotify&timestamp=1512788565&sign=c2da337c73393dbd51ef2d58559daa15
http://zydy/pay/create_wxpay_order?out_trade_no=2017120917571001&body=%E6%B5%8B%E8%AF%95%E4%B8%8B%E8%80%8C%E5%B7%B2&detail=%E6%B5%8B%E8%AF%95%E4%B8%8B%E7%88%B1%E8%BF%BD%E4%B9%A6%E5%BE%AE%E4%BF%A1%E6%94%AF%E4%BB%98&total_fee=1&appid=wx2538d0bc2ea3089e&open_id=oc5mg0xkIlKEMDkQL39RSLXhfatM&notify_url=http%3A%2F%2Fpay.aizhuishu.com%2Fpay%2Fnotify&timestamp=1512788565&sign=c2da337c73393dbd51ef2d58559daa15
http://zydy/pay/create_wxpay_order?out_trade_no=2017120917571002&body=%E6%B5%8B%E8%AF%95%E4%B8%8B%E8%80%8C%E5%B7%B2&detail=%E6%B5%8B%E8%AF%95%E4%B8%8B%E7%88%B1%E8%BF%BD%E4%B9%A6%E5%BE%AE%E4%BF%A1%E6%94%AF%E4%BB%98&total_fee=1&appid=wx2538d0bc2ea3089e&open_id=oc5mg0xkIlKEMDkQL39RSLXhfatM&notify_url=http%3A%2F%2Fauth.aizhuishu.com%2Fpay%2Fnotify&timestamp=1512788565&sign=c2da337c73393dbd51ef2d58559daa15

    */
    function create_wxpay_order(Request $request){
    	$result = array('code'=>1,'msg'=>'','data'=>'');
    	$body = $request->get('body');
    	$detail = $request->get('detail');
    	$total_fee = $request->get('total_fee');
    	$open_id = $request->get('open_id');
    	$appid = $request->get('appid');
    	$out_trade_no = $request->get('out_trade_no');
    	$attach = $request->get('attach');
    	$is_call_pay = $request->get('is_call_pay');//是否直接唤起
    	$notify_url = $request->get('notify_url');
    	$redirect_url = $request->get('redirect_url');
    	
    	if(empty($open_id) || empty($notify_url)  || empty($redirect_url) || empty($appid) || empty($out_trade_no)){
    		$result['code'] = 0;
    		$result['msg'] = 'invalid param';
    		v('invalid_param_open_id:'.$open_id);
    		json_echo($result);
    	}
    	
    	$this->set_options($appid);
    	if(empty($this->options)){
    		$result['code'] = 0;
    		$result['msg'] = 'invalid appid';
    		v('invalid_param_open_id:'.$open_id.' appid:'.$appid);
    		json_echo($result);
    	}
    	
    	$check_result = $this->check_sign_params($request);
    	if($check_result['code'] == 0){
    		$result['code'] = 0;
    		$result['msg'] = $check_result['msg'];
    		json_echo($result);
    	}

    	$attributes = [
	    	'trade_type'       => 'JSAPI', // JSAPI，NATIVE，APP...
	    	'body'             => $body,
	    	'detail'           => $detail,
	    	'out_trade_no'     => $out_trade_no,
	    	'total_fee'        => $total_fee, // 单位：分
	    	'attach'        => $attach	, // 附加参数，127字符
	    	'openid'           => $open_id, // trade_type=JSAPI，此参数必传，用户在商户appid下的唯一标识，
	    	// ...
    	];
    	v('attributes:');v($attributes);
    	$order = new Order($attributes);
    	
    	$this->options['payment']['notify_url'] = urldecode($notify_url);
    	$app = new Application($this->options);
    	$this->payment = $app->payment;
    	
    	// 创建订单
    	$prepare_result = $this->payment->prepare($order);
    	v('$prepare_result:');v($prepare_result);
    	$prepayId = '';
    	if ($prepare_result->return_code == 'SUCCESS' && $prepare_result->result_code == 'SUCCESS'){
    		$prepayId = $prepare_result->prepay_id;
    	}else{
    		$result['code'] = 0;
    		$result['msg'] = 'prepare order fail';
    		v('prepare_order_fail:'.$attributes['out_trade_no']);
    		json_echo($result);
    	}
    	v('prepayId:'.$prepayId);
    	
    	$config = $this->payment->configForJSSDKPayment($prepayId); // 返回数组
    	v('config:');v($config);
    	
    	// 状态没问题则创建订单
    	if(!empty($config)){

    	}else{
    		$result['code'] = 0;
    		$result['msg'] = 'configForJSSDKPayment fail';
    		v('configForJSSDKPayment_fail:'.$attributes['out_trade_no']);
    		json_echo($result);
    	}
    	$result['data'] = $config;
    	
    	v('create_result:');v($result);
    	if(!$is_call_pay){
    		json_echo($result);
    	}else{
    		$pay_info = array();
    		$pay_info['appId'] = $config['appId'];
    		$pay_info['timeStamp'] = $config['timestamp'];
    		$pay_info['nonceStr'] = $config['nonceStr'];
    		$pay_info['package'] = $config['package'];
    		$pay_info['paySign'] = $config['paySign'];
    		$pay_info['pay_redirect_url'] = $redirect_url;
    		 
    		return view('pay.order.index',compact('pay_info'));
    	}
    	
    }
    
    
    /**
     * @api {get} /bag/create_wxpay_order_refund?out_trade_no=:out_trade_no&timestamp=:timestamp&sign=:sign 交易退款
     * @apiName create_wxpay_order_refund
     * @apiGroup Bag
     * @apiDescription
     * 创建微信退款订单(暂时不需要)
     * @apiParam {String} out_trade_no 支付订单号.
     * @apiParam {String} timestamp 时间戳.
     * @apiParam {String} sign 签名.
    
     */
    // 暂时不管：可能会遇到这个问题，交易未结算资金不足，请使用可用余额退款
    function create_wxpay_order_refund(Request $request){
    	$result = array('code'=>1,'msg'=>'','data'=>'');
    	$out_trade_no = $request->get('out_trade_no');
    	$timestamp = $request->get('timestamp');
    	$sign = $request->get('sign');
    	 
    	if(empty($out_trade_no) || empty($timestamp) || empty($sign)){
    		$result['code'] = 0;
    		$result['msg'] = 'invalid param';
    		v('invalid_param_out_trade_no:'.$out_trade_no);
    		json_echo($result);
    	}
    	
    	$param = array();
    	$param['out_trade_no'] = $out_trade_no;
    	$param['timestamp'] = $timestamp;
    	$my_sign = $this->WxSign->get_sign($param);
    	if($sign != $my_sign){
    		$result['code'] = 0;
    		$result['msg'] = 'invalid sign';
    		v('create_wxpay_order_refund_sign_error:'.$out_trade_no.' $sign:'.$sign.' $my_sign:'.$my_sign);
    		json_echo($result);
    	}

    	$refund_no = get_orderno_by_time();
    	$total_fee = $wx_pay_record->total_fee;
    	$refund_fee = $total_fee;
    	$open_id = $wx_pay_record->open_id;
    	v('refund:out_trade_no:'.$out_trade_no.' refund_no:'.$refund_no.' total_fee:'.$total_fee.' refund_fee:'.$refund_fee.' open_id:'.$open_id);
    
        $refund_result = $this->payment->refund($out_trade_no, $refund_no, $total_fee, $total_fee); 
//         $refund_result = $this->get_fake_refund_data();
        v('$refund_result');v($refund_result);
        
        if ($refund_result->return_code == 'SUCCESS' && $refund_result->result_code == 'SUCCESS'){
        	$refund_result->open_id = $open_id;
//         	WxRefundRecord::save_wx_refund_record($refund_result);
        }else{
        	$result['code'] = 0;
        	$result['msg'] = 'refund fail';
        	v('refund_fail:'.$out_trade_no);
        	json_echo($result);
        }
        
    	$result['data'] = 'refund success';
    	json_echo($result);
    }
    
    /**
     * 查询退款结果
     */
    //http://wread/pay/query_refund?out_trade_no=201705171025468688026&timestamp=12&sign=2cb2d01ae367265a1dbdd663e1d32415
    function query_refund(Request $request){
    	$out_trade_no = $request->get('out_trade_no');
    	$timestamp = $request->get('timestamp');
    	$sign = $request->get('sign');
    	if(empty($out_trade_no) || empty($timestamp) || empty($sign)){
    		$result['code'] = 0;
    		$result['msg'] = 'invalid param';
    		v('invalid_param_out_trade_no:'.$out_trade_no);
    		json_echo($result);
    	}
    	
    	$param = array();
    	$param['out_trade_no'] = $out_trade_no;
    	$param['timestamp'] = $timestamp;
    	$my_sign = $this->WxSign->get_sign($param);
    	if($sign != $my_sign){
    		$result['code'] = 0;
    		$result['msg'] = 'invalid sign';
    		v('query_refund_sign_error:'.$out_trade_no.' $sign:'.$sign.' $my_sign:'.$my_sign);
    		json_echo($result);
    	}
    	
    	$query_refund_result = $this->payment->queryRefund($out_trade_no);
    	v('query_refund_result:');v($query_refund_result);
    	 
    }
    
    
    private function checkSignature($request)
    {
    	$signature = $request->get('signature');
    	$timestamp = $request->get('timestamp');
    	$nonce = $request->get('nonce');
    	$echostr = $request->get('echostr');
    	 
    	//     	$token = 'd4352c0225d5da500b176cf3464e9822';
    	$tmpArr = array($this->token, $timestamp, $nonce);
    	sort($tmpArr, SORT_STRING);
    	$tmpStr = implode( $tmpArr );
    	$tmpStr = sha1( $tmpStr );
    	v('$tmpStr:'.$tmpStr);
    
    	if( $tmpStr == $signature ){
    		return true;
    	}else{
    		return false;
    	}
    }
    
    function get_fake_data(){
    	$message = new \stdClass();
    	$message->out_trade_no = '201705261556493599255';
    	 
    	return $message;
    }
    
    //"return_code":"SUCCESS","return_msg":"OK","appid":"wx27c650c50a36cc46","mch_id":"1468320702","nonce_str":"DNMs2GFrmZilOy8w","sign":"B1F25F070184B94202D67D3722057850","result_code":"SUCCESS","transaction_id":"4005562001201705171197097763","out_trade_no":"201705171025468688026","out_refund_no":"201705181118027912184","refund_id":"50000302912017051801101133889","refund_channel":null,"refund_fee":"500","coupon_refund_fee":"0","total_fee":"500","cash_fee":"500","coupon_refund_count":"0","cash_refund_fee":"500"}
    function get_fake_refund_data(){
    	$refund_result = new \stdClass();
    	$refund_result->return_code = 'SUCCESS';
    	$refund_result->result_code = 'SUCCESS';
    	$refund_result->transaction_id = '4005562001201705171197097763';
    	$refund_result->out_trade_no = '201705171025468688026';
    	$refund_result->out_refund_no = '201705181118027912184';
    	$refund_result->refund_id = '50000302912017051801101133889';
    	$refund_result->refund_channel = '';
    	$refund_result->refund_fee = '500';
    	$refund_result->coupon_refund_fee = '0';
    	$refund_result->total_fee = '500';
    	$refund_result->cash_fee = '500';
    	$refund_result->coupon_refund_count = '0';
    	$refund_result->cash_refund_fee = '500';
    	$refund_result->return_msg = 'OK';
    	$refund_result->appid = 'wx27c650c50a36cc46';
    	$refund_result->mch_id = '1468320702';
    	$refund_result->nonce_str = 'DNMs2GFrmZilOy8w';
    	$refund_result->sign = 'B1F25F070184B94202D67D3722057850';
    	
    	return $refund_result;
    }
    
}
