<?php

namespace App\Http\Controllers\Platform;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Validator;
use App\Models\AldGift;
use App\Models\User;
use App\Models\UserExtra;
use App\Services\RealnameAuthService;
use Illuminate\Support\Facades\Log;
use App\Services\UtilService;
use App\Services\AldGmService;
use Illuminate\Support\Facades\Artisan;
use App\Aldzn\UserRefund;

class UserController extends Controller
{
    
    public function login(Request $request) 
    {
        $expire = 300;
        
        $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());
        }
        
        $blockIPKey = "block:" . $request->getClientIp();
        
        $ipErrorNum = Cache::get($blockIPKey, 0);
        
        if ($ipErrorNum >= 5) {
            $this->jsonReturn(1009, "短时间内错误太多，请稍后再试");
        }
        
        $account = trim($request->input("account"));
        $password = $request->input("password");
        $user = User::findByAccount($account);

        if (empty($user)) { //用户不存在
            if (UtilService::isPhoneNum($account)) {
                $user = User::findByMobile($account);
                if (empty($user)) {
                    return $this->jsonReturn(1101, "账号不存在");
                }
            }else {
                return $this->jsonReturn(1001, "账号不存在");
            }
        }
        
        if ($user->attemptLogin($user->account, $password)) { //成功登陆
            $request->session()->put("uid", $user->uid);
            $request->session()->put("account", $user->account);
            return $this->jsonReturn(0, "登陆成功", ['next_url' => route("index")]);
        }     
        Cache::put($blockIPKey, $ipErrorNum+1, $expire);       
        //登陆失败
        return $this->jsonReturn(1002, "账号或密码错误");
    }
    
    //短信验证码登录
    public function mobileLogin(Request $request) {
        $rules = [
            'phone' => 'required|min:11|string',
            'auth_code' => 'required',
        ];
        $messages = [
            'phone.min' => '手机号码最少11位',
            'required' => "请填写完整，缺少参数",
        ];
        $validator = Validator::make($request->all(), $rules, $messages);
        if ($validator->errors()->first()) {
            return $this->jsonReturn(10033, $validator->errors()->first());
        }
        
        $mobile = $request->input("phone");
        $srvAuthCode = Cache::get("sms_auth_code:" . $mobile);
        
        if ($request->input("auth_code") != $srvAuthCode) { //验证码错误
            return $this->jsonReturn(1003, "验证码错误");
        }
        
        $user = User::findByMobile($mobile);
        if (empty($user)) {
            return $this->jsonReturn(1004, "该手机未绑定任何账号");
        }
        
        $request->session()->put("uid", $user->uid);
        $request->session()->put("account", $user->account);
        return $this->jsonReturn(0, "登陆成功", ['next_url' => route("index")]);
    }
    
    
    public function logout(Request $request)
    {
        $request->session()->invalidate();
        
        $request->session()->regenerateToken();
        return redirect("/");
    }
    
    public function register(Request $request)
    {
        $messages = [
            'phone.min' => '手机号码最少11位', 
            'required' => "请填写完整，缺少参数",
            'password.min' => '密码最少6位',
//             'id_card.min' => '身份证最少16位', 
        ];
        $rules = [
            'phone' => 'required|min:11|string',
            'password' => 'required|string|min:6',
//             'real_name' => 'required|string',
//             'id_card' => 'required|string|min:16',
            'auth_code' => 'required',
        ];

        $validator = Validator::make($request->all(), $rules, $messages);
        
        if ($validator->errors()->first()) {
            return $this->jsonReturn(10033, $validator->errors()->first());
        }
               
        $mobile = $request->input("phone");
        $srvAuthCode = Cache::get("sms_auth_code:" . $mobile);

        if ($request->input("auth_code") != $srvAuthCode) { //验证码错误
            return $this->jsonReturn(1003, "验证码错误");
        }
                     
        $user = User::findByMobile($mobile);

        if (!empty($user)) {
            return $this->jsonReturn(11008, "手机号已绑定过账号");
        }
        
        $user = User::findByAccount($mobile);
        if (!empty($user)) {
            return $this->jsonReturn(11009, "手机号已被注册过");
        }

        $originPassword = $request->input("password");
        
        if ($mobile == $originPassword) {
            return $this->jsonReturn(12001, "密码不可以是手机号");
        }
        
//         $realName = trim($request->input('real_name'));
//         $idCard = trim($request->input("id_card"));

//         $realnameAuthService = new RealnameAuthService();
//         $result = $realnameAuthService->check("用户中心", $realName, $idCard, $mobile, $this->getClientRealIP());
//         if (!$result[0]) {
//             Log::error("实名验证错误", $result);
//             return $this->jsonReturn(30002, "实名信息不匹配");
//         }            
        
        $user = new User();
        $user->account = $mobile;
        $user->mobile = $mobile;
        $user->password = md5($originPassword);
//         $user->real_name = $realName;
//         $user->id_card = $idCard;
        $user->time = time();
        $user->reg_type = 21;
        $user->reg_ip = $request->getClientIp();
        $ret = $user->save();
        
        if ($ret) {
            //保存密码强度
            $userExtra = new UserExtra();
            $userExtra->uid = $user->uid;
            $userExtra->password_strength = UserExtra::getPasswordStrength($originPassword);
            $userExtra->save();
            
            $request->session()->put("uid", $user->uid);
            $request->session()->put("account", $user->account);
            return $this->jsonReturn(0, "注册成功", ['next_url' => route("index")]);
        }else {
            return $this->jsonReturn(1007, "注册失败");
        }
    }

    public function bindALD(Request $request)
    {
        $request->validate([
            'bind_code' => 'required',
        ]);
        $uid = $request->session()->get("uid");
        if (empty($uid)) {
            return $this->jsonReturn(1019, "登陆失效或未登陆，请重新登陆");
        }
        
        $limitErrorTimesPerDay = 3;
        $errTimesKey = "bind_code_errtimes:" . date("Ymd") . ":" . $uid;
        $expire = 3600 * 24;
        $errTimes = Cache::get($errTimesKey, 0);
        
        if ($errTimes >= $limitErrorTimesPerDay) {
            return $this->jsonReturn(1020, "每日限额错误次数", ['left_times' => 0, 'total_times' => $limitErrorTimesPerDay ]);
        }
        
        $bindCode = trim($request->input("bind_code"));
        
        $aldznUser = UserExtra::find($uid);
        if (!empty($aldznUser) && !empty($aldznUser->udid)) {
            Cache::put($errTimesKey, $errTimes+1, $expire);
            return $this->jsonReturn(1015, "该账号已绑定过");
        }
        
        $bindUser = UserExtra::findByUdid($bindCode);
        if ($bindUser) {
            Cache::put($errTimesKey, $errTimes+1, $expire);
            return $this->jsonReturn(1016, "该Orange识别码已被绑定");
        }
        
        if (empty($aldznUser)) {
            $aldznUser = new UserExtra();
        }
        
        $gmService = new AldGmService();
        $codeInfo = $gmService->checkBindCode($bindCode);
        if (!$codeInfo) {
           Cache::put($errTimesKey, $errTimes+1, $expire);
           return $this->jsonReturn(1017, "该Orange识别码不存在请重新输入");
        }
        $channel = $codeInfo['channel'] ?? '';
        $ouid = $codeInfo['userId'] ?? '';
//        if (!empty($channel) && !empty($ouid) && $channel != "mg") {
//            //Artisan::call("search:refund", ['channel' => $channel, 'ouid' => $ouid]);
//            //$oCoin = UserRefund::where('channel_id', $codeInfo['channel'])
//                ->where("ouid", $codeInfo['userId'])
//                ->value('o_coin');
//            //$aldznUser->o_coin = intval($oCoin);
//            //$aldznUser->is_refund = 1;
//        }
        
        $aldznUser->uid = $uid;
        $aldznUser->udid = $bindCode;
        $aldznUser->aldzn_info = json_encode($codeInfo);
               
        $ret = $aldznUser->save();
        if ($ret) {
            $gmService->confirmBind($bindCode, $codeInfo);
            return $this->jsonReturn(0, "绑定成功", ['bind_code' => $bindCode] + $codeInfo);
        }else {
            return $this->jsonReturn(1013, "绑定失败");
        }
    }
    

    
}
