<?php

namespace App\Http\Controllers\Platform;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Services\UtilService;
use App\Models\User;
use App\Models\UserExtra;
use App\Services\AldGmService;
use Illuminate\Support\Facades\Redis;
use App\Models\AldGift;
use Illuminate\Support\Facades\Log;

class AldUserController extends Controller
{
    public function login(Request $request)
    {
        $rules = [
            "account" => "required",
            "password" => "required|string|min:6",
        ];
        
        $messages = [
            'required' => "请填写完整，缺少参数",
            'account.min' => "账号最少3位",
            'password.min' => '密码最少6位',
        ];
        
        $validator = Validator::make($request->all(), $rules, $messages);
        
        if ($validator->errors()->first()) {
            return $this->jsonReturn(10033, $validator->errors()->first());
        }
        
        $account = $request->input('account');
        $password = $request->input('password');
        
        //是否已同步
        $user = User::findByAccount($account);
        
        if ($user && $user->reg_type != 22) {
            return $this->jsonReturn(1009, "该账号已被其他玩家注册占用");
        }
        
        if (empty($user)) {
            $data = array(
                'account' => $account,
                'pwd'     => md5($password),
                'appid' => 21,
            );
            $data['ip'] = $request->getClientIp();
            $data['sign'] = UtilService::genSafeSign($data,'73*Vet43nDverw#$');
            $res = UtilService::get_http_request('http://adapi.srccwl.com/account_ald/login', $data);
                    
            $ret = json_decode($res,true); 
            if (!isset($ret['ret']) || $ret['ret'] != 0) {
                Log::info("aldzn MG login:" , $data);
                Log::info("aldzn MG login resp:" . $res);
            }
            
            if($ret['ret'] == 0 && !empty($ret['data']['uid'])) {
                //如果手机号已存在
                $mobile = $ret['data']['mobile'];
                if ($mobile) {
                    $mobileBindUser = User::findByMobile($mobile);
                }else {
                    $mobileBindUser = null;
                }               
                if (!empty($mobile) && $mobileBindUser) {
//                     return $this->jsonReturn(1007, "手机账号已被账号" . $mobileBindUser->account ."绑定过");
                    $mobile = '';               
                }
                
                //同步用户数据
                $user = new User();
                $user->account = $ret['data']['username'];
                $user->mobile = $mobile;
                $user->password = md5($password);
                $user->real_name = $ret['data']['realname'] ?? '';
                $user->id_card = $ret['data']['idcard'] ?? '';
                $user->time = $ret['data']['reg_time'];
                $user->reg_type = 22; //MG同步用户
                $user->reg_ip = $ret['data']['cip'];
                $user->nick_name = $ret['data']['nickname'] ?? '';
                $user->device_id = $ret['data']['equip'] ?? '';
                $user->mac = $ret['data']['mac'] ?? '';
                $saveRet = $user->save();
                
                if ($saveRet) {
                    //保存密码强度
                    $userExtra = new UserExtra();
                    $userExtra->uid = $user->uid;
                    $userExtra->password_strength = UserExtra::getPasswordStrength($password);
                    $userExtra->save();                                       
                }else {
                    return $this->jsonReturn(1007, "网络异常，请稍后再试");
                }                
            }else {
                return $this->jsonReturn(1004, $ret['msg']);
            }                      
        }
               
        if (!User::attemptLogin($user->account, $password)) {
            return $this->jsonReturn(1002, "账号或密码错误");
        }
        
        $request->session()->put("uid", $user->uid);
        $request->session()->put("account", $user->account);
        
        return $this->jsonReturn(0, "登陆成功", ['next_url' => route("index")]);
    }

    public function getRoleList(Request $request)
    {
        $uid = $request->session()->get("uid");
        if (empty($uid)) {
            return $this->jsonReturn(1019, "登陆失效或未登陆，请重新登陆");
        }
        
        $userId = $request->input("userId");
        $serverId = $request->input("serverId");
        
        $userExtra = UserExtra::find($uid);
        if (empty($userExtra->aldzn_info)) {
            return $this->jsonReturn(4003, "请您先绑定Orange识别码后再来领取哦~");
        }

        $gmService = new AldGmService();
        $aldzn_info = json_decode($userExtra->aldzn_info, true);
        
        //修补没有serverId的数据
        if (!isset($aldzn_info['serverId']) || empty($aldzn_info['serverId'])) {
            $codeInfo = $gmService->checkBindCode($userExtra->udid);
            if ($codeInfo) {
                $userExtra->aldzn_info = json_encode($codeInfo);
                $userExtra->save();
                $aldzn_info = $codeInfo;
            }
        }
              
        $serverId = $aldzn_info['serverId'];
        $userId = $aldzn_info['userId'];
        $channel = $aldzn_info['channel'];
        
        
        $roleList = $gmService->getRoles($serverId, $userId, $channel);
        if ($roleList === false) {
            return $this->jsonReturn(7001, "网络异常，请稍后再试");
        }
        
        if (empty($roleList)) {
            return $this->jsonReturn(7003, "该账号未找到角色数据");
        }
        
        $roleIdsKey = "user_roleIds:" . $uid;
        Redis::set($roleIdsKey, json_encode($roleList));
        Redis::expire($roleIdsKey, 3600 * 5);
        return $this->jsonReturn(0, "角色列表", $roleList);
    }
    
    public function sendRoleGift(Request $request)
    {
        $uid = $request->session()->get("uid");
        if (empty($uid)) {
            return $this->jsonReturn(1019, "登陆失效或未登陆，请重新登陆");
        }
        
        $aldGift = AldGift::find($uid);
        if (!empty($aldGift)) {
            return $this->jsonReturn(1020, "礼包已发送过");
        }
        
        $roleId = $request->input("roleId");
        $serverId = $request->input("serverId");
        
        if (empty($roleId) || empty($serverId)) {
            return $this->jsonReturn(7002, "参数错误");
        }
               
        $targetRole = [];
        $roleIdsKey = "user_roleIds:" . $uid;
        $roleList = json_decode(Redis::get($roleIdsKey), true);
        
        if (!isset($roleList[$serverId])) {
            return $this->jsonReturn(7003, "请选择正确的服务器");
        }
        
        foreach ($roleList[$serverId]['list'] as $role) {      
            if ($role['roleId'] == $roleId) {
                $targetRole = $role;
                break;
            }          
        }
        if (empty($targetRole)) {
            return $this->jsonReturn(7004, "请刷新重新选择角色");
        }
        
        $gmService = new AldGmService();
        $gmService->sendRoleGift($serverId, $roleId, $targetRole['vipLevel'], $targetRole['channel']);

        $aldGift = new AldGift();
        $aldGift->uid = $uid;
        $aldGift->server_id = $serverId;
        $aldGift->vip_level = $targetRole['vipLevel'];
        $aldGift->channel = $targetRole['channel'];
        $aldGift->role_id = $targetRole['roleId'];
        $aldGift->role_name = $targetRole['roleName'];
        $aldGift->user_id = $targetRole['userId'];
//         $aldGift->user_name = $targetRole['userName'];
        $aldGift->save();
        
        return $this->jsonReturn(0, "请您移步游戏内角色邮箱领取礼包");
    }

    public function bindInfo(Request $request)
    {
        $uid = $request->session()->get("uid");
        if (empty($uid)) {
            return $this->jsonReturn(1019, "登陆失效或未登陆，请重新登陆");
        }

        $userExtra = UserExtra::find($uid);
        if (empty($userExtra->aldzn_info)) {
            return $this->jsonReturn(4003, "暂未绑定识别码");
        }
        $aldznInfo = json_decode($userExtra->aldzn_info, true);
        $aldznInfo['bind_code'] = $userExtra->udid;
        return $this->jsonReturn(0, "绑定信息", $aldznInfo);
    }
}
