<?php

namespace web\admin\demo;

class setpage {
    public static function json_init() {
        global $db;
        $rsuser = verifyfast();
        $post = new \ciy\post();
        $csql = new \ciy\sql('hf_providerbase');
        $csql->where('id', $rsuser['s_a']);
        $ret['data'] = $db->getone($csql);
        $csql = new \ciy\sql('hf_providerkey');
        $csql->where('id', $rsuser['s_a']);
        $csql->column('ali_appid');
        $ret['key'] = $db->getone($csql);
        return succjson($ret);
    }
    public static function json_editserv() {
        global $db;
        $rsuser = verifyfast();
        //if (nopower($db, $rsuser['id'], 'p u'))
        //    return errjson('您未被授权操作');
        $post = new \ciy\post();
        $serviceimg = $post->get('serviceimg');
        try {
            $db->begin();
            $updata = array();
            $updata['serviceimg'] = $serviceimg;
            $csql = new \ciy\sql('hf_providerbase');
            $csql->where('id', $rsuser['s_a']);
            if ($db->update($csql, $updata) === false)
                throw new \Exception('更新失败:' . $db->error);
            $db->commit();
        } catch (\Exception $ex) {
            $db->rollback();
            savelogfile('err_db', $ex->getMessage());
            return errjson($ex->getMessage());
        }
        return succjson();
    }
    public static function json_editrecv() {
        global $db;
        $rsuser = verifyfast();
        //if (nopower($db, $rsuser['id'], 'p u'))
        //    return errjson('您未被授权操作');
        $post = new \ciy\post();
        $recvtype = $post->getint('recvtype');
        $recvaccount = $post->get('recvaccount');
        $recvname = $post->get('recvname');
        if ($recvtype == 0)
            return errjson('请选择账号类型');
        if (empty($recvaccount))
            return errjson('请输入收款账号');
        if (empty($recvname))
            return errjson('请输入收款人姓名');
        try {
            $db->begin();
            $updata = array();
            $updata['recvtype'] = $recvtype;
            $updata['recvaccount'] = $recvaccount;
            $updata['recvname'] = $recvname;
            $csql = new \ciy\sql('hf_providerbase');
            $csql->where('id', $rsuser['s_a']);
            if ($db->update($csql, $updata) === false)
                throw new \Exception('更新失败:' . $db->error);
            $db->commit();
        } catch (\Exception $ex) {
            $db->rollback();
            savelogfile('err_db', $ex->getMessage());
            return errjson($ex->getMessage());
        }
        return succjson();
    }
    static function hex2dec($hex) {
        $dec = 0;
        $len = strlen($hex);
        for ($i = 1; $i <= $len; $i++) {
            $dec = bcadd($dec, bcmul(strval(hexdec($hex[$i - 1])), bcpow('16', strval($len - $i))));
        }
        return $dec;
    }
    static function array2string($array) {
        $string = [];
        if ($array && is_array($array)) {
            foreach ($array as $key => $value) {
                $string[] = $key . '=' . $value;
            }
        }
        return implode(',', $string);
    }
    public static function json_editapp() {
        global $db;
        $rsuser = verifyfast();
        //if (nopower($db, $rsuser['id'], 'p u'))
        //    return errjson('您未被授权操作');
        $post = new \ciy\post();
        $ali_appid = $post->get('ali_appid');
        $pubkey = $post->get('pubkey'); //appCertPublicKey_2021005173683965.crt
        $rootkey = $post->get('rootkey'); //alipayRootCert.crt
        $apppub = $post->get('apppub'); //alipayCertPublicKey_RSA2.crt
        $apppri = $post->get('apppri'); //应用私钥RSA2048-敏感数据，请妥善保管
        if (empty($ali_appid))
            return errjson('请输入APPID');
        if (empty($pubkey))
            return errjson('请输入公钥');
        if (empty($rootkey))
            return errjson('请输入root证书');
        if (empty($apppub))
            return errjson('请输入APP公钥');
        if (empty($apppri))
            return errjson('请输入APP私钥');
        $ssl = openssl_x509_parse($pubkey);
        if ($ssl === false)
            return errjson('公钥格式错误');
        $ali_app_cert_sn = '';
        if (is_array($ssl['issuer']))
            $ali_app_cert_sn = md5(self::array2string(array_reverse($ssl['issuer'])) . $ssl['serialNumber']);
        if (empty($ali_app_cert_sn))
            return errjson('app证书格式错误');

        $array = explode("-----END CERTIFICATE-----", $rootkey);
        $ali_root_cert_sn = null;
        for ($i = 0; $i < count($array) - 1; $i++) {
            $ssl[$i] = openssl_x509_parse($array[$i] . "-----END CERTIFICATE-----");
            if (strpos($ssl[$i]['serialNumber'], '0x') === 0) {
                $ssl[$i]['serialNumber'] = self::hex2dec($ssl[$i]['serialNumberHex']);
            }
            if ($ssl[$i]['signatureTypeLN'] == "sha1WithRSAEncryption" || $ssl[$i]['signatureTypeLN'] == "sha256WithRSAEncryption") {
                if ($ali_root_cert_sn == null) {
                    $ali_root_cert_sn = md5(self::array2string(array_reverse($ssl[$i]['issuer'])) . $ssl[$i]['serialNumber']);
                } else {
                    $ali_root_cert_sn = $ali_root_cert_sn . "_" . md5(self::array2string(array_reverse($ssl[$i]['issuer'])) . $ssl[$i]['serialNumber']);
                }
            }
        }
        if (empty($ali_root_cert_sn))
            return errjson('root证书格式错误');
        if (strpos($apppri, '-----BEGIN RSA PRIVATE KEY-----') === false) {
            $apppri = "-----BEGIN RSA PRIVATE KEY-----\n" . chunk_split($apppri, 64, "\n") . "-----END RSA PRIVATE KEY-----";
        }
        try {
            $db->begin();
            $updata = array();
            $updata['ali_appid'] = $ali_appid;
            $updata['ali_app_cert_sn'] = $ali_app_cert_sn;
            $updata['ali_root_cert_sn'] = $ali_root_cert_sn;
            $updata['ali_publickey'] = $apppub;
            $updata['ali_privatekey'] = $apppri;
            $csql = new \ciy\sql('hf_providerkey');
            $csql->where('id', $rsuser['s_a']);
            if ($db->update($csql, $updata) === false)
                throw new \Exception('更新失败:' . $db->error);
            $db->commit();
        } catch (\Exception $ex) {
            $db->rollback();
            savelogfile('err_db', $ex->getMessage());
            return errjson($ex->getMessage());
        }
        return succjson();
    }
    public static function json_testapp() {
        global $db;
        $rsuser = verifyfast();
        $csql = new \ciy\sql('hf_providerkey');
        $csql->where('id', $rsuser['s_a']);
        $keyrow = $db->getone($csql);
        $model = array();
        $model['personal_product_code'] = 'FUND_SAFT_SIGN_WITHHOLDING_P';
        $model['product_code'] = 'FUND_SAFT_SIGN_WITHHOLDING';
        $model['external_agreement_no'] = 'AX' . rand(10000, 99999); //bizno
        $model['sign_scene'] = 'INDUSTRY|SATF_ACC';
        $model['third_party_type'] = 'PARTNER';
        $accessParams = array();
        $accessParams['channel'] = 'QRCODE'; // 1. ALIPAYAPP （钱包h5页面签约） 2. QRCODE(扫码签约) 3. QRCODEORSMS(扫码签约或者短信签约)
        $model['access_params'] = $accessParams;
        return succjson();
    }
    public static function json_prov_stop() {
        global $db;
        $rsuser = verifyfast();
        try {
            $db->begin();
            $updata = array();
            $updata['providerstatus'] = 20;
            $csql = new \ciy\sql('hf_providerbase');
            $csql->where('id', $rsuser['s_a']);
            if ($db->update($csql, $updata) === false)
                throw new \Exception('更新失败:' . $db->error);
            $db->commit();
        } catch (\Exception $ex) {
            $db->rollback();
            savelogfile('err_db', $ex->getMessage());
            return errjson($ex->getMessage());
        }
        return succjson();
    }
    public static function json_prov_start() {
        global $db;
        $rsuser = verifyfast();
        $csql = new \ciy\sql('hf_providerbase');
        $csql->where('id', $rsuser['s_a']);
        $providerrow = $db->getone($csql);
        if ($providerrow['recvtype'] == 0 || empty($providerrow['recvaccount']) || empty($providerrow['recvname']))
            return errjson('请配置收款账号');
        if ($providerrow['depositmoney'] < 1)
            return errjson('您的保证金不足');
        $csql = new \ciy\sql('hf_providerkey');
        $csql->where('id', $rsuser['s_a']);
        $keyrow = $db->getone($csql);
        if (!is_array($keyrow)) {
            $updata = array();
            $updata['ali_appid'] = '';
            $updata['ali_app_cert_sn'] = '';
            $updata['ali_root_cert_sn'] = '';
            $updata['ali_publickey'] = '';
            $updata['ali_privatekey'] = '';
            $csql = new \ciy\sql('hf_providerkey');
            $csql->where('id', $rsuser['s_a']);
            if ($db->insert($csql, $updata) === false)
                return errjson('添加key失败:' . $db->error);
            $keyrow = array();
        }
        if (empty($keyrow['ali_appid']))
            return errjson('请配置APPID');
        if (empty($keyrow['ali_app_cert_sn']))
            return errjson('请配置APP证书SN');
        if (empty($keyrow['ali_root_cert_sn']))
            return errjson('请配置根证书SN');
        if (empty($keyrow['ali_publickey']))
            return errjson('请配置APP公钥');
        if (empty($keyrow['ali_privatekey']))
            return errjson('请配置APP私钥');
        try {
            $db->begin();
            $updata = array();
            $updata['providerstatus'] = 10;
            $csql = new \ciy\sql('hf_providerbase');
            $csql->where('id', $rsuser['s_a']);
            if ($db->update($csql, $updata) === false)
                throw new \Exception('更新失败:' . $db->error);
            $db->commit();
        } catch (\Exception $ex) {
            $db->rollback();
            savelogfile('err_db', $ex->getMessage());
            return errjson($ex->getMessage());
        }
        return succjson();
    }
}
