<?php namespace Pay\Lib;
use Dever;
Dever::apply('sdk/alipay', 'pay');

class Alipay extends Core
{
	private $signType = 'RSA2';
	public function __construct($config)
	{
		$project = Dever::project('pay');
		# 通知接口
		$config['notify'] = $this->url($config['type'], $config['id']);
		$this->config = $config;
	}

	/**
	 * 通知
	 */
	public function notify()
	{
		$type = Dever::input('type');
		if ($type == 1) {
			$input = $_GET;
			unset($input['account_id']);
			$result = $this->check($input);
			if ($result) {
				$status = 1;
			} else {
				$status = 2;
			}
			$refer = Dever::input('refer');
			$refer = urldecode($refer) . '&status=' . $status;
			Dever::location($refer);
		} else {
			$input = $_POST;
			if (!$input) {
				echo 'fail';die;
			}
			unset($input['account_id']);
			$this->log('支付回调-初始化', $input);

			$result = $this->check($input);

			if ($result) {
				$this->log('支付回调-获取数据', $result);

				if($input['trade_status'] == 'TRADE_FINISHED') {
					#退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
					$this->updateOrder($result['out_trade_no'], $result['total_amount'], '已超过退款期限');
				} elseif ($input['trade_status'] == 'TRADE_SUCCESS') {
					#付款完成后，支付宝系统发送该交易状态通知
					$this->updateOrder($result['out_trade_no'], $result['total_amount']);
				}
				
				echo 'success';die;
			} else {
				echo 'fail';die;
			}
		}
	}

	/**
	 * 获取统一下单的基本信息
	 */
	public function order($account_id, $project_id, $uid, $username, $product_id, $name, $cash, $openid = false, $type = 1, $order_id = false, $other = false, $refer = false)
	{
		$order_id = $this->createOrder($uid, $username, $account_id, $project_id, $product_id, $name, $cash, $this->config['type'], $order_id);

		$request['out_trade_no'] = $order_id;
		$request['body'] = $name;
		$request['total_amount'] = $cash;
		$request['subject'] = $name;
		$request['timeout_express'] = $this->config['timeout'];
		$content = json_encode($request, JSON_UNESCAPED_UNICODE);

		$request = new \AlipayTradeWapPayRequest();
	
		$request->setNotifyUrl($this->config['notify']);
		$request->setReturnUrl($this->config['refer']);
		$request->setBizContent($content);

		if ($type == 1) {
			$result = $this->aop(2)->pageExecute($request, 'post');
		} else {
			$result = $this->aop(2)->Execute($request);
		}

		return $result;
	}

	private function aop()
    {
    	$type = 1;
    	if ($this->config['appCertPath'] && $this->config['alipayCertPath'] && $this->config['rootCertPath']) {
    		$type = 2;
    	}
        if ($type == 2) {
            $this->aop = new \AopCertClient();
        } else {
            $this->aop = new \AopClient();
        }

        $this->aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
        if ($this->config['box'] == 2) {
            $this->aop->gatewayUrl = 'https://openapi.alipaydev.com/gateway.do';
        }
        
        $this->aop->appId = $this->config['appid'];
        $this->aop->signType = $this->signType;
        // 开启页面信息输出
        $this->aop->debugInfo = true;

        if ($type == 2) {
            $appCertPath = Dever::local($this->config['appCertPath']);
            $alipayCertPath = Dever::local($this->config['alipayCertPath']);
            $rootCertPath = Dever::local($this->config['rootCertPath']);

            if (is_file($appCertPath)) {
                $this->aop->alipayrsaPublicKey = $this->aop->getPublicKey($alipayCertPath);
                $this->aop->isCheckAlipayPublicCert = true;//是否校验自动下载的支付宝公钥证书，如果开启校验要保证支付宝根证书在有效期内
                $this->aop->appCertSN = $this->aop->getCertSN($appCertPath);//调用getCertSN获取证书序列号
                $this->aop->alipayRootCertSN = $this->aop->getRootCertSN($rootCertPath);//调用getRootCertSN获取支付宝根证书序列号
            }
        } else {
        	$this->aop->rsaPrivateKey = $this->config['private_key'];
        	$this->aop->alipayrsaPublicKey = $this->config['public_key'];
        }

        return $this->aop;
    }

	/**
	 * 获取二维码支付
	 */
	public function qrcode($order, $refer)
	{
		$notify = new \NativePay();
		$result = $notify->GetPayUrl($order);
		$url = $result['code_url'];
		return $url;
	}

	/**
	 * 获取小程序支付
	 */
	public function applet($order)
	{
		$result = array();
		return $result;
	}


	/**
	 * 获取页面支付
	 */
	public function page($order, $refer)
	{
		return $order;
	}

	private function check($data)
	{
		$result = $this->aop()->rsaCheckV1($data, $this->config['public_key'], $this->signType);
		return $result;
	}

	# 退款
	public function refund($order_id, $cash, $order, $refund_order_id = false)
	{
		$out_trade_no = $order_id;
		$cash = $cash * 100;
		$total_fee = $cash;
		$refund_fee = $cash;
		$input = new \WxPayRefund();
		$input->SetOut_trade_no($out_trade_no);
		$input->SetTotal_fee($total_fee);
		$input->SetRefund_fee($refund_fee);

	    $input->SetOut_refund_no($out_trade_no . '_' . time());
	    $input->SetOp_user_id($this->config->GetMerchantId());
		$result = \WxPayApi::refund($this->config, $input);
		return $result;
	}
}