<?php

namespace Kylin\Payment\Services;

use Illuminate\Support\Facades\Log;
use Kylin\Payment\Payment;
use Illuminate\Contracts\Container\Container;

/**
 * 支付分账服务类
 */
class ProfitSharingService
{
    /**
     * 构造函数
     */
    public function __construct(
        protected readonly Container $app,
        protected readonly Payment $payment
    ) {
    }

    /**
     * 发起分账
     */
    public function share(string $type, array $params, string $name = 'default'): mixed
    {
        try {
            // 获取支付网关
            $gateway = $this->payment->manager()->gateway($type, $name);

            // 检查网关是否支持分账
            if (!method_exists($gateway, 'share')) {
                throw new \Exception('该支付方式不支持分账功能');
            }

            // 发起分账
            $result = $gateway->share($params);

            Log::info('发起分账成功', [
                'type' => $type,
                'params' => $params,
                'result' => $result,
            ]);

            return $result;
        } catch (\Exception $e) {
            Log::error('发起分账失败', [
                'type' => $type,
                'params' => $params,
                'error' => $e->getMessage(),
            ]);
            throw $e;
        }
    }

    /**
     * 查询分账
     */
    public function queryShare(string $type, array $params, string $name = 'default'): mixed
    {
        try {
            // 获取支付网关
            $gateway = $this->payment->manager()->gateway($type, $name);

            // 检查网关是否支持分账查询
            if (!method_exists($gateway, 'queryShare')) {
                throw new \Exception('该支付方式不支持分账查询功能');
            }

            // 查询分账
            $result = $gateway->queryShare($params);

            Log::info('查询分账成功', [
                'type' => $type,
                'params' => $params,
                'result' => $result,
            ]);

            return $result;
        } catch (\Exception $e) {
            Log::error('查询分账失败', [
                'type' => $type,
                'params' => $params,
                'error' => $e->getMessage(),
            ]);
            throw $e;
        }
    }

    /**
     * 关闭分账
     */
    public function closeShare(string $type, array $params, string $name = 'default'): mixed
    {
        try {
            // 获取支付网关
            $gateway = $this->payment->manager()->gateway($type, $name);

            // 检查网关是否支持关闭分账
            if (!method_exists($gateway, 'closeShare')) {
                throw new \Exception('该支付方式不支持关闭分账功能');
            }

            // 关闭分账
            $result = $gateway->closeShare($params);

            Log::info('关闭分账成功', [
                'type' => $type,
                'params' => $params,
                'result' => $result,
            ]);

            return $result;
        } catch (\Exception $e) {
            Log::error('关闭分账失败', [
                'type' => $type,
                'params' => $params,
                'error' => $e->getMessage(),
            ]);
            throw $e;
        }
    }

    /**
     * 分账回退
     */
    public function refundShare(string $type, array $params, string $name = 'default'): mixed
    {
        try {
            // 获取支付网关
            $gateway = $this->payment->manager()->gateway($type, $name);

            // 检查网关是否支持分账回退
            if (!method_exists($gateway, 'refundShare')) {
                throw new \Exception('该支付方式不支持分账回退功能');
            }

            // 分账回退
            $result = $gateway->refundShare($params);

            Log::info('分账回退成功', [
                'type' => $type,
                'params' => $params,
                'result' => $result,
            ]);

            return $result;
        } catch (\Exception $e) {
            Log::error('分账回退失败', [
                'type' => $type,
                'params' => $params,
                'error' => $e->getMessage(),
            ]);
            throw $e;
        }
    }

    /**
     * 添加分账接收方
     */
    public function addReceiver(string $type, array $params, string $name = 'default'): mixed
    {
        try {
            // 获取支付网关
            $gateway = $this->payment->manager()->gateway($type, $name);

            // 检查网关是否支持添加分账接收方
            if (!method_exists($gateway, 'addReceiver')) {
                throw new \Exception('该支付方式不支持添加分账接收方功能');
            }

            // 添加分账接收方
            $result = $gateway->addReceiver($params);

            Log::info('添加分账接收方成功', [
                'type' => $type,
                'params' => $params,
                'result' => $result,
            ]);

            return $result;
        } catch (\Exception $e) {
            Log::error('添加分账接收方失败', [
                'type' => $type,
                'params' => $params,
                'error' => $e->getMessage(),
            ]);
            throw $e;
        }
    }

    /**
     * 删除分账接收方
     */
    public function removeReceiver(string $type, array $params, string $name = 'default'): mixed
    {
        try {
            // 获取支付网关
            $gateway = $this->payment->manager()->gateway($type, $name);

            // 检查网关是否支持删除分账接收方
            if (!method_exists($gateway, 'removeReceiver')) {
                throw new \Exception('该支付方式不支持删除分账接收方功能');
            }

            // 删除分账接收方
            $result = $gateway->removeReceiver($params);

            Log::info('删除分账接收方成功', [
                'type' => $type,
                'params' => $params,
                'result' => $result,
            ]);

            return $result;
        } catch (\Exception $e) {
            Log::error('删除分账接收方失败', [
                'type' => $type,
                'params' => $params,
                'error' => $e->getMessage(),
            ]);
            throw $e;
        }
    }

    /**
     * 计算分账金额
     */
    public function calculateShareAmount(float $totalAmount, array $receivers): array
    {
        $result = [];
        $totalShare = 0;

        foreach ($receivers as $receiver) {
            if (isset($receiver['amount'])) {
                // 固定金额
                $amount = $receiver['amount'];
            } elseif (isset($receiver['ratio'])) {
                // 比例
                $amount = $totalAmount * ($receiver['ratio'] / 100);
            } else {
                continue;
            }

            $result[] = array_merge($receiver, [
                'amount' => round($amount, 2),
            ]);

            $totalShare += $amount;
        }

        // 检查分账总额是否超过总金额
        if ($totalShare > $totalAmount) {
            throw new \Exception('分账总额不能超过订单总金额');
        }

        // 计算剩余金额（平台留存）
        $platformAmount = round($totalAmount - $totalShare, 2);

        return [
            'receivers' => $result,
            'platform_amount' => $platformAmount,
            'total_share' => round($totalShare, 2),
        ];
    }

    /**
     * 微信支付分账
     */
    public function wechatShare(array $params, string $name = 'default'): mixed
    {
        return $this->share('wechat', $params, $name);
    }

    /**
     * 支付宝分账
     */
    public function alipayShare(array $params, string $name = 'default'): mixed
    {
        return $this->share('alipay', $params, $name);
    }

    /**
     * 抖音支付分账
     */
    public function douyinShare(array $params, string $name = 'default'): mixed
    {
        return $this->share('douyin', $params, $name);
    }
}