<?php

/**
 * 文件功能：微信机器人配置控制器
 *
 * @author   ChatRoom Laravel
 *
 * @version  1.0.0
 */

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Controller;
use App\Models\SysParam;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;

class WechatBotController extends Controller
{
    /**
     * 显示微信机器人配置表单
     */
    public function edit(): View
    {
        // 从 SysParam 获取配置，若不存在赋予默认空 JSON
        $param = SysParam::firstOrCreate(
            ['alias' => 'wechat_bot_config'],
            [
                'body' => json_encode([
                    'kafka' => [
                        'brokers' => '',
                        'topic' => '',
                        'group_id' => 'chatroom_wechat_bot',
                        'bot_wxid' => '',
                    ],
                    'api' => [
                        'base_url' => '',
                        'bot_key' => '',
                    ],
                    'global_notify' => [
                        'start_time' => '08:00',
                        'end_time' => '22:00',
                    ],
                    'group_notify' => [
                        'target_wxid' => '',
                        'toggle_admin_online' => false,
                        'toggle_baccarat_result' => false,
                        'toggle_lottery_result' => false,
                    ],
                    'personal_notify' => [
                        'toggle_friend_online' => false,
                        'toggle_spouse_online' => false,
                        'toggle_level_change' => false,
                    ],
                ]),
                'guidetxt' => '微信机器人全站配置（包含群聊推送和私聊推送开关及Kafka连接）',
            ]
        );

        $config = json_decode($param->body, true);

        return view('admin.wechat_bot.edit', compact('config'));
    }

    /**
     * 更新微信机器人配置
     */
    public function update(Request $request): RedirectResponse
    {
        $validated = $request->validate([
            'kafka_brokers' => 'nullable|string',
            'kafka_topic' => 'nullable|string',
            'kafka_group_id' => 'nullable|string',
            'kafka_bot_wxid' => 'nullable|string',
            'api_base_url' => 'nullable|string',
            'api_bot_key' => 'nullable|string',
            'qrcode_image' => 'nullable|image|max:2048',
            'global_start_time' => 'nullable|string',
            'global_end_time' => 'nullable|string',
            'group_target_wxid' => 'nullable|string',
            'toggle_admin_online' => 'nullable|boolean',
            'toggle_baccarat_result' => 'nullable|boolean',
            'toggle_lottery_result' => 'nullable|boolean',
            'toggle_friend_online' => 'nullable|boolean',
            'toggle_spouse_online' => 'nullable|boolean',
            'toggle_level_change' => 'nullable|boolean',
        ]);

        $param = SysParam::where('alias', 'wechat_bot_config')->first();
        $oldConfig = $param ? (json_decode($param->body, true) ?? []) : [];

        $qrcodePath = $oldConfig['api']['qrcode_image'] ?? '';
        if ($request->hasFile('qrcode_image')) {
            // 删除旧图
            if ($qrcodePath && \Illuminate\Support\Facades\Storage::disk('public')->exists($qrcodePath)) {
                \Illuminate\Support\Facades\Storage::disk('public')->delete($qrcodePath);
            }
            $qrcodePath = $request->file('qrcode_image')->store('wechat', 'public');
        }

        $config = [
            'kafka' => [
                'brokers' => $validated['kafka_brokers'] ?? '',
                'topic' => $validated['kafka_topic'] ?? '',
                'group_id' => $validated['kafka_group_id'] ?? 'chatroom_wechat_bot',
                'bot_wxid' => $validated['kafka_bot_wxid'] ?? '',
            ],
            'api' => [
                'base_url' => $validated['api_base_url'] ?? '',
                'bot_key' => $validated['api_bot_key'] ?? '',
                'qrcode_image' => $qrcodePath,
            ],
            'global_notify' => [
                'start_time' => $validated['global_start_time'] ?? '',
                'end_time' => $validated['global_end_time'] ?? '',
            ],
            'group_notify' => [
                'target_wxid' => $validated['group_target_wxid'] ?? '',
                'toggle_admin_online' => $validated['toggle_admin_online'] ?? false,
                'toggle_baccarat_result' => $validated['toggle_baccarat_result'] ?? false,
                'toggle_lottery_result' => $validated['toggle_lottery_result'] ?? false,
            ],
            'personal_notify' => [
                'toggle_friend_online' => $validated['toggle_friend_online'] ?? false,
                'toggle_spouse_online' => $validated['toggle_spouse_online'] ?? false,
                'toggle_level_change' => $validated['toggle_level_change'] ?? false,
            ],
        ];

        if ($param) {
            $param->update(['body' => json_encode($config)]);
            SysParam::clearCache('wechat_bot_config');
        }

        return redirect()->route('admin.wechat_bot.edit')->with('success', '机器相关配置已更新完成。如修改了Kafka请重启后端监听队列守护进程。');
    }

    /**
     * 发送群内公告
     */
    public function sendAnnouncement(Request $request, \App\Services\WechatBot\WechatNotificationService $wechatService): RedirectResponse
    {
        $validated = $request->validate([
            'announcement_content' => 'required|string|max:1000',
        ], [
            'announcement_content.required' => '请输入公告内容',
            'announcement_content.max' => '公告内容太长，不能超过1000字',
        ]);

        try {
            $wechatService->sendCustomGroupAnnouncement($validated['announcement_content']);

            return back()->with('success', '群公告已通过微信机器人发送成功！（消息已进入队列）');
        } catch (\Exception $e) {
            return back()->withInput()->withErrors(['announcement_content' => $e->getMessage()]);
        }
    }
}
