<?php

namespace SRVX\Service\Pay;

use SRVX\Service\BaseService;
use AopClient;


class AlipayK12Service extends BaseService
{

    static private $config = [];
    static private $aopClient;

    public $gatewayUrl = 'https://openapi.alipay.com/gateway.do';
    public $apiVersion = '1.0';
    public $signType = 'RSA2';
    public $postCharset = 'UTF-8';
    public $format = 'json';

    public function __construct($config = [])
    {
        empty($config) && $this->getConfig();
        $this->aopClient($config);
    }


    private function aopClient($config)
    {
        if (!self::$aopClient instanceof AopClient) {
            self::$aopClient = new AopClient();
            if (empty($config)) :
                self::$aopClient->appId = self::$config['ali_app_id'];
                //支付宝私钥值
                self::$aopClient->rsaPrivateKey = self::$config['ali_private_key'];
                //支付宝公钥值
                self::$aopClient->alipayrsaPublicKey = self::$config['ali_public_key'];
            else :
                self::$aopClient->appId = $config['ali_app_id'];
                //支付宝私钥值
                self::$aopClient->rsaPrivateKey = $config['ali_private_key'];
                //支付宝公钥值
                self::$aopClient->alipayrsaPublicKey = $config['ali_public_key'];
            endif;
        }

        self::$aopClient->gatewayUrl = $this->gatewayUrl;
        self::$aopClient->apiVersion = $this->apiVersion;
        self::$aopClient->signType = $this->signType;
        self::$aopClient->postCharset = $this->postCharset;
        self::$aopClient->format = $this->format;
    }


    private function getConfig()
    {
        if (empty(self::$config)) {
            self::$config = [
                "ali_app_id" => "2021004101651996",
                "ali_private_key" => "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCSGJ9ob4kmGy6y4YeynjKJc/LSg02EXjLErPZSfVrAOy69FTRfBDbazlxpfl6YCAxDdT5ZcspB5kS2XYOY4dmqqPmF4VywmcjmZM8IxZFl1p7YC8BOlP6JrzDPwVl3hn4z3Em1byj8ANLY/AxAaW9W43FSIX+cSfdJThTlxGcbHZFM3kqu++hgFc/E+ar1nB0garqh03ESjatO4b6tuHM57ou7M+fXsoIf3gaL1IDZpeAoRh5sLCBLIbLz55tF0DcOaFsK7NUImnabJDRtrM1IN0lDZkQYAzL+JFsAq+ncRJm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e/gshEj/gr5eHHvd4UrvMQKBgD2Toow7sfpV0R9rhO8aJ9njlbH15LqUK/AotK3E7zr73Uv5j/BIKS4dVC7T56L2khEUbM/y8+Rig6CdyFf3A4i4GKfbp56Sap/Haa9OP6jfep6VW7Aa1AJxPvIPgPZ2U+EuRxrwrP1EBcL5z6Cern9c9Zzs8BPUacU+Q5e8c87W",
                "ali_public_key" => "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAzEC7+3O/Ej/gkXug6EgcCM3LjWzz11RR6ESo0KshGg3ODgM8DfdKDHD5b1T6VbcRGFobXQBqVtW008ocUnSOZzE67a73l6mKT3FbmhRsbrgwcUuOHEJUZaLFxPibJgFl7fkOjBcIiz+Wc+9VDTt8O4YxIZhAL6L6ppXcrVrCkOaiIiuHGyp7FjQ+5s3Lk3NLSO3TfXw1WEX2F+IHnw32ZN/FlC8rF8HVlgM0w/PZJ9RuadoLqn5H6z/iqrurbtxscnx0Qbdt8CBzREabJnWxHjxO936AXu9njIPvsXkTfaJJIXxRGGb0b8peSiCljwi8UEODe8mjl2c/LzLel6RuLQIDAQAB"
            ];
        }
    }

    /**
     * alipay.commerce.educate.scene.token.create(教育场景token生成处理器)
     * @param $sub_code string
     * 教育场景子业务码: SCHOOL_PAYMENT_REMOTE_OPEN_ACCOUNT：校园一脸通行集采邀请（生成的token用于集采邀请发送采集阶段）；
     * SCHOOL_FACE_PASS_QUERY：校园一脸通行查询（生成的token用于查询用户的一脸通行开通状态）；
     * SCHOOL_FACE_PASS_NAVIGATE：校园一脸通行跳转（生成的token用于个采开通阶段的用户信息填充）
     * @param $cert_type string 证件类型。{1:居民身份证；A:护照}
     * @param $cert_no string 证件号码
     * @param $school_std_code string 学校外标
     * @param $student_name  string 学生/教职工/访客姓名
     * @param $parent_phone string 家长手机号码
     * @param $out_user_id  string 服务商内部用户唯一ID，用于与支付宝用户 ID 进行关联。
     * @param $operator_user_id string 采集人员的支付宝会员标识。（当sub_code为SCHOOL_PAYMENT_REMOTE_OPEN_ACCOUNT时，当前参数必选）
     * @return array
     */
    public function alipayCommerceEducateSceneTokenCreateRequest($sub_code, $cert_type, $cert_no, $school_std_code, $student_name, $parent_phone, $out_user_id, $operator_user_id = ""): array
    {
        try {
            $request = new \AlipayCommerceEducateSceneTokenCreateRequest();
            $params = [
                "sub_code" => $sub_code,
                "cert_type" => $cert_type,
                "cert_no" => $cert_no,
                "school_std_code" => $school_std_code,
                "student_name" => $student_name,
                "parent_phone" => $parent_phone,
                "out_user_id" => $out_user_id,
            ];

            if (empty($operator_user_id)) {
                $params["operator_user_id"] = $operator_user_id;
            }
            $request->setBizContent(json_encode($params));
            $response = self::$aopClient->execute($request);
            $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
            $responseData = json_decode(json_encode($response->$responseNode), true);
//            if ($responseData['code'] == 10000) {
            return $this->returnRes(true, $responseData['msg'], $responseData);
//            } else {
//                return $this->returnRes(false, ($responseData['sub_msg'] ?? $responseData['msg']), $responseData);
//            }
        } catch (\Exception $exception) {
            return $this->returnRes(false, $exception->getMessage());
        }
    }


    /**
     * alipay.commerce.educate.scene.token.query(查询刷脸用户开通详细信息)
     * @param $user_token string 用于查询用户详情的凭证
     * @return array
     */
    public function alipayCommerceEducateSceneTokenQueryRequest($user_token): array
    {
        try {
            $request = new \AlipayCommerceEducateSceneTokenQueryRequest();
            $params = [
                "user_token" => $user_token,
            ];

            $request->setBizContent(json_encode($params));
            $response = self::$aopClient->execute($request, null);
            $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
            $responseData = json_decode(json_encode($response->$responseNode), true);
//            if ($responseData['code'] == 10000) {
            return $this->returnRes(true, $responseData['msg'], $responseData);
//            } else {
//                return $this->returnRes(false, ($responseData['sub_msg'] ?? $responseData['msg']), $responseData);
//            }
        } catch (\Exception $exception) {
            return $this->returnRes(false, $exception->getMessage());
        }
    }


    /**
     * alipay.commerce.educate.facepay.apply(人脸开通支付申请)
     * @param $face_uid  string 刷脸用户id
     * @param $face_open_id  string 刷脸用户openId
     * @param $school_stdcode string 学校外标
     * @param $scene string 接入场景，可选项(K12：K12场景 / COLLEGE：高校场景)
     * @param $ext_info array 扩展信息, JSON格式，可以通过传参给不同的用户设置不同的支付方式
     * 不使用指定银行：{"useBankChannel":"NO"}；
     * 指定银行：{"useBankChannel":"YES","useBankMode":"BANK"}；
     * 指定银行卡（需同时传入银行卡号）：{"useBankChannel":"YES","useBankMode":"BANK_CARD","cardNo":"620xxxxxxx"}
     * 若不传此参数，默认指定银行
     * @return array
     */
    public function alipayCommerceEducateFacepayApplyRequest($face_uid, $face_open_id, $school_stdcode, $scene = "K12", $ext_info = ["useBankChannel" => "NO", "useBankMode" => "BANK"]): array
    {
        try {
            $request = new \AlipayCommerceEducateFacepayApplyRequest();
            $params = [
                "face_uid" => $face_uid,
                "school_stdcode" => $school_stdcode,
                "scene" => $scene,
                "ext_info" => json_encode($ext_info, JSON_UNESCAPED_UNICODE),
            ];
            if (!empty($face_open_id)) {
                $params["face_open_id"] = $face_open_id;
            }
            $request->setBizContent(json_encode($params));
            $response = self::$aopClient->execute($request, null);
            $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
            $responseData = json_decode(json_encode($response->$responseNode), true);
//            dd($responseData);
//            if ($responseData['code'] == 10000) {
            return $this->returnRes(true, $responseData['msg'], $responseData);
//            } else {
//                return $this->returnRes(false, ($responseData['sub_msg'] ?? $responseData['msg']), $responseData);
//            }
        } catch (\Exception $exception) {
            return $this->returnRes(false, $exception->getMessage());
        }
    }

    /**
     * alipay.commerce.educate.facepay.apply(人脸开通支付申请)
     * @param $school_stdcode string 学校外标
     * @return array
     */
    public function alipayCommerceEducateFaceFeatureGroupKeyQuery($school_stdcode): array
    {
        try {
            $request = new \AlipayCommerceEducateFacefeatureGroupkeyQueryRequest();
            $params = [
                "school_stdcode" => $school_stdcode,
                "biz_code" => "SCHOOL_PAYMENT",
            ];
            $request->setBizContent(json_encode($params));
            $response = self::$aopClient->execute($request, null);
            $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
            $responseData = json_decode(json_encode($response->$responseNode), true);
//            dd($responseData);
            if ($responseData['code'] == 10000) {
                return $this->returnRes(true, $responseData['msg'], $responseData);
            } else {
                return $this->returnRes(false, ($responseData['sub_msg'] ?? $responseData['msg']), $responseData);
            }
        } catch (\Exception $exception) {
            return $this->returnRes(false, $exception->getMessage());
        }
    }

}