<?php
namespace app\api\logic;

use app\common\service\ConfigService;

class ArticleRedLogic
{
    /**
     * 检查红包功能是否开启
     */
    public static function checkRedOpen()
    {
        $redOpen = ConfigService::get('articlered', 'red_open', 0);
        if (!$redOpen) {
            throw new \Exception('红包功能未开启');
        }
    }

    /**
     * 获取红包配置
     */
    public static function getConfig()
    {
        return [
            'red_open' => ConfigService::get('articlered', 'red_open', 0),
            'red_pay_mode' => ConfigService::get('articlered', 'red_pay_mode', 0),
            'red_mode' => ConfigService::get('articlered', 'red_mode', ''),
            'red_fee' => ConfigService::get('articlered', 'red_fee', 0),
            'red_day_phone_limit' => ConfigService::get('articlered', 'red_day_phone_limit', 0),
            'red_day_ID_limit' => ConfigService::get('articlered', 'red_day_ID_limit', 0),
            'red_day_IP_limit' => ConfigService::get('articlered', 'red_day_IP_limit', 0),
            'red_receive_allow_ip' => ConfigService::get('articlered', 'red_receive_allow_ip', ''),
        ];
    }

    /**
     * 解析红包规格
     */
    public static function parseRedMode()
    {
        $redMode = ConfigService::get('articlered', 'red_mode', '');
        if (empty($redMode)) {
            throw new \Exception('请先设置红包规格');
        }

        $rules = explode(' ', $redMode);
        $config = [];
        
        foreach ($rules as $rule) {
            list($amount, $count) = explode('=', $rule);
            $config[] = [
                'amount' => (float)$amount,
                'count' => (int)$count,
                'total' => (float)$amount * (int)$count
            ];
        }

        return $config;
    }

    /**
     * 计算手续费
     */
    public static function calculateFee($amount)
    {
        $feeRate = ConfigService::get('articlered', 'red_fee', 0) / 100;
        return $amount * $feeRate;
    }

    /**
     * 检查领取限制
     */
    public static function checkReceiveLimit($userId, $ip, $phone)
    {
        $today = strtotime(date('Y-m-d'));
        
        // 检查手机号限制
        $phoneLimit = ConfigService::get('articlered', 'red_day_phone_limit', 0);
        if ($phoneLimit > 0) {
            $count = \app\common\model\TradeRedPacketRecords::where([
                'phone' => $phone,
                'create_time' => ['>=', $today]
            ])->count();
            if ($count >= $phoneLimit) {
                throw new \Exception('手机号领取次数已达上限');
            }
        }

        // 检查ID限制
        $idLimit = ConfigService::get('articlered', 'red_day_ID_limit', 0);
        if ($idLimit > 0) {
            $count = \app\common\model\TradeRedPacketRecords::where([
                'receiv_user_id' => $userId,
                'create_time' => ['>=', $today]
            ])->count();
            if ($count >= $idLimit) {
                throw new \Exception('账号领取次数已达上限');
            }
        }

        // 检查IP限制
        $ipLimit = ConfigService::get('articlered', 'red_day_IP_limit', 0);
        if ($ipLimit > 0) {
            $count = \app\common\model\TradeRedPacketRecords::where([
                'ip' => $ip,
                'create_time' => ['>=', $today]
            ])->count();
            if ($count >= $ipLimit) {
                throw new \Exception('IP领取次数已达上限');
            }
        }

        // 检查地区限制
        $allowIp = ConfigService::get('articlered', 'red_receive_allow_ip', '');
        if (!empty($allowIp)) {
            // 这里可以添加IP地区检测逻辑
        }
    }

    /**
     * 检查付费模式
     */
    public static function checkPayMode($userId, $amount)
    {
        $payMode = ConfigService::get('articlered', 'red_pay_mode', 0);
        $user = \app\common\model\User::find($userId);
        
        if ($payMode == 0) {
            // 积分支付
            if ($user->score < $amount) {
                throw new \Exception('积分不足');
            }
        } else {
            // 余额支付
            if ($user->balance < $amount) {
                throw new \Exception('余额不足');
            }
        }
        
        return $payMode;
    }

    /**
     * 扣除用户资金
     */
    public static function deductFunds($userId, $amount, $payMode)
    {
        $user = \app\common\model\User::find($userId);
        
        if ($payMode == 0) {
            // 积分支付
            $user->score -= $amount;
        } else {
            // 余额支付
            $user->balance -= $amount;
        }
        
        $user->save();
    }

    /**
     * 增加用户资金
     */
    public static function addFunds($userId, $amount, $payMode)
    {
        $user = \app\common\model\User::find($userId);
        
        if ($payMode == 0) {
            // 积分支付
            $user->score += $amount;
        } else {
            // 余额支付
            $user->balance += $amount;
        }
        
        $user->save();
    }

    /**
     * 发送红包
     */
    public function sendRedPacket($articleId, $redParams, $userId)
    {
        // 检查红包功能是否开启
        self::checkRedOpen();

        // 解析红包规格
        $modes = self::parseRedMode();
        $selectedMode = $modes[$redParams['mode_index']] ?? null;
        if (!$selectedMode) {
            throw new \Exception('无效的红包规格');
        }

        // 计算总金额和手续费
        $totalAmount = $selectedMode['total'];
        $fee = self::calculateFee($totalAmount);
        $actualPay = $totalAmount + $fee;

        // 检查付费模式和资金
        $payMode = self::checkPayMode($userId, $actualPay);

        // 扣除用户资金
        self::deductFunds($userId, $actualPay, $payMode);

        // 创建红包记录
        $redPacket = \app\common\model\TradeRedPackets::create([
            'user_id' => $userId,
            'article_id' => $articleId,
            'total_amount' => $totalAmount,
            'total_count' => $selectedMode['count'],
            'remain_amount' => $totalAmount,
            'remain_count' => $selectedMode['count'],
            'pay_mode' => $payMode,
            'fee' => $fee,
            'status' => 1,
            'create_time' => time(),
            'open_time' => time()
        ]);

        // 关联文章和红包
        \app\common\model\TradeArticleRedPackets::create([
            'article_id' => $articleId,
            'packet_id' => $redPacket->id,
            'create_time' => time()
        ]);

        return $redPacket->id;
    }
}