<?php

namespace app\home\service;

use app\model\RechargeApplyModel;
use app\model\UserWithdrawalModel;
use think\facade\Log;


/**
 * 处理团队佣金业务
 */
class ClickPayService extends BaseHomeService
{

//    public $key         = "399fd368dbd84b3fbee7012f20ca0b45";
//    public $df_key      = 'UQBCGZ3IWBVWUUDXYU8ZDXZ2QOQAC2DN';
//    public $merchant    = "400029056";
    public $key = "";
    public $df_key = "";
    public $merchant = "S820240528143535000000";
    public $payable_url = "https://open.clickpay.click/gateway/pay";//代收
    public $pay_url = "https://open.clickpay.click/gateway/cash";//代付
    public $get_account = "https://open.clickpay.click/gateway/account";//查余额
    public $pu_key = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCS2D+QBLB+2bJi2r7o23GAoE37b9P6yrAykzxXvo0/284qOOn2rzX1htbzyDm0QJSqHQaOFfalZEa/SaB1n0Wv3xaumQUwwoUVvWIkM/+RJiRW0Gtch7MbKW/6GU7+xD3B4auILIQs4/bpNeN1JYOWVW90dlDONyl+qzBoSPMbqwIDAQAB';
    public $pr_key = 'MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAJLYP5AEsH7ZsmLavujbcYCgTftv0/rKsDKTPFe+jT/bzio46favNfWG1vPIObRAlKodBo4V9qVkRr9JoHWfRa/fFq6ZBTDChRW9YiQz/5EmJFbQa1yHsxspb/oZTv7EPcHhq4gshCzj9uk143Ulg5ZVb3R2UM43KX6rMGhI8xurAgMBAAECgYAZHF+qOhMQbhvCKdPxr+z16PPM5m+ieFyvGVx9SLmQzP6xW7AungGlLdy+LWQovc5uVK5VR844tDAg7+8/je/1g+n1sVBa3rtbfoFIrwXNuhf/UgygzrGuhL0gHyVLwxLb0VoLdmK5ggGhuj5FDwSkmAMFa4hLzL1tVVH/+K3T+QJBAMIq51VGbEPQ2+qny8PQVBVQk72jQs4Z2sAtOdD1tC2AoJohHXuQ8welHHmcuJ/F9/xoDaWAgf1m/Mn/cD2WhbcCQQDBm3LyAyenYcfi1lLbiOzjvd571k/gySvMHCZcdrzor1AC2vcHJ6FGw5vmd5clGW7R1K47kJqwptfMJTiVMzmtAkEAv4WaUZ75Q5tMkRWaBDgF+FBWqoPTbYBLKaxyjw8M/qUVxXJMpom/bxcKE1rnMZIQnkP00f8EOXPQfV8c02MZ2QJBAJaAAXWR8ERUZW63Dofrw8IxuX5olYV2vF4ZT9S21JjIlxjxH/Bm5R6+NjWMp2jGgXgJrTtOaIGD4OKn2Hla7a0CQBQVTCr3yhlsjcEvP8H7f2eo13dmvnHRC5pZSGWNr/vDp13QAAVvA2ZdvpWSLpm00kXYLDAudW6ox35m0Eh1dAM=';
    public $de_pu_key = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC3WjmvweygLpMt48RzxYo5vPWi41yHqxW2DjcPLzkIeKyatHGo+XpnwzyJirz0HLed9AA56lTw+SrNdPKe1TBNfrHNkd1ymw+ahwAGm0Y4LOnhGxr1gb5qg3mtU2w7H/jC5CbfN3VG9KdUCdH/TTFCa5JM9Fduo6P/fdkN2O7FtwIDAQAB';
    public $notify_url = 'https://api.abglobalfund.com/bs/clickpay_notify';
    public $notify_apply_url = 'https://api.abglobalfund.com/bs/clickpay_ApplyNotify';

//    public function __construct()
//    {
//
//    }


    /**
     * @param $orderId // 订单id - 代收 - 充值
     * @param $amount
     * @return mixed
     */
    public function create_order($orderId, $amount)
    {
        // order_no
        $post_data['merchantCode'] = $this->merchant;  //商户在平台开通的商户号 string(32)
        $post_data['method'] = 'UPI';  //付款方式 string(10)
        $post_data['orderNum'] = $orderId;  //商户系统唯一订单号 string(32)
        $post_data['payMoney'] = floor($amount);  //订单付款金额 double(15,2)
        $post_data['productDetail'] = $orderId;  //产品描述 string(32)
        $post_data['name'] = 'Neo';  //银行付款确认页面上显示的名称 string(32)
        $post_data['email'] = 'neo@gmial.com';  //客户的电子邮件地址 string(64)
        $post_data['currency'] = 'INR';  //货币 string(64)
        $post_data['notifyUrl'] = $this->notify_url;  //异步通知地址 string(100)
        $post_data['redirectUrl'] = 'https://abglobalfund.com/topUp';  //同步重定向地址 string(100)
        $post_data['phone'] = '082112345678';  //客户的手机号码 string(16)
        $post_data['expiryPeriod'] = 10;  //订单到期时间(分钟) int(5)
        $post_data['dateTime'] = date("YmdHis", time());;  //日期和时间 (yyyyMMddHHmmss) string(14)
        ksort($post_data);

        Log::info('clickPay post-:  ' . json_encode($post_data));

        $params_str = '';
        foreach ($post_data as $postVal) {
            $params_str = $params_str . $postVal;
        }
        $sign = $this->pivate_key_encrypt($params_str, $this->pr_key);
        $post_data['sign'] = $sign;
        $header = array("Content-Type:application/json");
        $res = json_decode($this->curlPost($this->payable_url, $post_data, 10, $header, 'json'), true);

        Log::info('clickPay notify-:  ' . json_encode($res));
        if (!empty($res['status'])) {
            $res['platRespMessage'] = '11';
            $res['platRespCode'] = 'error';
            return $res;
        }
        if (!empty($res['platSign'])) unset($res['platSign']);
        //        $platSign = $res['platSign'];
//        $decryptSign = $this->public_key_decrypt($platSign, $this->de_pu_key);
//        $params = $res;
//        ksort($params);
//        $params_str = '';
//        foreach ($params as $resVal) {
//            $params_str .= $resVal;
//        }
//        if ($params_str == $decryptSign && !empty($res['payData'])) {
        return $res;
//        } else {
//            $res['platRespMessage'] = '11';
//            $res['platRespCode'] = 'error';
//            return $res;
//        }
    }

    // 代收 异步回调处理
    public function clickPayNotify($data)
    {
        $platSign = $data['platSign'];
        unset($data['platSign']);

        $sign = $this->public_key_decrypt($platSign, $this->de_pu_key);
        $params = $data;
        ksort($params);
        $params_str = '';
        foreach ($params as $val) {
            $params_str .= $val;
        }
        if ($params_str == $sign) {
            // Check if payment was successful
            if ($data['code'] == '00' && $data['msg'] == 'SUCCESS') {
                $order_info = RechargeApplyModel::getOrderByNo([
                    'order_no' => $data['orderNum']
                ]);
                if ($order_info && $data['payMoney'] == $order_info['total_amount']) {
                    if ($order_info['status'] == 0) {
                        $res = (new PayService())->dealPayNotify($order_info);
                        if ($res['code'] == 200) {
                            Log::info('clickpay代收 成功111:' . json_encode($data));
                            return 'SUCCESS';
                        }
                    }
                }
                Log::info('clickpay代收 成功222:' . json_encode($data));
                return 'SUCCESS';
            } else {
                Log::info('clickpay代收 失败111:' . json_encode($data));
                return 'FAIL';
            }
        } else {
            Log::info('clickpay代收 失败222:' . json_encode($data));
            return 'FAIL';
        }
    }

    // 代付
    public function apply_pay($orderId, $amount, $bank_account, $nike_name, $ifsc, $bank_code)
    {
        $post_data['merchantCode'] = $this->merchant;  //商户在平台开通的商户号 string(32)
        $post_data['orderNum'] = $orderId;  //商户系统唯一订单号 string(32)
        $post_data['money'] = floor($amount);  //转账金额	 double(15,2)
        $post_data['feeType'] = '0';  //费用类型(0-从转账金额中扣除,1-从商户余额中扣除) string(10)
        $post_data['dateTime'] = date("YmdHis", time());;  //日期和时间 (yyyyMMddHHmmss) string(14)
        $post_data['name'] = '	MUHAMAD JUMAEDI';  //持卡人姓名	 string(32)
        $post_data['number'] = $bank_account;  //帐号或 UPI 号码	 string(32)
        $post_data['bankLinked'] = $ifsc;  //联合服务中心	 string(32)
        $post_data['bankCode'] = 'IFSC';  //联合服务中心	 string(32)
        $post_data['bankName'] = $nike_name;  //银行名	 string(32)
        $post_data['accountEmail'] = 'test@test.com';  //帐户的电子邮件	 string(64)
        $post_data['accountMobile'] = '082112345678';  //帐号手机号码 string(16)
        $post_data['description'] = 'INR';  //转让说明	 string(100)
        $post_data['currency'] = 'INR';  //货币 string(64)
        $post_data['notifyUrl'] = $this->notify_apply_url;  //异步通知地址 string(100)
        ksort($post_data);

        Log::info('clickPay-daifu- post-:  ' . json_encode($post_data));
        $params_str = '';
        foreach ($post_data as $postVal) {
            $params_str = $params_str . $postVal;
        }
        $sign = $this->pivate_key_encrypt($params_str, $this->pr_key);
        $post_data['sign'] = $sign;
        $header = array("Content-Type:application/json");
        $res = json_decode($this->curlPost($this->pay_url, $post_data, 10, $header, 'json'), true);
        Log::info('clickPay-daifu notify-:  ' . json_encode($res));

        if (!empty($res['platSign'])) unset($res['platSign']);

        if (strtoupper($res['platRespCode']) == 'SUCCESS') {
            return [
                'code' => 200,
                'msg' => 'ok',
                'order_idx' => $res['orderNum'],
                'content' => $res
            ];
        } else {
            return [
                'code' => 300,
                'msg' => $res['platRespMessage'],
                'order_idx' => '',
                'content' => $res
            ];
        }


    }

    public function clickPayApplyNotify($data)
    {
        $platSign = $data['platSign'];
        unset($data['platSign']);

        $sign = $this->public_key_decrypt($platSign, $this->de_pu_key);
        $params = $data;
        ksort($params);
        $params_str = '';
        foreach ($params as $val) {
            $params_str .= $val;
        }
        if ($params_str == $sign) {
            // Check if payment was successful
            if ($data['code'] == '00' && $data['msg'] == 'SUCCESS') {
                $order_info = UserWithdrawalModel::getUserDrawalInfo([
                    'order_no' => $data['orderNum']
                ]);
                if ($order_info && $order_info['status'] == 3) {
                    UserWithdrawalModel::where([
                        'id' => $order_info['id']
                    ])->update([
                        'status' => 4,
                        'deal_time' => date('Y-m-d H:i:s')
                    ]);
                    Log::info('clickpay代付 成功111:' . json_encode($data));
                    return 'SUCCESS';
                }
                Log::info('clickpay代付 成功222:' . json_encode($data));
                return 'SUCCESS';
            } else {
                Log::info('clickpay代付 失败111:' . json_encode($data));
                return 'FAIL';
            }
        } else {
            Log::info('clickpay代付 失败222:' . json_encode($data));
            return 'FAIL';
        }
    }

    public function getBalance()
    {
        $post_data['merchantCode'] = $this->merchant;
        $post_data['dateTime'] = date("YmdHis", time());;  //日期和时间 (yyyyMMddHHmmss) string(14)
        ksort($post_data);
        Log::info('clickPay-getBalance-post-:  ' . json_encode($post_data));

        $params_str = '';
        foreach ($post_data as  $val) {
            $params_str .= $val;
        }

        $sign = $this->pivate_key_encrypt($params_str, $this->pr_key);
        $post_data['sign'] = $sign;
        $header = array("Content-Type:application/json");
        $res = json_decode($this->curlPost($this->get_account, $post_data, 10, $header, 'json'), true);
        Log::info('clickPay-getBalance-res-:  ' . json_encode($res));
        if (strtoupper($res['platRespCode']) == 'SUCCESS') {
            return [
                'amount' => $res['balance']
            ];
        } else {
            return [
                'amount' => 0
            ];
        }
    }

    private function curlPost($url, $post_data = array(), $timeout = 5, $header = "", $data_type = "")
    {
        $header = empty($header) ? '' : $header;
        //支持json数据数据提交
        if ($data_type == 'json') {
            $post_string = json_encode($post_data);
        } elseif ($data_type == 'array') {
            $post_string = $post_data;
        } elseif (is_array($post_data)) {
            $post_string = http_build_query($post_data, '', '&');
        }

        $ch = curl_init();    // 启动一个CURL会话
        curl_setopt($ch, CURLOPT_URL, $url);     // 要访问的地址
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);  // 对认证证书来源的检查   // https请求 不验证证书和hosts
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);  // 从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']); // 模拟用户使用的浏览器
        //curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1); // 使用自动跳转
        //curl_setopt($curl, CURLOPT_AUTOREFERER, 1); // 自动设置Referer
        curl_setopt($ch, CURLOPT_POST, true); // 发送一个常规的Post请求
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_string);     // Post提交的数据包
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);     // 设置超时限制防止死循环
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        //curl_setopt($curl, CURLOPT_HEADER, 0); // 显示返回的Header区域内容
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);     // 获取的信息以文件流的形式返回
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header); //模拟的header头
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    private function pivate_key_encrypt($data, $key)
    {
        $pivate_key = '-----BEGIN PRIVATE KEY-----' . "\n" . $key . "\n" . '-----END PRIVATE KEY-----';
        $pi_key = openssl_pkey_get_private($pivate_key);
        $crypto = '';
        foreach (str_split($data, 117) as $chunk) {
            openssl_private_encrypt($chunk, $encryptData, $pi_key);
            $crypto .= $encryptData;
        }

        return base64_encode($crypto);
    }

    private function public_key_decrypt($data, $key)
    {
        $public_key = '-----BEGIN PUBLIC KEY-----' . "\n" . $key . "\n" . '-----END PUBLIC KEY-----';
        $data = base64_decode($data);
        $pu_key = openssl_pkey_get_public($public_key);
        $crypto = '';
        foreach (str_split($data, 128) as $chunk) {
            openssl_public_decrypt($chunk, $decryptData, $pu_key);
            $crypto .= $decryptData;
        }

        return $crypto;
    }


}