<?php

namespace SRVX\Api\Controllers;

use SRVX\Model\SelfSupportForSchoolInfo;
use SRVX\Traits\BasisFun;

class AliCallBackController extends \Phalcon\Mvc\Controller
{

    use BasisFun;

    //加密方法
    function encrypt($input, $key, $iv)
    {

        $data = @base64_encode(openssl_encrypt($input, 'AES-256-CBC', base64_decode($key), OPENSSL_RAW_DATA, $iv));
        return $data;
    }

    //解密
    function decrypt($input, $key, $iv)
    {
        return openssl_decrypt(base64_decode($input), 'AES-256-CBC', base64_decode($key), OPENSSL_RAW_DATA, $iv);
    }


    protected function RSA2($data, $pikey)
    {
        $res = "-----BEGIN RSA PRIVATE KEY-----\n" . wordwrap($pikey, 64, "\n", true) . "\n-----END RSA PRIVATE KEY-----";
        // 请注意密钥 是不是有带   -----BEGIN RSA PRIVATE KEY-----   -----END RSA PRIVATE KEY-----

        $piKey = openssl_pkey_get_private($res);

        if ($piKey) {
            $res = openssl_get_privatekey($res);
            openssl_sign($data, $sign, $res, 'SHA256');
            $sign = base64_encode($sign);
            openssl_free_key($piKey);
            return $sign;
        }
    }


    //接口服务商解析入参、包装返回值
    public function ecoCallBackAction()
    {
        $params = $this->request->get();
        $this->logger(["req" => $params, "service" => $params["service"]], 'aliEcoCommonCallBack', true);

        //获取支付宝行业云公钥
        $alipayrsaPublicKey = 'MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuWFuSpwY/2llLhy5Hxkqcc0qQFQOvemkYOI4S43L4qArX4x+DQN1RFuvfGuwOLScBKaoDYHsu9PSoTtcIj4obhhexbWHfelcsouV7Pj4YChrOkOLHAMLDQhGRXaZyXQAJdk2DoBkJ0vBDD/b1gZT8QznPopvuT4Y0rx/a2vK+5B/XV0wUuP2PnpWoPxNSwr7neFWvUdkC7yJJg4zJ1INLYy9TgHH3LKYrsEDbQzPJyMPFhD0zDb36b62q3tQYc1w8JknS6XeXMkX1Tu4zZbAxyIiv3J1FK8y7dtoRi9gLgo0uLsXWDn5AwAlzqfOERgLMWD2r6FE8tOXVbMha6IImQIDAQAB';
        //支付宝提供的密钥
        $secretKey = "HOrPS0V4BthAPfgSdbHWwy0TwPnC8TQAQZIOjc8vOzI=";
        //配置应用公私钥 中生成的私钥
        $privateKey = 'MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCSGJ9ob4kmGy6y4YeynjKJc/LSg02EXjLErPZSfVrAOy69FTRfBDbazlxpfl6YCAxDdT5ZcspB5kS2XYOY4dmqqPmF4VywmcjmZM8IxZFl1p7YC8BOlP6JrzDPwVl3hn4z3Em1byj8ANLY/AxAaW9W43FSIX+cSfdJThTlxGcbHZFM3kqu++hgFc/E+ar1nB0garqh03ESjatO4b6tuHM57ou7M+fXsoIf3gaL1IDZpeAoRh5sLCBLIbLz55tF0DcOaFsK7NUImnabJDRtrM1IN0lDZkQYAzL+JFsAq+ncRJm60Vd1jq/pXML/cFVHQQgdnjUd2u2NJTSMiCKCftmdAgMBAAECggEARzt+LduEEXJbeJiCI1MC7QX9tSqUFyAevMpgZ6P7JZM1nLfECzfwzwqjAES/Nn1mDVYTCmXvu+XcRtadnWMxUAaHcwGIwgqZa8xnLa220OKuHETOhQIcgWFL+WAakS6gRgT4Y2BJqWV1aJqsFpPR15mZ3SO8JqXhznolsknqw8sO+DBJu+QXn1HdntSGWrLU4GblPlYAs64y/MzPMUWfA4ShDRn9MZK6ypnh2GB5ezgnFxx1jRGOy96IqikI8f+M/CVdgzErLIl+qTd/IbfL8B6Gccb4ZwimL/x1H1bqYCA6xINMZLo5eDHCvBTU4AW7sItw1Q7MQ8l3wBl7hW62gQKBgQDZT1SEaeBtOJxt3vrK7o/kCWNh/4h9oENFhDIuTvLQk9tirKw0BSiZedjbEHqnqM+bgeuvxazCp9uqoYXgC/dtIooy1P8aso+ZrroC/0vZV7TQBGBjbSSkKPn7ShZM2hfYQFpmLznwpel7KJbP6AJ8atv99wjB6uvqNf6fMU7IbQKBgQCsG3mj0amsYbS5ZQZpl2v65QnlkAxv0dxcstx15kW0hXRugLOu7EGcJNZMhO4gbn8dzMOaJANZPG1VLcFpe/QyP/AW7vDt9vTWdeQkQCD5xcXEDihLLCq0pFaSkmuOHWCI+aepSHUILlJ1P/K/5biD7MTdPg6tyLqyM+rjUd/38QKBgQCNu2fsVQHDOsEMB/qakK3YlSb0q61iAjzeAjKYcXV9BHJ6ERTfeN3Z+9asSjs1TqzZSAtoQQ1EiCaFS4P9dNCTpYttS+52gy+VlJhNjCT0RHfxlGkpb+4OA4vHkbKpvTUAHjjXnMW1ZwC5CugSAchdTXTeV1im4Yms4DqJqacwoQKBgQCocPd7An8qTDIBZMOC4oT29+TYvUO+yMkAHLmx1h4QkLCkWegB4g5QkKkAGPWp3hshAj/KA0cXthFXVUG/SGZ2K6eB+nbon1N+9cDETdM4QXzN5gE/mUlupIxqRU1ouI27YYPbJSQNTrC7OkwNzfnpe/gshEj/gr5eHHvd4UrvMQKBgD2Toow7sfpV0R9rhO8aJ9njlbH15LqUK/AotK3E7zr73Uv5j/BIKS4dVC7T56L2khEUbM/y8+Rig6CdyFf3A4i4GKfbp56Sap/Haa9OP6jfep6VW7Aa1AJxPvIPgPZ2U+EuRxrwrP1EBcL5z6Cern9c9Zzs8BPUacU+Q5e8c87W';

        $response = [];
        switch ($params["service"] ?? "") {
            case "alipay.planet.ecocampus.spi.school.queryFaceGroupKey":
                $biz_content = json_decode($params["biz_content"], true);

                $this->logger(["biz_content" => $biz_content["schoolCode"]], 'aliEcoCommonCallBack', true);
                //SPI::获取学校人脸库id
                $selfSupportForSchoolInfo = SelfSupportForSchoolInfo::findFirst("school_code = '{$biz_content["schoolCode"]}'");
                $this->logger(["info" => $selfSupportForSchoolInfo], 'aliEcoCommonCallBack', true);
                if (empty($selfSupportForSchoolInfo)) {
                    $response = [
                        "code" => "10000",
                        "msg" => "Success",
                        "face_group_key" => "",
                    ];
                } else {
                    $response = [
                        "code" => "10000",
                        "msg" => "Success",
                        "face_group_key" => $selfSupportForSchoolInfo->group_key,
                    ];
                }
                break;
            default:
                $response = [
                    "code" => "40000",
                    "msg" => "Business Failed",
                    "sub_code" => "20000",
                    "sub_msg" => "未匹配到相关接口服务",
                ];
        }

        // 3、业务处理结果加签，业务返回结果需要进行排序
        ksort($response);//数组排序
        $contentToSign = json_encode($response);//数组转json
//        $responseSecretText = $this->encrypt($contentToSign, $secretKey, $iv);//加密方法，只有当前调用的业务接口需要加解密时才需要

        //用 接入准备 >  3.配置应用公私钥 中生成的私钥，对第4步的加密字符串进行加签，放到 sign 参数里。
//        $sign1 = $this->RSA2($responseSecretText, $privateKey);//加签
        $sign1 = $this->RSA2($contentToSign, $privateKey);//加签
        $result = [
            "sign" => $sign1,
            "response" => $response
        ];

        $this->logger(["resp" => $result], 'aliEcoCommonCallBack', true);

        header('Content-Type: application/json');
        exit(json_encode(
            $result
        ));
    }


}