<?php

namespace App\Services\Payment;

use App\Services\BaseService;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Support\Facades\Log;

class ZimuPayService extends BaseService
{
    public const CHANNEL_RECHARGE = 'ZIMUpay';
    public const CHANNEL_WITHDRAW = 'ZIMUwithdraw';
    public const CHANNEL_CASH = 'ZIMUcash';

    public const PAY_STATUS_SUCCESS = '3';
    public const PAY_STATUS_FAIL = '2';

    public const WITHDRAW_STATUS_SUCCESS = '2';
    public const WITHDRAW_STATUS_FAIL = '5';

    public const CASH_STATUS_SUCCESS = '3';
    public const CASH_STATUS_FAIL = '4';

    public static function isRechargeChannel(?string $channel): bool
    {
        return in_array(strtolower((string)$channel), [
            strtolower(self::CHANNEL_RECHARGE),
            'zimupay',
            '808pay',
            '808支付',
        ], true);
    }

    public static function isWithdrawChannel(?string $channel): bool
    {
        return strtolower((string)$channel) === strtolower(self::CHANNEL_WITHDRAW);
    }

    public static function isCashChannel(?string $channel): bool
    {
        return strtolower((string)$channel) === strtolower(self::CHANNEL_CASH);
    }

    public static function isPayoutChannel(?string $channel): bool
    {
        return self::isWithdrawChannel($channel) || self::isCashChannel($channel);
    }

    public static function canUserRecharge($userId): bool
    {
        $allowedUserIds = array_values(array_filter(array_map(
            'trim',
            explode(',', (string)config('app.zimu_pay_recharge_user_ids', ''))
        )));

        if (empty($allowedUserIds)) {
            return true;
        }

        return in_array((string)$userId, $allowedUserIds, true);
    }

    public static function amount($amount): string
    {
        return number_format((float)$amount, 2, '.', '');
    }

    public static function getAppId(): string
    {
        return (string)config('app.zimu_pay_app_id');
    }

    public static function getSecret(): string
    {
        return (string)config('app.zimu_pay_key');
    }

    public static function getPayNotifyUrl(): string
    {
        return rtrim(config('app.url'), '/') . '/api/pay/harvest';
    }

    public static function getPayoutNotifyUrl(): string
    {
        return rtrim(config('app.url'), '/') . '/api/pay/notify';
    }

    public static function signature(array $params, ?string $key = null): string
    {
        unset($params['sign']);
        $params = array_filter($params, static function ($value) {
            return $value !== null && $value !== '';
        });
        ksort($params, SORT_STRING);

        $parts = [];
        foreach ($params as $name => $value) {
            $parts[] = $name . '=' . $value;
        }
        $parts[] = 'key=' . ($key ?? self::getSecret());

        return strtoupper(md5(implode('&', $parts)));
    }

    public static function pay($amount, string $orderNo, string $member): array
    {
        $data = self::signedData([
            'appId' => self::getAppId(),
            'mchOrderNo' => $orderNo,
            'amount' => self::amount($amount),
            'member' => $member,
            'notifyUrl' => self::getPayNotifyUrl(),
            'timestamp' => self::timestamp(),
            'nonce' => self::nonce(),
        ]);

        return self::post((string)config('app.zimu_pay_gateway'), $data);
    }

    public static function queryPayOrder(string $orderNo): array
    {
        return self::post((string)config('app.zimu_pay_query_gateway'), self::queryData($orderNo));
    }

    public static function withdraw($amount, string $orderNo, string $member, string $receiveAccount, string $realName = ''): array
    {
        $data = self::signedData([
            'appId' => self::getAppId(),
            'member' => $member,
            'realName' => $realName,
            'mchOrderNo' => $orderNo,
            'amount' => self::amount($amount),
            'notifyUrl' => self::getPayoutNotifyUrl(),
            'timestamp' => self::timestamp(),
            'nonce' => self::nonce(),
            'receiveAccount' => $receiveAccount,
        ]);

        return self::post((string)config('app.zimu_withdraw_gateway'), $data);
    }

    public static function queryWithdrawOrder(string $orderNo): array
    {
        return self::post((string)config('app.zimu_withdraw_query_gateway'), self::queryData($orderNo));
    }

    public static function cash($amount, string $orderNo, string $accountName, string $accountNo, string $bank, string $payMethod = ''): array
    {
        $data = self::signedData([
            'appId' => self::getAppId(),
            'mchOrderNo' => $orderNo,
            'amount' => self::amount($amount),
            'notifyUrl' => self::getPayoutNotifyUrl(),
            'accountName' => $accountName,
            'accountNo' => $accountNo,
            'bank' => $bank,
            'payMethod' => $payMethod,
            'timestamp' => self::timestamp(),
            'nonce' => self::nonce(),
        ]);

        return self::post((string)config('app.zimu_cash_gateway'), $data);
    }

    public static function queryCashOrder(string $orderNo): array
    {
        return self::post((string)config('app.zimu_cash_query_gateway'), self::queryData($orderNo));
    }

    public static function balance(): array
    {
        $data = self::signedData([
            'appId' => self::getAppId(),
            'timestamp' => self::timestamp(),
            'nonce' => self::nonce(),
        ]);

        return self::post((string)config('app.zimu_balance_gateway'), $data);
    }

    public static function verifyNotify(array $params): bool
    {
        if (self::getAppId() === '' || ($params['appId'] ?? '') !== self::getAppId() || empty($params['sign'])) {
            return false;
        }

        return hash_equals(self::signature($params), strtoupper((string)$params['sign']));
    }

    public static function notifySignatureDiagnostics(array $params): array
    {
        $fields = $params;
        unset($fields['sign']);

        return [
            'received_sign' => strtoupper((string)($params['sign'] ?? '')),
            'calculated_sign' => self::signature($params),
            'signing_fields' => array_keys(array_filter($fields, static function ($value) {
                return $value !== null && $value !== '';
            })),
        ];
    }

    public static function cashPayMethod(string $bankName): string
    {
        if (str_contains($bankName, '微信')) {
            return '2';
        }
        if (str_contains($bankName, '支付宝')) {
            return '3';
        }
        if (str_contains($bankName, '数字')) {
            return '4';
        }

        return '1';
    }

    private static function queryData(string $orderNo): array
    {
        return self::signedData([
            'appId' => self::getAppId(),
            'mchOrderNo' => $orderNo,
            'timestamp' => self::timestamp(),
            'nonce' => self::nonce(),
        ]);
    }

    private static function signedData(array $data): array
    {
        $data['sign'] = self::signature($data);
        return $data;
    }

    private static function timestamp(): string
    {
        return (string)round(microtime(true) * 1000);
    }

    private static function nonce(): string
    {
        return substr(str_replace('.', '', uniqid('', true)), 0, 15);
    }

    private static function post(string $url, array $data): array
    {
        $logData = $data;
        unset($logData['sign']);

        Log::info('ZIMU支付接口请求', [
            'url' => $url,
            'app_id' => self::getAppId(),
            'data' => $logData,
        ]);

        try {
            $response = (new Client(['timeout' => 10.0]))->post($url, [
                'json' => $data,
                'headers' => [
                    'Accept' => 'application/json',
                    'Content-Type' => 'application/json',
                ],
            ]);
            $body = $response->getBody()->getContents();

            Log::info('ZIMU支付接口响应', [
                'url' => $url,
                'app_id' => self::getAppId(),
                'http_status' => $response->getStatusCode(),
                'body' => $body,
            ]);

            return json_decode($body, true) ?: [];
        } catch (RequestException $e) {
            $response = $e->getResponse();
            $body = $response ? $response->getBody()->getContents() : '';

            Log::error('ZIMU支付接口请求失败', [
                'url' => $url,
                'app_id' => self::getAppId(),
                'http_status' => $response ? $response->getStatusCode() : null,
                'body' => $body,
                'error' => $e->getMessage(),
            ]);

            throw $e;
        } catch (\Throwable $e) {
            Log::error('ZIMU支付接口异常', [
                'url' => $url,
                'app_id' => self::getAppId(),
                'error' => $e->getMessage(),
            ]);

            throw $e;
        }
    }

    public static function getWhere(array $search = []): array
    {
        return [];
    }
}
