<?php
/*
 本代码由 焕岱科技 创建
 技术支持 WX：15285007200
 严禁反编译、逆向等任何形式的侵权行为，违者将追究法律责任
*/

namespace app\common\model\bbfxshop;

use think\Db;


class Huifubafang
{
    // public $host = 'https://payapitest.aqchongfang.com';//测试地址
	public $host = 'https://payapi.huifubafang.com';//正式地址
    public $comKey = '';// 接入方唯一标识
    public $comSecret = '';
    public $merchant_id = '';// 微信商户号
    public $appid = '';// 微信应用appid
    public $status = 0;// 微信应用appid

	public function __construct(){
		$huifubafang = Db::name("platform")->where(['id'=>UNIACID])->field("huifubafang")->value("huifubafang");
		$huifubafang = iunserializer($huifubafang);
		if(empty($huifubafang)){
			$huifubafang = ['status'=>0,'comKey'=>'','comSecret'=>'','merchant_id'=>'','appid'=>''];
		}
		$this->comKey = $huifubafang['comKey'];
		$this->comSecret = $huifubafang['comSecret'];
		$this->merchant_id = $huifubafang['merchant_id'];
		$this->appid = $huifubafang['appid'];
		$this->status = $huifubafang['status'];
	}

	public function checkParams(){
		if($this->status != 1){
			return __json(-2,'未开启功能');
		}
		if(empty($this->comKey)){
			return __json(0,'配置参数comKey不完整');
		}
		if(empty($this->comSecret)){
			return __json(0,'配置参数comSecret不完整');
		}
		if(empty($this->merchant_id)){
			return __json(0,'配置参数微信商户号不完整');
		}
		if(empty($this->appid)){
			return __json(0,'配置参数微信应用appid不完整');
		}
		return __json(1,'配置参数完整');
	}

	/**
	 * 微信批量转账（可单笔）
	 */
	public function wxorderBatchPay($params){
		$result = $this->checkParams();
		if($result['code'] != 1){
			return $result;
		}
		$result = $this->getOauthConfig($params['user_id']);
		if($result['code'] != 1){
			return $result;
		}
		if($result['data']['is_auth'] != 1){
			return __json(0,'用户未授权');
		}

        $reqParams = [
            'batch_no' => $params['out_batch_no'],
            'order_time' => date('Y-m-d H:i:s'),
            'merchant_id' => $this->merchant_id,
            'appid' => $this->appid,
            'batch_name' => "提现".$params['out_batch_no'],
            'batch_remark' => "提现",
            'total_amount' => round($params['money'] * 100),
            'total_num' => 1,
            'details' => [
                [
                    'order_id' => $params['trade_no'],
                    'openid' => $params['user_id'],
                    'transfer_amount' => round($params['money'] * 100),
                    'transfer_remark' => '提现',
                    // 'user_name' => '',
                ],
            ],
        ];

		if ($params['money'] >= 2000) {
            if(empty($params['user_name'])){
                return __json(0, '提现金额 >= 2000元时，收款用户真实姓名必填');
            }
            
            $data['transfer_detail_list'][0]['user_name'] = $params['user_name'];
        }

        $str = json_encode($reqParams);

        $data = [
            "comKey"=>$this->comKey,
            "timestamp"=>time(),
            'data'=>$this->app_encrypt($str,$this->comKey,$this->comSecret),
        ];
        try {
            $res = $this->http($this->host.'/api/wx/wxorderBatchPay','POST',$data);
			addFileLog("hfbf111",$res);
			$res = json_decode($res,true);
			if($res['code'] == 200){
				$result = __json(1,'提交成功，请等待打款！',$res['data']);
			}
			else{
				$result = __json(0,$res['message']);
			}
        } catch (\Exception $e) {
            $result = __json(0,$e->getMessage());
        }  
        
        return $result;  	  
    }

	// 查询状态
	public function wxorderBatchQuery($params){
		$result = $this->checkParams();
		if($result['code'] != 1){
			return $result;
		}
		$reqParams = [
            'batch_no' => $params['out_batch_no'],
            'month' => $params['month'],
            'order_id' => $params['order_id'],
        ];
        $str = json_encode($reqParams);
        $data = [
            "comKey"=>$this->comKey,
            "timestamp"=>time(),
            'data'=>$this->app_encrypt($str,$this->comKey,$this->comSecret),
        ];
        try {
            $res = $this->http($this->host.'/api/wx/wxBatchDetailQuery','POST',$data);
			addFileLog("hfbf333",$res);
			$res = json_decode($res,true);
			if($res['code'] == 200){
				$result = __json(1,'操作成功',$res['data']);
			}
			else{
				$result = __json(0,$res['message']);
			}
        } catch (\Exception $e) {
            $result = __json(0,$e->getMessage());
        }  
        
        return $result;  	  
    }

	// 获取授权
    public function getOauthConfig($user_id){
		$result = $this->checkParams();
		if($result['code'] != 1){
			return $result;
		}
        $reqParams = [
            'merchant_id' => $this->merchant_id,
            'appid' => $this->appid,
            'account' => (string)$user_id
        ];
        $str = json_encode($reqParams);
        $data = [
            "comKey"=>$this->comKey,
            "timestamp"=>time(),
            'data'=>$this->app_encrypt($str,$this->comKey,$this->comSecret),
        ];
        try {
            $res = $this->http($this->host.'/api/getOauthConfig','POST',$data);
			addFileLog("hfbf222",$res);
			$res = json_decode($res,true);
			if($res['code'] == 200){
				$result = __json(1,'操作成功',$res['data']);
			}
			else{
				$result = __json(0,$res['message']);
			}
        } catch (\Exception $e) {
            $result = __json(0,$e->getMessage());
        }  
        
        return $result;  	  
    }

    /**
	 * 加密
	 * @param $id
	 * @param $key
	 * @return string
	 * key 和 iv的长度 必须满足16的整数倍
	 */
	public function app_encrypt($str,$comKey,$comSecret) {
	    $data = openssl_encrypt($str, 'AES-256-CBC', $comSecret, true, $comKey);
	    $encrypt       = base64_encode($data);
	    return $encrypt;
	}


	/**
	 * 解密
	 * @param $encrypt
	 * @param $key
	 * @return int|string
	 */
	public function app_decrypt($encrypt, $comKey,$comSecret) {
	    if (!is_string($encrypt)) return 0;
	    $encrypt = base64_decode($encrypt);
	    $data      = openssl_decrypt($encrypt, 'AES-256-CBC', $comSecret, true, $comKey);
	    if($data) {
	        return $data;
	    } else {
	        return 0;
	    }
	}



	/**
	 *回调签名加密方法
	 * @param $req
	 * @param $comSecret
	 * @return string
	 */
	public function getSign($req,$appsecret)
	{
	    ksort($req['params'],SORT_NATURAL);
	    $values = $this->getValues($req['params']);
	    return strtoupper(md5($req['timeStamp'].$values.$appsecret));
	}

	/**
	 *http请求
	 * @param $url
	 * @param $method
	 * @param $postFields
	 * @param $headers
	 * @return string
	 */
	public function http($url, $method = 'GET', $postFields = null, $headers = null)
    {
        $method = strtoupper($method);
        if (!in_array($method, ['GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'HEAD', 'OPTIONS'])) {
            return false;
        }
        $opts = [
            CURLOPT_CUSTOMREQUEST => $method,
            CURLOPT_URL => $url,
            CURLOPT_FAILONERROR => false,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_TIMEOUT => 30,
            CURLOPT_CONNECTTIMEOUT => 30,
        ];
        if ($method == 'POST' && !is_null($postFields)) {
            $opts[CURLOPT_POSTFIELDS] = http_build_query($postFields);
        }
        if (strlen($url) > 5 && strtolower(substr($url, 0, 5)) == 'https') {
            $opts[CURLOPT_SSL_VERIFYPEER] = false;
            $opts[CURLOPT_SSL_VERIFYHOST] = false;
        }
        if (!empty($headers) && is_array($headers)) {
            $httpHeaders = [];
            foreach ($headers as $key => $value) {
                array_push($httpHeaders, $key . ':' . $value);
            }
            $opts[CURLOPT_HTTPHEADER] = $httpHeaders;
        }
        $ch = curl_init();
        curl_setopt_array($ch, $opts);
        $data = curl_exec($ch);
        $err = curl_errno($ch);
        curl_close($ch);
        if ($err > 0) {
            return false;
        } else {
            return $data;
        }
    }



	/**
	 *获取数组字段值
	 *
	 */
	public function getValues($arr,$str='') {
	    foreach ($arr as $key=>$val) {
	        if (is_array($val)) {
	            $this->getValues($val,$str);
	        } else {
	            if (is_bool($val)) {
	                $val = $val ? 'True':'False';
	            }
	            $val = str_replace(' ', '', (string)$val);
	            $str.=$val;
	        }
	    }
	    return $str;
	}
}