<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class HolidayWheelController
{
    /**
     * 节假日大转盘配置页
     */
    public function index(Request $request)
    {
        // 活动配置（只取一条最新的）
        $activity = DB::connection('write')
            ->table('agent.dbo.holiday_wheel_activity')
            ->orderBy('id', 'desc')
            ->first();

        if ($activity) {
            $activity = (array)$activity;
            $activity['recharge_rules'] = $activity['recharge_rules'] ?? '';
        } else {
            $activity = [
                'id' => 0,
                'start_time' => null,
                'end_time' => null,
                'status' => 0,
                'icon_url' => '',
                'recharge_rules' => json_encode([
                    ['amount' => 9.99, 'times' => 1],
                    ['amount' => 19.99, 'times' => 3],
                    ['amount' => 49.99, 'times' => 6],
                ], JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT),
            ];
        }

        // 解析充值规则为数组，供前端更友好编辑
        $rules = [];
        if (!empty($activity['recharge_rules'])) {
            $decodedRules = json_decode($activity['recharge_rules'], true);
            if (is_array($decodedRules)) {
                $rules = $decodedRules;
            }
        }
        if (empty($rules)) {
            $rules = [
                ['amount' => 9.99, 'times' => 1],
                ['amount' => 19.99, 'times' => 3],
                ['amount' => 49.99, 'times' => 6],
            ];
        }

        // 16 档配置
        $configs = DB::connection('write')
            ->table('agent.dbo.holiday_wheel_config')
            ->orderBy('sort_index', 'asc')
            ->orderBy('slot_index', 'asc')
            ->get();

        // 确保有 0-15 共 16 个档位
        $byIndex = [];
        foreach ($configs as $cfg) {
            $byIndex[(int)$cfg->slot_index] = $cfg;
        }

        $slots = [];
        for ($i = 0; $i < 16; $i++) {
            if (isset($byIndex[$i])) {
                $row = $byIndex[$i];
                $slots[] = [
                    'id' => $row->id,
                    'slot_index' => (int)$row->slot_index,
                    'reward' => (float)$row->reward,
                    'weight' => (int)$row->weight,
                    'sort_index' => (int)$row->sort_index,
                ];
            } else {
                $slots[] = [
                    'id' => 0,
                    'slot_index' => $i,
                    'reward' => 0,
                    'weight' => 0,
                    'sort_index' => $i,
                ];
            }
        }

        return view('admin.holiday_wheel.index', [
            'activity' => $activity,
            'slots' => $slots,
            'rules' => $rules,
        ]);
    }

    /**
     * 保存活动配置 + 16档权重
     */
    public function update(Request $request)
    {
        // 活动配置
        $status = (int)$request->input('status', 0);
        $start_time = $request->input('start_time');
        $end_time = $request->input('end_time');
        $icon_url = $request->input('icon_url', '');
        $recharge_rules = $request->input('recharge_rules', '');

        // 支持 datetime-local 格式（YYYY-MM-DDTHH:MM）
        if ($start_time && strpos($start_time, 'T') !== false) {
            $start_time = str_replace('T', ' ', $start_time) . ':00';
        }
        if ($end_time && strpos($end_time, 'T') !== false) {
            $end_time = str_replace('T', ' ', $end_time) . ':00';
        }

        // 简单校验 JSON（来自前端构造）
        if ($recharge_rules) {
            $decoded = json_decode($recharge_rules, true);
            if (json_last_error() !== JSON_ERROR_NONE) {
                return apiReturnFail('充值规则 JSON 格式错误：' . json_last_error_msg());
            }
            $recharge_rules = json_encode($decoded, JSON_UNESCAPED_UNICODE);
        }

        DB::connection('write')->beginTransaction();
        try {
            // upsert 活动配置（只保留一条）
            $activity = DB::connection('write')
                ->table('agent.dbo.holiday_wheel_activity')
                ->orderBy('id', 'desc')
                ->lockForUpdate()
                ->first();

            $data = [
                'start_time' => $start_time ?: null,
                'end_time' => $end_time ?: null,
                'status' => $status,
                'icon_url' => $icon_url,
                'recharge_rules' => $recharge_rules,
                'updated_at' => now(),
            ];

            if ($activity) {
                DB::connection('write')
                    ->table('agent.dbo.holiday_wheel_activity')
                    ->where('id', $activity->id)
                    ->update($data);
            } else {
                $data['created_at'] = now();
                DB::connection('write')
                    ->table('agent.dbo.holiday_wheel_activity')
                    ->insert($data);
            }

            // 16 档配置
            $slots = $request->input('slots', []);
            if (!empty($slots) && is_array($slots)) {
                foreach ($slots as $slotIndex => $row) {
                    $slotIndex = (int)$slotIndex;
                    if ($slotIndex < 0 || $slotIndex > 15) {
                        continue;
                    }
                    $reward = isset($row['reward']) ? (float)$row['reward'] : 0;
                    $weight = isset($row['weight']) ? (int)$row['weight'] : 0;
                    $sortIndex = isset($row['sort_index']) ? (int)$row['sort_index'] : $slotIndex;

                    $exists = DB::connection('write')
                        ->table('agent.dbo.holiday_wheel_config')
                        ->where('slot_index', $slotIndex)
                        ->first();

                    $cfgData = [
                        'reward' => $reward,
                        'weight' => $weight,
                        'sort_index' => $sortIndex,
                        'updated_at' => now(),
                    ];

                    if ($exists) {
                        DB::connection('write')
                            ->table('agent.dbo.holiday_wheel_config')
                            ->where('slot_index', $slotIndex)
                            ->update($cfgData);
                    } else {
                        $cfgData['slot_index'] = $slotIndex;
                        $cfgData['created_at'] = now();
                        DB::connection('write')
                            ->table('agent.dbo.holiday_wheel_config')
                            ->insert($cfgData);
                    }
                }
            }

            DB::connection('write')->commit();
        } catch (\Throwable $e) {
            DB::connection('write')->rollBack();
            return apiReturnFail('保存失败：' . $e->getMessage());
        }

        return apiReturnSuc('保存成功');
    }

    /**
     * 节假日大转盘 - 抽奖记录列表
     */
    public function history(Request $request)
    {
        $userId = (int)$request->input('user_id', 0);
        $gameId = (int)$request->input('game_id', 0);
        $startDate = $request->input('start_date', '');
        $endDate = $request->input('end_date', '');

        $query = DB::connection('write')
            ->table('agent.dbo.holiday_wheel_history as h')
            ->leftJoin('QPAccountsDB.dbo.AccountsInfo as ai', 'h.UserID', '=', 'ai.UserID')
            ->select(
                'h.id',
                'h.UserID',
                'ai.GameID',
                'ai.NickName',
                'h.slot_index',
                'h.reward',
                'h.created_at'
            )
            ->orderBy('h.id', 'desc');

        if ($userId > 0) {
            $query->where('h.UserID', $userId);
        }

        if ($gameId > 0) {
            $query->where('ai.GameID', $gameId);
        }

        if ($startDate) {
            $query->where('h.created_at', '>=', $startDate . ' 00:00:00');
        }
        if ($endDate) {
            $query->where('h.created_at', '<=', $endDate . ' 23:59:59');
        }

        $list = $query->paginate(20);

        return view('admin.holiday_wheel.history', [
            'list' => $list,
            'user_id' => $userId,
            'game_id' => $gameId,
            'start_date' => $startDate,
            'end_date' => $endDate,
        ]);
    }
}

