<?php

namespace App\Services;

use App\Util;

class WiwiPay
{
    public $config;
    public $key;
    public $mchNo;
    public $apiUrl;

    public function __construct()
    {
        $payConfigService = new PayConfig();
        $this->config = $payConfigService->getConfig('WiwiPay');
        
        $this->key = $this->config['key'] ?? '';
        $this->mchNo = $this->config['mchNo'] ?? '';
        $this->apiUrl = $this->config['apiUrl'];
    }

    /**
     * 签名
     */
    public function sign(array $params): array
    {
        return PayUtils::sign($params, $this->key);
    }

    /**
     * 验签
     */
    public function verifySign(array $params): bool
    {
        return PayUtils::verifySign($params, $this->key);
    }

    /**
     * 生成随机字符串
     */
    public function getNonceStr($length = 16): string
    {
        $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    /**
     * POST请求
     */
    public function curlPost($url, $payload)
    {
        $timeout = 20;
        $data = json_encode($payload, JSON_UNESCAPED_UNICODE);
        
        $headers = [
            'Content-Type: application/json',
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $result = curl_exec($ch);

        if (curl_errno($ch)) {
            $error = curl_error($ch);
            Util::WriteLog('WiwiPay_error', 'CURL Error: ' . $error);
            curl_close($ch);
            return false;
        }

        if (strstr($result, 'code') || $httpCode != 200) {
//            Util::WriteLog('WiwiPay_error', 'error_state_' . $httpCode . "|" . $result);
        }

        curl_close($ch);
        return $result;
    }
}
