<?php
namespace App\Http\Controllers\Card;

use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Throwable;
use Exception;
use Carbon\Carbon;
use Illuminate\Validation\Rule;
use Illuminate\Support\Facades\Redis;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Cache;
use App\Services\AldGmService;
use App\Models\UserExtra;
use App\Models\GameUserPvp;
use App\Models\GameUserPvpCount;
use App\Models\GameUserRoleTime;
use App\Models\BaseItem;
use App\Models\WxUserImg;
use App\Services\UploadServer;

class CardController extends Controller
{
    private $time;

    public function __construct(Request $request)
    {

        $this->time = Carbon::now()->format('Y-m-d H:i:s');
    }

    /**
     * 测试图片上传
     * @date 2021/06/01
     * @author live
     */
    public function getIndexImg()
    {
        $data = [];
        return view('img', $data);
    }
    /**
     * 绑定角色
     * @date 2021/06/01
     * @author live
     */
    public function getVerityLogin($userId)
    {
        $array = ['code'=>200,'msg'=>''];
        if (empty($userId)){
            $array['code'] = 1019;
            $array['msg'] = '登陆失效或未登陆，请重新登陆';
            return $array;
        }

        $userExtra = UserExtra::find($userId);
        if (empty($userExtra->aldzn_info)){
            $array['code'] = 4003;
            $array['msg'] = '请您先绑定Orange识别码后再来绑定角色哦~';
            return $array;
        }

        $aldznInfo = json_decode($userExtra->aldzn_info,true);
        $channel = $aldznInfo['channel'] ?? 0;
        if($channel == ''){
            $array['code'] = 10008;
            $array['msg'] = '很抱歉，非指定平台用户无法参与本次签到活动';
            return $array;
        }

        if (!in_array($channel, config('sign.channel'))){
            $array['code'] = 10008;
            $array['msg'] = '很抱歉，非指定平台用户无法参与本次签到活动';
            return $array;
        }

        return $array;
    }

    /**
     * 绑定角色
     * @date 2021/05/31
     * @author live
     */
    public function getBindAldRole(Request $request)
    {
        $userId = $request->session()->get("uid");
        $result = $this->getVerityLogin($userId);
        if($result['code'] != 200) return $this->jsonReturn($result['code'], $result['msg']);

        $roleId = $request->input('roleId');
        $serverId = $request->input('serverId');
        $serverName = $request->input('serverName');
        if (empty($roleId) || empty($serverId) || empty($serverName)) return $this->jsonReturn(7002, '参数错误');
        $tableName = 'wx_card_role_'.$serverId;
        $this->getCheckRoleInfoTable($tableName);
        $verity = DB::connection('wx_mysql')->table($tableName)->where('uid',$userId)->where('role_id',$roleId)->select('id')->first();
        if($verity) return $this->jsonReturn(0, '角色绑定成功');
        $insert = $this->getInsertRoleInfo($userId,$roleId,$serverId,$serverName,$tableName);
        return $this->jsonReturn(0, '角色绑定成功');
    }

    /**
     * 拉去角色所选取数据
     * @date 2021/06/01
     * @author live
     */
    public function getInsertRoleInfo($userId,$roleId,$serverId,$serverName,$tableName){
        $array = ['code'=>200,'msg'=>''];
        $time = date('Y-m-d H:i:s');

        $targetRole = [];
        $roleIdsKey = "user_roleIds:" . $userId;
        $roleList = json_decode(Redis::get($roleIdsKey), true);

        if (!isset($roleList[$serverId])){
            $array['code'] = 7003;
            $array['msg'] = '请选择正确的服务器';
            return $array;
        }

        foreach ($roleList[$serverId]['list'] as $role) {
            if ($role['roleId'] == $roleId) {
                $targetRole = $role;
                break;
            }
        }
        if (empty($targetRole)){
            $array['code'] = 7004;
            $array['msg'] = '请刷新重新选择角色';
            return $array;
        }
        $duelTotal = 0;
        $duelWin = 0;
        $maxRank = '';

        $win = GameUserPvpCount::where('server_id',$serverId)->where('role_id',$roleId)->select('role_id','total_pvp_num','pvp_win_num')->first();
        if($win){
            $duelTotal = $win->total_pvp_num;
            $duelWin = $win->pvp_win_num;
        }

        $rank = GameUserPvp::where('server_id',$serverId)->where('role_id',$roleId)->select('role_id','level')->first();
        if($rank) $maxRank = $rank->level;
        $gmService = new AldGmService();
        $roleInfo = $gmService->getCPRoleInfo($serverId,$targetRole['userId'],$roleId);
        if(!$roleInfo){
            $array['code'] = 10055;
            $array['msg'] = 'cp返回信息异常';
            return $array;
        }
        $roleScore = $roleInfo['RoleScore'] ?? 0;

        $armsIds = [];
        $armsScore = [];
        $armsStrong = [];
        $armsExciting = [];

        if($roleInfo['TopScoreEquip']['Id'] > 0){
            $armsIds[$roleInfo['TopScoreEquip']['Id']] = $roleInfo['TopScoreEquip']['Id'];
            $armsScore[$roleInfo['TopScoreEquip']['Id']]['id'] = $roleInfo['TopScoreEquip']['Id'];
            $armsScore[$roleInfo['TopScoreEquip']['Id']]['name'] = '';
            if( $roleInfo['TopScoreEquip']['Score'] < 1){
                $armsScore[$roleInfo['TopScoreEquip']['Id']]['score'] = 0;
            }else{
                $armsScore[$roleInfo['TopScoreEquip']['Id']]['score'] = $roleInfo['TopScoreEquip']['Score'];
            }
        }
        if($roleInfo['TopStrengthenEquip']['Id'] > 0){
            $armsIds[$roleInfo['TopStrengthenEquip']['Id']] = $roleInfo['TopStrengthenEquip']['Id'];
            $armsStrong[$roleInfo['TopStrengthenEquip']['Id']]['id'] = $roleInfo['TopStrengthenEquip']['Id'];
            $armsStrong[$roleInfo['TopStrengthenEquip']['Id']]['name'] = '';
            if($roleInfo['TopStrengthenEquip']['Strengthen'] < 1){
                $armsStrong[$roleInfo['TopStrengthenEquip']['Id']]['level'] = 0;
            }else{
                $armsStrong[$roleInfo['TopStrengthenEquip']['Id']]['level'] = $roleInfo['TopStrengthenEquip']['Strengthen'];
            }

        }
        if($roleInfo['TopEnhanceEquip']['Id'] > 0){
            $armsIds[$roleInfo['TopEnhanceEquip']['Id']] = $roleInfo['TopEnhanceEquip']['Id'];
            $armsExciting[$roleInfo['TopEnhanceEquip']['Id']]['id'] = $roleInfo['TopEnhanceEquip']['Id'];
            $armsExciting[$roleInfo['TopEnhanceEquip']['Id']]['name'] = '';
            if($roleInfo['TopEnhanceEquip']['Strengthen'] < 1){
                $armsExciting[$roleInfo['TopEnhanceEquip']['Id']]['level'] = 0;
            }else{
                $armsExciting[$roleInfo['TopEnhanceEquip']['Id']]['level'] = $roleInfo['TopEnhanceEquip']['Strengthen'];
            }

        }

        if(!empty($armsIds)){
            $items = BaseItem::whereIn('item_id',$armsIds)->select('item_id','item_name')->get();
            if (!$items->isEmpty()) {
                foreach($items as $item){
                    if(isset($armsScore[$item->item_id])) $armsScore[$item->item_id]['name'] = $item->item_name;
                    if(isset($armsStrong[$item->item_id])) $armsStrong[$item->item_id]['name'] = $item->item_name;
                    if(isset($armsExciting[$item->item_id])) $armsExciting[$item->item_id]['name'] = $item->item_name;
                }
            }
        }

        $armsScoreArr = '';
        $armsStrongArr = '';
        $armsExcitingArr = '';
        if(!empty($armsScore)) $armsScoreArr = json_encode(array_values($armsScore));
        if(!empty($armsStrong)) $armsStrongArr = json_encode(array_values($armsStrong));
        if(!empty($armsExciting)) $armsExcitingArr = json_encode(array_values($armsExciting));

        $duelContinuityWin = $roleInfo['MaxPkWinStreak'] ?? 0;
        $braveNum = $roleInfo['TowerTopFloor'] ?? 0;
        $braveTime = $roleInfo['TowerUsedTime'] ?? 0;
        $mercenaryScore = $roleInfo['AdventureGrade'] ?? 0;
        if($duelContinuityWin < 1) $duelContinuityWin = 0;
        if($braveNum < 1) $braveNum = 0;
        if($braveTime < 1) $braveTime = 0;
        if($mercenaryScore < 1) $mercenaryScore = 0;

        $array = ['uid'=>$userId,'server_id'=>$serverId,'server_name'=>$serverName,'user_id'=>$targetRole['userId'],'role_id'=>$roleId,'role_name'=>$targetRole['roleName'],'job'=>$targetRole['occupation'],'guild'=>$targetRole['guild'],'online_time'=>$targetRole['onlineTime'],'register_time'=>date('Y-m-d H:i:s',$targetRole['createTime']),'role_score'=>$roleScore,'arms_score'=>$armsScoreArr,'arms_strong'=>$armsStrongArr,'arms_exciting'=>$armsExcitingArr,'duel_total'=>$duelTotal,'duel_win'=>$duelWin,'duel_continuity_win'=>$duelContinuityWin,'max_rank'=>$maxRank,'brave_num'=>$braveNum,'brave_time'=>$braveTime,'mercenary_score'=>$mercenaryScore,'created_at'=>$time,'updated_at'=>$time];
        $result = DB::connection('wx_mysql')->table($tableName)->insert($array);
        if($result) return $array;

        $array['code'] = 10052;
        $array['msg'] = '绑定角色失败';
        return $array;

    }

    /**
     * 一个区服创建一张角色信息表
     * @date 2021/06/01
     * @author live
     */
    public function getCheckRoleInfoTable($tableName)
    {

        if ( ! Schema::connection('wx_mysql')->hasTable($tableName)) {
            Schema::connection('wx_mysql')->create($tableName, function (Blueprint $table) {
                $table->bigIncrements('id')->comment('自增主键');
                $table->integer('uid')->default(0)->comment('用户id');
                $table->integer('server_id')->default(0)->comment('用户id');
                $table->string('server_name',64)->default('')->comment('区服名称');
                $table->integer('user_id')->default(0)->comment('阿拉德用户ID');
                $table->string('role_id',32)->default('')->comment('角色ID');
                $table->string('role_name',32)->default('')->comment('角色名称');
                $table->string('job',32)->default('')->comment('职业');
                $table->string('guild',32)->default('')->comment('工会');
                $table->integer('online_time')->default(0)->comment('在线时长');
                $table->dateTime('register_time')->comment('角色注册时间');
                $table->integer('role_score')->default(0)->comment('角色评分');
                $table->string('arms_score',512)->default('')->comment('武器评分');
                $table->string('arms_strong',512)->default('')->comment('武器强化');
                $table->string('arms_exciting',512)->default('')->comment('武器激化');
                $table->integer('duel_total')->default(0)->comment('角斗场总场数');
                $table->integer('duel_win')->default(0)->comment('角斗场胜场数');
                $table->integer('duel_continuity_win')->default(0)->comment('角斗场连胜场数');
                $table->string('max_rank',32)->default('')->comment('赛季最高段位');
                $table->integer('brave_num')->default(0)->comment('勇者之塔最高层数');
                $table->integer('brave_time')->default(0)->comment('勇者之塔过关时间');
                $table->integer('mercenary_score')->default(0)->comment('佣兵团评分');
                $table->timestamps();
                $table->index(['uid','role_id']);
                $table->engine = 'InnoDB';
            });
        }
        return true;
    }

    /**
     * 用户上传图片
     * @date 2021/06/01
     * @author live
     */
    public function getUploadImg(Request $request)
    {
        $userId = $request->session()->get("uid");
        $result = $this->getVerityLogin($userId);
        if($result['code'] != 200) return $this->jsonReturn($result['code'], $result['msg']);
        $postData = $request->all();
        if($request->hasFile('imgFile') && $request->file('imgFile')->isValid()){
            $file = $request->file('imgFile');
            $upload = new UploadServer();
            $result = $upload->getUpload($postData,$file);
            if($result['code'] != 200) return $this->jsonReturn($result['code'], $result['msg']);
            $img = $this->getUpdateImg($result['data'],$userId);

            if($img) return $this->jsonReturn(0, '上传成功',['src'=>$result['data']]);
            return $this->jsonReturn(10060, '上传失败');
        }
        return $this->jsonReturn(10056, '请选择要上传的图片');
    }

    /**
     * 更新用户上传图片
     * @date 2021/06/01
     * @author live
     */
    public function getUpdateImg($data,$userId)
    {
        $img = WxUserImg::where('uid',$userId)->first();
        if($img){
            $img->loacl_url = $data['url'];
            $img->img_url = $data['yunUrl'];
            $img->status = 0;
            if($img->save()) return true;
        }else{
            $row = new WxUserImg();
            $row->uid = $userId;
            $row->loacl_url = $data['url'];
            $row->img_url = $data['yunUrl'];
            $row->status = 0;
            $row->remark = '';
            if($row->save()) return true;
        }
        return false;
    }

    /**
     * 明信片信息
     * @date 2021/06/02
     * @author live
     */
    public function getCardHtml(Request $request)
    {
        $userId = $request->session()->get("uid");
        $result = $this->getVerityLogin($userId);
        if($result['code'] != 200) return $this->jsonReturn($result['code'], $result['msg']);
        $roleId = $request->input('roleId','3804433377408900301');
        $serverId = $request->input('serverId',269);
        if (empty($roleId) || empty($serverId)) return $this->jsonReturn(7002, '参数错误');
        $info = DB::connection('wx_mysql')->table('wx_card_role_'.$serverId)->where('uid',$userId)->where('role_id',$roleId)->where('server_id',$serverId)->first();
        if(!$info) return redirect(route('cardIndex'));

        $img = WxUserImg::where('uid',$userId)->select('id','img_url','status')->first();
        if($img){
            $data['userImgStatus'] = $img->status;
            $data['userImg'] = $img->img_url;
        }else{
            $data['userImg'] = '';
            $data['userImgStatus'] = -1;
        }

        $armsScore = [];
        $armsStrong = [];
        $armsExciting = [];
        if($info->arms_score != '') $armsScore = json_decode($info->arms_score,true);
        if($info->arms_strong != '') $armsStrong = json_decode($info->arms_strong,true);
        if($info->arms_exciting != '') $armsExciting = json_decode($info->arms_exciting,true);

        $roleScore = '00000';
        if(strlen($info->role_score) == 1) $roleScore = '0000'.(string)$info->role_score;
        if(strlen($info->role_score) == 2) $roleScore = '000'.(string)$info->role_score;
        if(strlen($info->role_score) == 3) $roleScore = '00'.(string)$info->role_score;
        if(strlen($info->role_score) == 4) $roleScore = '0'.(string)$info->role_score;
        if(strlen($info->role_score) == 5) $roleScore = (string)$info->role_score;

        $jobInco = config('sign.jobInco');
        $data['info'] = $info;
        $data['roleScore'] = $roleScore;
        $data['jobImg'] = $jobInco[$info->job] ?? '';

        if($info->mercenary_score > 4999 && $info->mercenary_score < 12000){
            $data['ybImg'] = 'img-B';
        }elseif($info->mercenary_score > 11999 && $info->mercenary_score < 17000){
            $data['ybImg'] = 'img-A';
        }elseif($info->mercenary_score > 16999 && $info->mercenary_score < 20000){
            $data['ybImg'] = 'img-S';
        }elseif($info->mercenary_score > 19999 && $info->mercenary_score < 24000){
            $data['ybImg'] = 'img-SS';
        }elseif($info->mercenary_score > 23999){
            $data['ybImg'] = 'img-SSS';
        }else{
            $data['ybImg'] = 'img-C';
        }

        $data['rank'] = '';
        $rank = explode('-',$info->max_rank);
        if(!empty($rank)) $data['rank'] = $rank[0] ?? '';
        if(!empty($armsScore)){
            $armsScoreNum = '00000';
            if(strlen($armsScore[0]['score']) == 1) $armsScoreNum = '0000'.(string)$armsScore[0]['score'];
            if(strlen($armsScore[0]['score']) == 2) $armsScoreNum = '000'.(string)$armsScore[0]['score'];
            if(strlen($armsScore[0]['score']) == 3) $armsScoreNum = '00'.(string)$armsScore[0]['score'];
            if(strlen($armsScore[0]['score']) == 4) $armsScoreNum = '0'.(string)$armsScore[0]['score'];
            if(strlen($armsScore[0]['score']) == 5) $armsScoreNum = (string)$armsScore[0]['score'];
            $data['armsScoreName'] = $armsScore[0]['name'];
            $data['armsScore'] = $armsScoreNum;
        }else{
            $data['armsScoreName'] = '';
            $data['armsScore'] = '00000';
        }

        if(!empty($armsStrong)){
            $armsStrongNum = '00';
            if(strlen($armsStrong[0]['level']) == 1) $armsStrongNum = '0'.(string)$armsStrong[0]['level'];
            if(strlen($armsStrong[0]['level']) == 2) $armsStrongNum = (string)$armsStrong[0]['level'];
            $data['armsStrongName'] = $armsStrong[0]['name'];
            $data['armsStrong'] = $armsStrongNum;
        }else{
            $data['armsStrongName'] = '';
            $data['armsStrong'] = '00';
        }

        if(!empty($armsExciting)){
            $armsExcitingNum = '00';
            if(strlen($armsExciting[0]['level']) == 1) $armsExcitingNum = '0'.(string)$armsExciting[0]['level'];
            if(strlen($armsExciting[0]['level']) == 2) $armsExcitingNum = (string)$armsExciting[0]['level'];
            $data['armsExcitingName'] = $armsExciting[0]['name'];
            $data['armsExciting'] = $armsExcitingNum;
        }else{
            $data['armsExcitingName'] = '';
            $data['armsExciting'] = '00';
        }

        if($info->brave_time > 0){
            $His = strtotime(date('Y-m-d')) + $info->brave_time;
            if(date('H',$His) > 0){
                $data['braveTime'] = date('H:i',$His);
            }else{
                $data['braveTime'] = date('i:s',$His);
            }
        }else{
            $data['braveTime'] = '00:00';
        }
        return view('card.card', $data);
    }
}