<?php


namespace App\Http\Controllers\Game;


use App\Game\AgentBonusRecord;
use App\Game\AgentCommission;
use App\Game\AgentLinks;
use App\Game\AgentLinksClickLog;
use App\Game\AgentUser;
use App\Game\AgentUserRecord;
use App\Game\GlobalUserInfo;
use App\Game\Services\AgentService;
use App\Game\Services\OuroGameService;
use App\Http\helper\NumConfig;
use App\Models\AccountsInfo;
use App\Models\Treasure\GameScoreInfo;
use App\Services\ExtensionCopy;
use App\Services\Extensions;
use App\Util;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;

// 裂变入口
// 数值统一要除 100
class AgentSystemController
{
    public function ClickScore(Request $request)
    {
        Util::WriteLog("click", $request->all());
        $code = $request->input('code');
        if ($code) {
            $link = AgentLinks::getByCode($code);
            if ($link) {
                $link->increment('ClickNum', 1);
                if ($request->has('add')) {
                    $add = json_decode($request->input('add')??"{'country':'','city':''}");
                    if ($add) {
                        AgentLinksClickLog::create([
                            'LinkID'  => $link->LinkID,
                            'Country' => $add->country??"",
                            'City'    => $add->city??"",
                        ]);
                    }

                }
            }
        }

    }

    /**
     * /api/extension/getScore?UserID=2111
     * 获取裂变 可领额度
     * @param Request $request
     * @return array
     */
    public function getScore(Request $request)
    {
        $data['levels']=AgentCommission::getCommissionData();

        $user = LoginController::checkLogin($request);

        if(!$user)return apiReturnSuc($data);

        $UserID =  $user->UserID;


        // 用户余额
//        $data['Score'] = GameScoreInfo::where('UserID', $UserID)
//            ->value('Score');

        $agentUser=AgentUser::query()->where('UserID', $UserID)->first();
        if(!$agentUser){
            $agentUser=AgentService::SetUserAgent($user->GlobalUID, $UserID);
        }
        extract($agentUser->toArray());

        //我的全部业绩
        $SubTotal=AgentUserRecord::query()
            ->where('UserID', $UserID)
//            ->where('HigherID',0)
            ->where('Date',Carbon::now()->format('Ymd'))
            ->sum('SubTotal');

        $data['info']=compact('SubTotal','downCount1', 'downCount2', 'downCount3', 'downCount4');
        //合并了level和rate
        $data['info']=array_merge($data['info'],AgentCommission::getLevelAndRate($SubTotal/NumConfig::NUM_VALUE));



        $data['subs']=AgentUserRecord::query()
            ->leftJoin("webgame.GlobalUserInfo as gi","gi.UserID","=","webgame.AgentUserRecord.UserID")
            ->where('HigherID', $UserID)->where('Date',Carbon::now()->format('Ymd'))
            ->select('NickName','FaceID','SubTotal')->get()->toArray();

        $subBonus=0;
//        dd($data['subs']);
        $data['subs']=array_map(function ($item) use (&$subBonus){
            $item=(object)$item;
            $item->img = GlobalUserInfo::faceidToAvatar($item->FaceID);
            $lr=AgentCommission::getLevelAndRate($item->SubTotal/NumConfig::NUM_VALUE);
            $item->level=$lr['level'];
            $item->rate=$lr['rate'];
            $item->bonus=$item->SubTotal*$item->rate;
            $subBonus+=$item->bonus;
            return $item;
        },$data['subs']);

        $data['info']['sub_bonus']=$subBonus;
        $data['info']['org_bonus']=$SubTotal*$data['info']['rate'];
        $data['info']['bonus']=$data['info']['org_bonus']-$subBonus;
        $data['history']=AgentBonusRecord::where('UserID', $UserID)
            ->where('status',AgentBonusRecord::STATUS_INIT)
            ->get()->toArray();
        $data['link']=AgentService::getShareLink($user->GlobalUID);
        return apiReturnSuc($data);
    }


    /**
     * 领取额度
     * @param Request $request
     * @return array
     */
    public function receiveScore(Request $request)
    {
        $user = $request->user();
        $UserID=$user->UserID;
        $ID=$request->input('ID');
        $record=AgentBonusRecord::where('ID',$ID)->first();
        if($record->GlobalUID!=$user->GlobalUID)return apiReturnFail(['web.agent.fail_wrong_id','Incorrect records ID']);
        if($record->status!=AgentBonusRecord::STATUS_INIT)return apiReturnFail(['web.agent.fail_wrong_status','Already received']);
        $record->update(['status'=>AgentBonusRecord::STATUS_GET]);
        OuroGameService::AddScore($UserID,$record->bonus,OuroGameService::REASON_AgentBonus);
        OuroGameService::AddDrawBase($UserID,$record->bonus,OuroGameService::REASON_AgentBonus);


        return apiReturnSuc($record->toArray());
    }
    public function statLastDayMoney(Request $request)
    {

        $recount=$request->input('recount')??0;
        $Date=Carbon::yesterday()->format('Ymd');
        if(!$recount&&AgentBonusRecord::where('Date',$Date)->exists()){
            return "EXISTS";
        }
        $uids=AgentUserRecord::where('Date',$Date)
            ->select('UserID','GlobalUID')
            ->distinct()->get()
            ->toArray();
//        dd($uids);
        foreach ($uids as &$data) {
            $UserID=$data['UserID'];
            //我的全部业绩
            $SubTotal = AgentUserRecord::query()
                ->where('UserID', $UserID)
//                ->where('HigherID', 0)
                ->where('Date', $Date)
                ->sum('SubTotal');

            //合并了level和rate
            $data=array_merge($data,AgentCommission::getLevelAndRate($SubTotal / NumConfig::NUM_VALUE));


            $subs = AgentUserRecord::query()
                ->where('HigherID', $UserID)
                ->where('Date', Carbon::yesterday()->format('Ymd'))
                ->select('UserID','SubTotal')->get()->toArray();

            $subBonus = 0;
            foreach ($subs as &$item) {
                $lr = AgentCommission::getLevelAndRate($item['SubTotal'] / NumConfig::NUM_VALUE);
                $item['level'] = $lr['level'];
                $item['rate'] = $lr['rate'];
                $item['bonus'] = $item['SubTotal'] * $item['rate'];
                $subBonus += $item['bonus'];
            }

            $data['SubTotal'] = $SubTotal;
            $data['sub_bonus'] = $subBonus;
            $data['org_bonus'] = $SubTotal * $data['rate'];
            $data['bonus'] = $data['org_bonus'] - $subBonus;
            $data['status'] = AgentBonusRecord::STATUS_INIT;
            $data['Date'] = $Date;

            if($data['bonus']>0)AgentBonusRecord::create($data);
        }
        dd($uids);
    }
    // 获取用户领取记录
    public function history(Request $request)
    {
        $user = $request->user();
        $UserID=$user->UserID;
        $data['history']=AgentBonusRecord::where('UserID', $UserID)
            ->where('status',AgentBonusRecord::STATUS_GET)
            ->get()->toArray();
        return apiReturnSuc($data);
    }

    // 充值比率
    public function rechargeRate()
    {
        $AgentRebateRatio = DB::connection('write')->table('QPAccountsDB.dbo.SystemStatusInfo')
            ->where('StatusName', 'AgentRebateRatio1')
            ->orWhere('StatusName', 'AgentRebateRatio2')
            ->select('StatusName', 'StatusValue')
            ->pluck('StatusValue', 'StatusName');

        return apiReturnSuc($AgentRebateRatio);
    }


}
