<?php namespace Pay\Yspay;
use Dever;
use Dever\Http\Curl;
# 银联商务商户资金自主管理系统
class Multi
{
	static $host = 'https://im.chinaums.com/channel/Business/UnifyMulti/';

    /*
    public function act($config, $merchant, $info, $auto = 1)
    {
        $result = $this->huafu($config, $merchant, $info);
        if ($result == 1) {
            $this->fenzhang($config, $merchant, $info);
        }
        
        return $result;
    }*/

	# 划付
    public function huafu($config, $merchant, $info, $auto = 1)
    {
    	$this->config = $config;

    	$mid = $merchant['mid'];
    	$cash = $info['hf_cash'];
    	$order_num = $this->getOrderNum($info['order_num']);

    	//整理内容信息
        $content = [
            'merNo' => $merchant['merno'],
            //'merOrderNo' => $order_num,
            'payAmt' => $cash,
            'ps' => $merchant['name'] . '划付',
        ];
        Dever::log($content, 'yspay_huafu');
        $result = $this->curl('202002', $content);
        if ($result == 'ok') {
        	$data['status'] = 1;
        } else {
        	$data['status'] = 3;
        	$data['error'] = $result; 
        }

        $data['merchant_id'] = $merchant['id'];
        $data['mid'] = $mid;
        $data['order_num'] = $order_num;
        $data['type'] = 1;
        $data['cash'] = $cash;
        $data['tdate'] = time();
        $data['desc'] = $content['ps'];
        $data['auto'] = $auto;
        Dever::db('pay/yspay_cash_log')->insert($data);

        return $data['status'];
    }

    # 分账
    public function fenzhang($config, $merchant, $info, $auto = 1)
    {
    	$this->config = $config;

    	$mid = $this->config['cash_mid'];
    	$cash = $info['fz_cash'] + $info['pt_cash'];
    	if (!$cash || $cash <= 0) {
    		return false;
    	}
    	$order_num = $this->getOrderNum($info['order_num']);

    	//整理内容信息
        $content = [
            'merNo' => $this->config['cash_merno'],
            //'merOrderNo' => $order_num,
            'payAmt' => $cash,
            'cardNo' => hash("sha256", $this->config['cash_card']),
            'ps' => $merchant['name'] . '分账',
        ];
        Dever::log($content, 'yspay_fenzhang');
        $result = $this->curl('202004', $content);
        if ($result == 'ok') {
        	$data['status'] = 1;
        } else {
        	$data['status'] = 3;
        	$data['error'] = $result; 
        }

        $data['merchant_id'] = $merchant['id'];
        $data['mid'] = $mid;
        $data['order_num'] = $order_num;
        $data['type'] = 2;
        $data['cash'] = $cash;
        $data['tdate'] = time();
        $data['desc'] = $content['ps'];
        $data['auto'] = $auto;
        Dever::db('pay/yspay_cash_log')->insert($data);

        return $data['status'];
    }

    # 查询余额
    public function yue($config, $merchant)
    {
        $this->config = $config;
        //整理内容信息
        $content = [
            'merNo' => $merchant['merno'],
        ];
        Dever::log($content, 'yspay_yue');
        $result = $this->curl('202006', $content, false);
        if (isset($result['canPayAmt'])) {
            return $result['canPayAmt'];
        }
        return 0;
    }

    # 提现
    public function tixian($config, $merchant, $cash)
    {
        $this->config = $config;

        $mid = $merchant['mid'];

        //整理内容信息
        $content = [
            'merNo' => $merchant['merno'],
            'payAmt' => $cash,
            'ps' => $merchant['name'] . '划付',
        ];
        Dever::log($content, 'yspay_huafu_tixian');
        $result = $this->curl('202002', $content);

        return 'ok';
    }

    protected function getOrderNum($order_num)
    {
        $where['order_num'] = $order_num . '_' . Dever::rand(8, 0);
        $state = Dever::db('pay/yspay_cash_log')->one($where);
        if (!$state) {
            return $where['order_num'];
        } else {
            return $this->getOrderNum($order_num);
        }
    }

	protected function common($param, $code)
    {
        $param += array(
            'transCode' => $code,
            'verNo' => '100',
            'srcReqDate' => date("Ymd"),
            'srcReqTime' => date("His"),
            'srcReqId' => Dever::uuid(),
            'channelId' => '043',
            'groupId' => $this->config['cash_groupid'],
        );

        return $param;
    }

	protected function curl($code, $param, $state = true)
	{
		$url = self::$host;
		$url .= $code;

    	$param = $this->common($param, $code);
    	$param['signature'] = $this->sign($param);
    	$curl = Curl::getInstance($url, $param, 'post', true);
		$body = $curl->result();

		if (strstr($body, '<html><head>')) {
			return 'error';
		}
		$body = Dever::json_decode($body);
		if (isset($body['respCode'])) {
			if ($body['respCode'] == '99999999') {
				return $state ? 'ok' : $body;
			} elseif ($body['respCode'] == 'FAN00012') {
                return $this->curl($code, $param, $state);
            } else {
				return $body['respMsg'];
			}
		} else {
			return 'error';
		}
	}

	protected function sign($data)
	{
		$data = $this->getParams($data);
		$file = $this->config['cash_private_file'];
        if (!strstr($file, 'http')) {
            $file = Dever::local($file);
        }
        
		$pkcs12 = file_get_contents($file);
		openssl_pkcs12_read($pkcs12, $certs, $this->config['cash_private_file_password']);
		if (!$certs) {
            Dever::alert('private_key error');
        }
        $privateKey = $certs['pkey']; 
		if (openssl_sign(utf8_encode($data), $binarySignature, $privateKey, OPENSSL_ALGO_SHA256)) {
            return bin2hex($binarySignature);
        } else {
            return '';
        }
	}

	protected function checkSign($data, $signature)
	{
		$file = $this->config['cash_public_file'];
        if (!strstr($file, 'http')) {
            $file = Dever::local($file);
        }
		$cert = file_get_contents($file);
        $cert = '-----BEGIN CERTIFICATE-----' . PHP_EOL
            . chunk_split(base64_encode($cert), 64, PHP_EOL)
            . '-----END CERTIFICATE-----' . PHP_EOL;
        $pubKeyId = openssl_get_publickey($cert);
        $signature = hex2bin($signature);
        $ok = openssl_verify($data, $signature, $pubKeyId, OPENSSL_ALGO_SHA256);

        if ($ok == 1) {
            openssl_free_key($pubKeyId);
            return true;
        }
        return false;
	}

	protected function getParams($param)
	{
		ksort($param);
		$result = array();
		foreach ($param as $k => $v) {
			if (is_array($v)) {
                $v = json_encode($v, JSON_UNESCAPED_UNICODE);
            } elseif(trim($v) == ""){
                continue;
            }
            if (is_bool($v)) {
                $result[] = $v ? "$k=true" : "$k=false";
            } else {
                $result[] = $k . '=' . $v;
            }
		}
		$result = implode('&', $result);
        return $result;
	}
}