<?php

namespace App\Http\Controllers\Admin;

use App\Game\WebChannelConfig;
use App\Game\WebRegionConfig;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class WebChannelConfigController
{
    protected $groupColors = [
        0 => '#007bff', // blue
        1 => '#28a745', // green
        2 => '#ffc107', // yellow/orange
        3 => '#dc3545', // red
        4 => '#6f42c1', // purple
        5 => '#17a2b8', // cyan
        6 => '#6c757d', // gray
        7 => '#e83e8c', // pink
    ];

    protected $specialModes = [
        1 => 'GUEST (自动游客登录模式)',
        2 => 'ZERO_MONEY (注册不送钱)',
        4 => 'DISABLE_PROMOTE_INSTALL (提示安装)',
        8 => 'PWA_BONUS (安装app送钱)',
        16 => 'REG_TO_REALMONEY (注册返回就是真金)',
        32 => 'MAIL_BONUS (MAIL验证送钱)',
        64 => 'FIRSTPAY_OFF30 (首冲打开30%bonus)',
        128 => 'DEBUG_EVENT (是否开启事件日志上报)',
        256 => 'REGION_UNIQUE (是否开启区域独立模式)',
        512 => 'FB_JUMP_LATER (fb内浏览器弹出时机在绑定手机后)',
        1024 => 'FB_JUMP_LATER2 (fb内浏览器弹出在点击提现后)',
    ];

    public function index(Request $request)
    {
        $channel = $request->input('Channel');
        $packageName = $request->input('PackageName');

        $query = WebChannelConfig::query();

        if ($channel) {
            $query->where('Channel', $channel);
        }
        if ($packageName) {
            $query->where('PackageName', 'like', '%' . $packageName . '%');
        }

        $list = $query->orderBy('Channel', 'asc')->paginate(40);

        $regions = WebRegionConfig::all();
        $regionMap = [];
        $regionUrlMap = [];
        foreach ($regions as $region) {
            $logoUrl = $region->DomainUrl . $region->LogoUrl;
            $isSvg = !empty($region->LogoUrl) && strtolower(pathinfo($region->LogoUrl, PATHINFO_EXTENSION)) === 'svg';

            $regionMap[$region->RegionID] = [
                'color' => $this->groupColors[$region->GroupID] ?? '#000000',
                'logo' => $logoUrl,
                'has_logo' => !empty($region->LogoUrl),
                'is_svg' => $isSvg
            ];
            // 构建区域的 URL 映射
            $regionUrlMap[$region->RegionID] = $region->DomainUrl;
        }

        // 为每条记录计算网站地址
        $channelUrls = [];
        foreach ($list as $item) {
            $url = '';
            // 优先：如果 WebChannelConfig 绑定了 RegionID，直接使用该 Region 的 URL
            if (!empty($item->RegionID) && isset($regionUrlMap[$item->RegionID])) {
                $url = rtrim($regionUrlMap[$item->RegionID], '/') . '/?c=' . $item->Channel;
            }
            $channelUrls[$item->ID] = $url;
        }

        return view('admin.web_channel_config.index', [
            'list' => $list,
            'channel' => $channel,
            'packageName' => $packageName,
            'regionMap' => $regionMap,
            'channelUrls' => $channelUrls,
        ]);
    }

    public function create()
    {
        $regionList = WebRegionConfig::orderBy('GroupID', 'asc')->get();
        return view('admin.web_channel_config.add', [
            'regionList' => $regionList,
            'groupColors' => $this->groupColors,
            'specialModes' => $this->specialModes
        ]);
    }

    public function store(Request $request)
    {
        $data = $request->all();
        $validator = Validator::make($data, [
            'Channel' => 'required|integer',
            'PackageName' => 'required|string|max:200',
        ]);

        if ($validator->fails()) {
            return apiReturnFail($validator->errors()->first());
        }

        // 处理 BonusArr
        $bonusArr = [
            $request->input('BonusArr_REG', 0),
            $request->input('BonusArr_MOBILE', 0),
            $request->input('BonusArr_EMAIL', 0),
            $request->input('BonusArr_PWA', 0),
        ];
        $data['BonusArr'] = implode('|', $bonusArr);

        // 处理 LoginOpen 和 RegOpen (多选框)
        $data['LoginOpen'] = $request->has('LoginOpen') ? implode(',', $request->input('LoginOpen')) : '';
        $data['RegOpen'] = $request->has('RegOpen') ? implode(',', $request->input('RegOpen')) : '';

        // 处理 SpecialMode (多选框位运算)
        $specialMode = 0;
        if ($request->has('SpecialMode') && is_array($request->input('SpecialMode'))) {
            foreach ($request->input('SpecialMode') as $val) {
                $specialMode += (int)$val;
            }
        }
        $data['SpecialMode'] = $specialMode;

        // 防止 null 报错
        $data['ShadowChannel'] = $data['ShadowChannel'] ?? '';
        $data['LightApk'] = $data['LightApk'] ?? '';
        $data['FullApk'] = $data['FullApk'] ?? '';
        $data['PlatformID'] = $data['PlatformID'] ?? '';
        $data['PlatformToken'] = $data['PlatformToken'] ?? '';
        $data['RegionID'] = $data['RegionID'] ?? '';

        $config = WebChannelConfig::create($data);

        // 同步更新 WebRegionConfig 的 BindChannels
        if (!empty($config->RegionID)) {
            $region = WebRegionConfig::where('RegionID', $config->RegionID)->first();
            if ($region) {
                $bindChannels = is_array($region->BindChannels) ? $region->BindChannels : [];
                if (!in_array($config->Channel, $bindChannels)) {
                    $bindChannels[] = (int)$config->Channel;
                    sort($bindChannels);
                    $region->BindChannels = $bindChannels;
                    $region->save();
                }
            }
        }

        return apiReturnSuc();
    }

    public function edit($id)
    {
        $info = WebChannelConfig::findOrFail($id);
        $regionList = WebRegionConfig::orderBy('GroupID', 'asc')->get();
        return view('admin.web_channel_config.edit', [
            'info' => $info,
            'regionList' => $regionList,
            'groupColors' => $this->groupColors,
            'specialModes' => $this->specialModes
        ]);
    }

    public function update(Request $request, $id)
    {
        $data = $request->all();
        $info = WebChannelConfig::findOrFail($id);
        
        $validator = Validator::make($data, [
            'PackageName' => 'required|string|max:200',
        ]);

        if ($validator->fails()) {
            return apiReturnFail($validator->errors()->first());
        }

        // 确保 Channel 不被修改
        unset($data['Channel']);

        // 处理 BonusArr
        $bonusArr = [
            $request->input('BonusArr_REG', 0),
            $request->input('BonusArr_MOBILE', 0),
            $request->input('BonusArr_EMAIL', 0),
            $request->input('BonusArr_PWA', 0),
        ];
        $data['BonusArr'] = implode('|', $bonusArr);

        // 处理 LoginOpen 和 RegOpen (多选框)
        $data['LoginOpen'] = $request->has('LoginOpen') ? implode(',', $request->input('LoginOpen')) : '';
        $data['RegOpen'] = $request->has('RegOpen') ? implode(',', $request->input('RegOpen')) : '';

        // 处理 SpecialMode (多选框位运算)
        $specialMode = 0;
        if ($request->has('SpecialMode') && is_array($request->input('SpecialMode'))) {
            foreach ($request->input('SpecialMode') as $val) {
                $specialMode += (int)$val;
            }
        }
        $data['SpecialMode'] = $specialMode;

        // 防止 null 报错
        $data['ShadowChannel'] = $data['ShadowChannel'] ?? '';
        $data['LightApk'] = $data['LightApk'] ?? '';
        $data['FullApk'] = $data['FullApk'] ?? '';
        $data['PlatformID'] = $data['PlatformID'] ?? '';
        $data['PlatformToken'] = $data['PlatformToken'] ?? '';
        $data['RegionID'] = $data['RegionID'] ?? '';
        $data['PlatformName'] = $data['PlatformName'] ?? '';

        $oldRegionID = $info->RegionID;
        $oldChannel = $info->Channel;
        $oldSpecialMode = $info->SpecialMode;

        // 一旦启用 REGION_UNIQUE，RegionID 不可更换同时 REGION_UNIQUE 选项不可更改
        if (($oldSpecialMode & 256) == 256) {
            $data['RegionID'] = $oldRegionID;
            if (!in_array(256, $request->input('SpecialMode', []))) {
                $specialMode += 256;
                $data['SpecialMode'] = $specialMode;
            }
        }

        $info->update($data);

        // 同步更新 WebRegionConfig 的 BindChannels
        // 1. 从旧的 RegionID 中移除旧的 Channel
        if (!empty($oldRegionID)) {
            $oldRegion = WebRegionConfig::where('RegionID', $oldRegionID)->first();
            if ($oldRegion) {
                $bindChannels = is_array($oldRegion->BindChannels) ? $oldRegion->BindChannels : [];
                $key = array_search($oldChannel, $bindChannels);
                if ($key !== false) {
                    unset($bindChannels[$key]);
                    $oldRegion->BindChannels = array_values($bindChannels);
                    $oldRegion->save();
                }
            }
        }

        // 2. 向新的 RegionID 中添加新的 Channel（如果新 RegionID 不为空）
        if (!empty($info->RegionID)) {
            $newRegion = WebRegionConfig::where('RegionID', $info->RegionID)->first();
            if ($newRegion) {
                $bindChannels = is_array($newRegion->BindChannels) ? $newRegion->BindChannels : [];
                if (!in_array($info->Channel, $bindChannels)) {
                    $bindChannels[] = (int)$info->Channel;
                    sort($bindChannels);
                    $newRegion->BindChannels = $bindChannels;
                    $newRegion->save();
                }
            }
        }

        return apiReturnSuc();
    }

    public function destroy($id)
    {
        $info = WebChannelConfig::findOrFail($id);
        $channel = $info->Channel;
        $regionID = $info->RegionID;

        $info->delete();

        // 删除时，从 WebRegionConfig 的 BindChannels 中移除该 Channel
        if (!empty($regionID)) {
            $region = WebRegionConfig::where('RegionID', $regionID)->first();
            if ($region) {
                $bindChannels = is_array($region->BindChannels) ? $region->BindChannels : [];
                $key = array_search($channel, $bindChannels);
                if ($key !== false) {
                    unset($bindChannels[$key]);
                    $region->BindChannels = array_values($bindChannels);
                    $region->save();
                }
            }
        }

        return apiReturnSuc();
    }

    public function remarks(Request $request, $id)
    {
        $remark = $request->input('remark', '');

        // 查找 WebChannelConfig 记录
        $config = WebChannelConfig::find($id);
        if (!$config) {
            return apiReturnFail('记录不存在');
        }

        $channel = $config->Channel;
        $packageName = $config->PackageName;

        // 更新 WebChannelConfig 的备注
        if (WebChannelConfig::where('Channel', $channel)->exists()) {
            WebChannelConfig::where('Channel', $channel)->update(['Remarks' => $remark]);
        } else {
            // 如果不存在，使用渠道100的配置作为模板创建新记录
            $templateConfig = WebChannelConfig::where('Channel', 100)->first();
            if ($templateConfig) {
                $configArray = $templateConfig->toArray();
                $configArray['Remarks'] = $remark;
                $configArray['Channel'] = $channel;
                $configArray['PackageName'] = $packageName;
                unset($configArray['ID']);
                WebChannelConfig::insert($configArray);
            }
        }

        //同步更新 ChannelPackage
        $channelNumber = DB::connection('write')->table('QPPlatformDB.dbo.ChannelPackageName')
            ->where('Channel', $channel);
        if ($channelNumber->exists()) {
            $channelNumber->update(['Remarks' => $remark]);
        }
        // 同步更新 dcat-admin.channel 表
        $dcatChannel = DB::connection('mysql')->table('dcat-admin.channel')->where('channel', $channel);
        if ($dcatChannel->exists()) {
            $dcatChannel->update(['channel_name' => $remark]);
        } else {
            DB::connection('mysql')->table('dcat-admin.channel')->insert([
                'channel' => $channel,
                'channel_name' => $remark,
                'package_name' => '',
                'remark' => ''
            ]);
        }

        // 同步更新 dcat-admin.channel_ownership 表
        $dcatChannelOwnership = DB::connection('mysql')->table('dcat-admin.channel_ownership')->where('channel', $channel);
        if ($dcatChannelOwnership->exists()) {
            $dcatChannelOwnership->update(['name' => $remark]);
        } else {
            DB::connection('mysql')->table('dcat-admin.channel_ownership')->insert([
                'channel' => $channel,
                'name' => $remark
            ]);
        }

        return apiReturnSuc('备注更新成功');
    }
}
