<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/19
 * Time: 16:37
 */
namespace app\web\controller;
use think\Db;

header('Access-Control-Allow-Origin:https://open.weixin.qq.com');
class WxpayController extends MainController{

    public function __construct()
    {
        parent::__construct();
        require_once CMF_ROOT.'vendor/wxpay/lib/WxPayApi.php';
        require_once CMF_ROOT.'vendor/wxpay/WxPayJsApiPay.php';
        require_once CMF_ROOT.'vendor/wxpay/log.php';
        require_once CMF_ROOT.'vendor/wxpay/lib/WxPay.Config.php';
    }


    //统一下单
    public function pay_order()
    {
        $id=$this->request->param('id');
        if(!isset($id)||empty($id)){
            $this->api_return_json(array('msg'=>'该订单id不存在')) ;
        }
        $order=Db::name('orders')
        ->field('o.order_sn,o.goods_id,o.hospital_id,o.appointment_time,o.pay_price,p.title,u.wx_openid')
        ->alias('o')
        ->join('goods p', 'p.id=o.goods_id', 'left')
        ->join('wx_user u', 'u.user_id=o.user_id', 'left')
        ->where(array('o.id'=>$id,'o.is_delete'=>0))
        ->find();
        if(empty($order))
        	$this->api_return_json(array('msg'=>'订单不存在'));
        //检测库存
        //总库存
        $res=db('hospital_good')->where(['good_id'=>$order['goods_id'],'hospital_id'=>$order['hospital_id'],'deleted_at'=>null])->find();
        if(empty($res))
        	$this->api_return_json(array('msg'=>'医院疫苗信息不存在'));
        //已预约库存
        $has=db('orders')->where(['goods_id'=>$order['goods_id'],'hospital_id'=>$order['hospital_id'],'appointment_time'=>$order['appointment_time'],'pay_status'=>array(1,2)])->count();
        if((int)$res['stock']<=$has)
        	$this->api_return_json(array('msg'=>'您预约时间的疫苗库存不足，请重新换个时间预约'));
        
        $order_money=$order['pay_price'];
        /*------------------------支付流程----------------------------*/
         $tools = new \JsApiPay();
	
	        //②、统一下单
	        $input = new \WxPayUnifiedOrder();
	        $input->SetBody($order['title']);
	        $input->SetOut_trade_no($order['order_sn']);
	        if ($this->is_product) {
	            $input->SetTotal_fee(((double)($order_money) * 100));
	        } else {
	            $input->SetTotal_fee(((double)(0.01) * 100));
	        }
	        //
	        $input->SetTime_start(date("YmdHis"));
	        $input->SetTime_expire(date("YmdHis", time() + 600));
	        $input->SetGoods_tag('预约疫苗');
	        $input->SetNotify_url(url('web/Notify/orderNotify','','html',true));
	        $input->SetTrade_type("JSAPI");
	
	        $input->SetSpbill_create_ip(get_client_ip());
	        $input->SetOpenid($order['wx_openid']);
	        $orders = \WxPayApi::unifiedOrder($input);
	
	        $jsApiParameters = json_decode($tools->GetJsApiParameters($orders));
        $this->api_return_json(array('pay_key' => $jsApiParameters), 1);
    }
    
    //统一下单会员
    public function pay_member_order()
    {
    	$id=$this->request->param('id');
    	if(!isset($id)||empty($id)){
    		$this->api_return_json(array('msg'=>'该订单id不存在')) ;
    	}
    	$order=Db::name('orders')
    	->field('o.order_sn,o.goods_id,o.hospital_id,o.appointment_time,o.pay_price,p.title,u.wx_openid')
    	->alias('o')
    	->join('goods p', 'p.id=o.goods_id', 'left')
    	->join('wx_user u', 'u.user_id=o.user_id', 'left')
    	->where(array('o.id'=>$id,'o.is_delete'=>0))
    	->find();
    	if(empty($order))
    		$this->api_return_json(array('msg'=>'订单不存在'));
    	//检测库存
    	//总库存
    
    	$order_money=$order['pay_price'];
    	/*------------------------支付流程----------------------------*/
    	$tools = new \JsApiPay();
    
    	//②、统一下单
    	$input = new \WxPayUnifiedOrder();
    	$input->SetBody('会员服务');
    	$input->SetOut_trade_no($order['order_sn']);
    	if ($this->is_product) {
    		$input->SetTotal_fee(((double)($order_money) * 100));
    	} else {
    		$input->SetTotal_fee(((double)(0.01) * 100));
    	}
    	//
    	$input->SetTime_start(date("YmdHis"));
    	$input->SetTime_expire(date("YmdHis", time() + 600));
    	$input->SetGoods_tag('会员');
    	$input->SetNotify_url(url('web/Notify/memberOrderNotify','','html',true));
    	$input->SetTrade_type("JSAPI");
    
    	$input->SetSpbill_create_ip(get_client_ip());
    	$input->SetOpenid($order['wx_openid']);
    	$orders = \WxPayApi::unifiedOrder($input);
    
    	$jsApiParameters = json_decode($tools->GetJsApiParameters($orders));
    	$this->api_return_json(array('pay_key' => $jsApiParameters), 1);
    }

    //申请退款
	public function apply_refund($out_trade_no='t_2018060218250996720000000001',$total_fee=1,$refund_fee=1){
		/*------------------------退款流程----------------------------*/
        file_put_contents(CMF_ROOT . "data/refund_log/refund_log.txt", date('Y-m-d H:i:s')."\n进入退款，订单号：".$out_trade_no."订单金额：".$total_fee."退款金额：".$refund_fee."\n", FILE_APPEND);
        $input = new \WxPayRefund();
			$input->SetOut_trade_no($out_trade_no);
			$input->SetTotal_fee($total_fee);
			$input->SetRefund_fee($refund_fee);
		    $input->SetOut_refund_no('1529522091'.date("YmdHis"));
		    $input->SetOp_user_id('1529522091');
			$result=\WxPayApi::refund($input);
			file_put_contents(CMF_ROOT . "data/refund_log/refund_log.txt", date('Y-m-d H:i:s')."\n退款的结果：" . json_encode($result).'退款单号：'.$out_trade_no.'退款金额：'.$refund_fee.'付款金额：'.$total_fee."\n", FILE_APPEND);
			
			if($result['return_code']=='SUCCESS' && $result['result_code']=='SUCCESS'){
				return array('return_code'=>$result['return_code'],'result_code'=>$result['result_code']);
			}else{
				return array('return_code'=>$result['return_code'],'result_code'=>$result['result_code'],'err_code_des'=>$result['err_code_des'],'return_msg'=>$result['return_msg']);
			}
			exit();
	}
	
	//发红包
	public function sendRedpackage($money,$user_id){
		header("content-type:text/html;charset=utf-8");
		$url = 'https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack';
		$user=Db::name('wx_user')->field('wx_openid2 as wx_openid')->where(array('user_id'=>$user_id))->find();
		$params = array();
		$account_key = \WxPayConfig::KEY;
		$params['nonce_str'] = md5(time() . rand(1, 9999));
		$params['wxappid'] = config('mp_wxconfig')['appid'];//wxd6053c3091d8aaaf
		$params['mch_id'] = \WxPayConfig::MCHID;
		$params['mch_billno'] = 'red'.date("YmdHis",time()).mt_rand(10,99);
		$params['send_name'] = '云货舱';
		$params['scene_id']='PRODUCT_5';
		$params['re_openid'] =$user['wx_openid'];//
		$params['total_amount'] =(int)$money*100;//分
		$params['total_num'] = 1;
		$params['wishing'] = '恭喜您提现成功';
		$params['client_ip'] = $this->real_ip();
		$params['act_name'] = '提现';
		$params['remark'] = '由于商户号3个月交易记录才能开放提现，故先采取发红包方式';
		ksort($params);
		$param_str = '';
		foreach ($params as $key => $param) {
			$param_str .= $key . '=' . $param . '&';
		}
		$sign = strtoupper(md5($param_str . 'key=' . $account_key));
		$params['sign'] = $sign;
		ksort($params);
		$xml = $this->ToXml($params);
		//$result = $this->curl_post_xml($url, $xml);
		//  echo BASEPATH.'../wx_pay/cert/apiclient_key.pem';exit;
		$result = \WxPayApi::postXmlCurl($xml, $url, true);
		$result = $this->FromXml($result);
		try{
			if($result['result_code']=='SUCCESS')
				return true;
			else 
				return false;
		}catch (\Exception $e){
			return false;
		}
		
	}
	
	 /**
	 * 获得用户的真实IP地址
	 *
	 * @access  public
	 * @return  string
	 */
	function real_ip()
	{
		static $realip = NULL;
	
		if ($realip !== NULL)
		{
			return $realip;
		}
	
		if (isset($_SERVER))
		{
			if (isset($_SERVER['HTTP_X_FORWARDED_FOR']))
			{
				$arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
	
				/* 取X-Forwarded-For中第一个非unknown的有效IP字符串 */
				foreach ($arr AS $ip)
				{
					$ip = trim($ip);
	
					if ($ip != 'unknown')
					{
						$realip = $ip;
	
						break;
					}
				}
			}
			elseif (isset($_SERVER['HTTP_CLIENT_IP']))
			{
				$realip = $_SERVER['HTTP_CLIENT_IP'];
			}
			else
			{
				if (isset($_SERVER['REMOTE_ADDR']))
				{
					$realip = $_SERVER['REMOTE_ADDR'];
				}
				else
				{
					$realip = '0.0.0.0';
				}
			}
		}
		else
		{
			if (getenv('HTTP_X_FORWARDED_FOR'))
			{
				$realip = getenv('HTTP_X_FORWARDED_FOR');
			}
			elseif (getenv('HTTP_CLIENT_IP'))
			{
				$realip = getenv('HTTP_CLIENT_IP');
			}
			else
			{
				$realip = getenv('REMOTE_ADDR');
			}
		}
	
		preg_match("/[\d\.]{7,15}/", $realip, $onlineip);
		$realip = !empty($onlineip[0]) ? $onlineip[0] : '0.0.0.0';
	
		return $realip;
	}
}