<?php

namespace App\Http\Controllers\Admin;

use App\dao\Pay\AccountPayInfo;
use App\Facade\TableName;
use App\Http\Controllers\Controller;
use App\Http\helper\HttpCurl;
use App\Http\helper\NumConfig;
use App\Http\logic\admin\GlobalLogicController;
use App\Models\AccountsInfo;
use App\Models\AdminScore;
use App\Models\Control;
use App\Models\ControlRecord;
use App\Models\Cpf;
use App\Models\Order;
use App\Models\RecordPlatformData;
use App\Models\Withdrawal;
use App\Services\CreateLog;
use App\Services\Custom;
use App\Services\GameRoomInfo;
use App\Services\GlobalUser;
use App\Services\Paging;
use App\Services\StoredProcedure;
use App\Utility\Helper;
use App\Utility\SetNXLock;
use Illuminate\Http\Request;
use Illuminate\Pagination\Paginator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Log;

class CustomController extends Controller
{


    public function getCallBack(){
        $key = 'get_callback';
        $res = SetNXLock::getExclusiveLock($key, 5);
        if (!$res) {
            return apiReturnFail('操作频繁');
        }
        $admin_id = session('admin')->id;
        $customService = new Custom();

        $unCall = $customService->userCallCount($admin_id,0,0,0);
        if($unCall>300){
            return apiReturnFail('未召回用户>2不分配新账号');
        }

        if($admin_id){
            $count = 30;
            $topUser = $customService->needCallUser(7,30,500);
            $midUser = $customService->needCallUser(7,30,100,499);
            $bottomUser = $customService->needCallUser(7,15,20,99);
            if($topUser){
                $topKey = array_rand($topUser,min(15,count($topUser)));
                if (is_array($topKey)) {
                    foreach ($topKey as $key) {
                        $user = $topUser[$key];
                        $email = $this->_checkCall($user->UserID,$user->PhoneNum);
                        if(!($email === false)){
                            $insert = $user;
                            $insert->Email = $email;
                            $insert->admin_id = $admin_id;
                            $insert->AddDate = date('Y-m-d H:i:s');
                            DB::table(TableName::agent() . 'UserCallBack')->insert(json_decode(json_encode($insert),true));
                            DB::connection('write')->table('QPAccountsDB.dbo.AccountsInfo')->where('UserID', $user->UserID)->update(['Present' => $admin_id]);
                            $count--;
                        }
                    }
                } else {
                    // 如果只选择了一个元素
                    $user = $topUser[$topKey];
                    $email = $this->_checkCall($user->UserID,$user->PhoneNum);
                    if(!($email === false)){
                        $insert = $user;
                        $insert->Email = $email;
                        $insert->admin_id = $admin_id;
                        $insert->AddDate = date('Y-m-d H:i:s');
                        DB::table(TableName::agent() . 'UserCallBack')->insert(json_decode(json_encode($insert),true));
                        DB::connection('write')->table('QPAccountsDB.dbo.AccountsInfo')->where('UserID', $user->UserID)->update(['Present' => $admin_id]);
                        $count--;
                    }
                }
            }

            if($midUser){
//                $topKey = array_rand($midUser,10);

                $topKey = array_rand($midUser,min(10,count($midUser)));
                if (is_array($topKey)) {
                    foreach ($topKey as $key) {
                        $user = $midUser[$key];
                        $email = $this->_checkCall($user->UserID,$user->PhoneNum);
                        if(!($email === false)){
                            $insert = $user;
                            $insert->Email = $email;
                            $insert->admin_id = $admin_id;
                            $insert->AddDate = date('Y-m-d H:i:s');
                            DB::table(TableName::agent() . 'UserCallBack')->insert(json_decode(json_encode($insert),true));
                            DB::connection('write')->table('QPAccountsDB.dbo.AccountsInfo')->where('UserID', $user->UserID)->update(['Present' => $admin_id]);
                            $count--;
                        }
                    }
                } else {
                    // 如果只选择了一个元素
                    $user = $midUser[$topKey];
                    $email = $this->_checkCall($user->UserID,$user->PhoneNum);
                    if(!($email === false)){
                        $insert = $user;
                        $insert->Email = $email;
                        $insert->admin_id = $admin_id;
                        $insert->AddDate = date('Y-m-d H:i:s');

                        DB::table(TableName::agent() . 'UserCallBack')->insert(json_decode(json_encode($insert),true));
                        DB::connection('write')->table('QPAccountsDB.dbo.AccountsInfo')->where('UserID', $user->UserID)->update(['Present' => $admin_id]);
                        $count--;
                    }
                }
            }

            if($bottomUser && $count){
                $topKey = array_rand($bottomUser,min($count,count($bottomUser)));
                if (is_array($topKey)) {
                    foreach ($topKey as $key) {
                        $user = $bottomUser[$key];
                        $email = $this->_checkCall($user->UserID,$user->PhoneNum);
                        if(!($email === false)){
                            $insert = $user;
                            $insert->Email = $email;
                            $insert->admin_id = $admin_id;
                            $insert->AddDate = date('Y-m-d H:i:s');
                            DB::table(TableName::agent() . 'UserCallBack')->insert(json_decode(json_encode($insert),true));
                            DB::connection('write')->table('QPAccountsDB.dbo.AccountsInfo')->where('UserID', $user->UserID)->update(['Present' => $admin_id]);
                        }
                    }
                } else {
                    // 如果只选择了一个元素
                    $user = $bottomUser[$topKey];
                    $email = $this->_checkCall($user->UserID,$user->PhoneNum);
                    if(!($email === false)){
                        $insert = $user;
                        $insert->Email = $email;
                        $insert->admin_id = $admin_id;
                        $insert->AddDate = date('Y-m-d H:i:s');
                        DB::table(TableName::agent() . 'UserCallBack')->insert(json_decode(json_encode($insert),true));
                        DB::connection('write')->table('QPAccountsDB.dbo.AccountsInfo')->where('UserID', $user->UserID)->update(['Present' => $admin_id]);
                    }
                }
            }
        }
        SetNXLock::release($key);
        return apiReturnSuc();
    }

    private function _checkCall($UserID,$phone){
        if(!$phone){
            return false;
        }else{




            //get email
            $AccountWithDrawInfo = DB::table(TableName::QPAccountsDB() . 'AccountWithDrawInfo')
                ->lock('WITH(NOLOCK)')
                ->where('UserID', $UserID)
                ->first();
            if($AccountWithDrawInfo){
                $email = $AccountWithDrawInfo->EmailAddress;
            }else{
                $email = '';
            }

            if($email){
                //check other phone account

                $otherPhoneAccount = DB::connection('read')->table(TableName::QPAccountsDB() . 'AccountsInfo as ai')
                    ->where('ai.IsAndroid', 0)
                    ->join(TableName::QPAccountsDB() . 'AccountPhone as ap', 'ai.UserID', 'ap.UserID')
                    ->where('ap.PhoneNum', $phone)
                    ->where('ai.LastLogonDate','>', date('Y-m-d H:i:s',strtotime("-7 days")))
                    ->count();
                if($otherPhoneAccount){
                    Log::info('【用户召回去重】' .$otherPhoneAccount.'-'.$phone);
                    return false;
                }
            }

            return $email;
        }
    }



    //用户列表
    public function userListNew(Request $request)
    {
        $gameID = (int)$request->GameID ?: "";
        $startTime = str_replace('T', ' ', $request->start_time ?? "");
        $endTime = str_replace('T', ' ', $request->end_time ?? "");

        $lstartTime = str_replace('T', ' ', $request->lstart_time ?? "");
        $lendTime = str_replace('T', ' ', $request->lend_time ?? "");

        $cstartTime = str_replace('T', ' ', $request->cstart_time ?? "");
        $cendTime = str_replace('T', ' ', $request->cend_time ?? "");

        $state = isset($request->state)?($request->state):-1;

        $admin_id = session('admin')->id;

        $list = (new Custom())->userNewList($admin_id, $gameID,$cstartTime, $cendTime,$startTime, $endTime, $lstartTime, $lendTime,$state);

        $callState = ['-1' =>'全部',0 => '等待召回', 1 => '已召回待激活', 2 => '激活'];

        $prize = 20;
        $prizeA = 50;

        $lastLogin = (new Custom())->userCallCount($admin_id,date('Y-m-01', strtotime('first day of last month')).' 00:00:00',date('Y-m-t', strtotime('last day of last month')).' 23:59:59',1);
        $lastActive = (new Custom())->userCallCount($admin_id,date('Y-m-01', strtotime('first day of last month')).' 00:00:00',date('Y-m-t', strtotime('last day of last month')).' 23:59:59',2);
        $lastPrize = $lastActive*$prizeA+$lastLogin*$prize;

        $currentLogin = (new Custom())->userCallCount($admin_id,date('Y-m-01').' 00:00:00',date('Y-m-t').' 23:59:59',1);
        $currentActive = (new Custom())->userCallCount($admin_id,date('Y-m-01').' 00:00:00',date('Y-m-t').' 23:59:59',2);

        $currentPrize = $currentActive*$prizeA+$currentLogin*$prize;

        foreach ($list as &$item){
            $item->mailStatus =  (new Custom())->checkSend($item->UserID)?1:0;
        }

        return view('admin.custom.usernew', compact('list', 'gameID','cstartTime', 'cendTime','startTime', 'endTime','lstartTime','lendTime','callState','state','prize','lastPrize','currentPrize','prizeA'));

    }


    //用户列表
    public function userListAll(Request $request)
    {
        $gameID = (int)$request->GameID ?: "";
        $startTime = str_replace('T', ' ', $request->start_time ?? "");
        $endTime = str_replace('T', ' ', $request->end_time ?? "");

        $lstartTime = str_replace('T', ' ', $request->lstart_time ?? "");
        $lendTime = str_replace('T', ' ', $request->lend_time ?? "");

        $cstartTime = str_replace('T', ' ', $request->cstart_time ?? "");
        $cendTime = str_replace('T', ' ', $request->cend_time ?? "");

        $state = isset($request->state)?($request->state):-1;

        $admin_id = (int)$request->admin_id ?: "";;

        $list = (new Custom())->userNewList($admin_id, $gameID,$cstartTime, $cendTime,$startTime, $endTime, $lstartTime, $lendTime,$state);

        $callState = ['-1' =>'全部',0 => '等待召回', 1 => '已召回待激活', 2 => '激活'];

        $prize = 20;
        $prizeA = 50;


        $currentActive = (new Custom())->userCallCount($admin_id,$cstartTime,$cendTime);

        $currentLogin = (new Custom())->userCallCount($admin_id,$cstartTime,$cendTime,1);

        $currentPrize = $currentActive*$prizeA+$currentLogin*$prize;

        $adminName = DB::connection('write')->table('agent.dbo.admin_users')
            ->pluck('nickname', 'id')->toArray();

        $profit = (new Custom())->userCallProfit($admin_id,$cstartTime,$cendTime);
        $currentPay = $profit->total_recharge;
        $currentWithdraw = $profit->total_withdraw;
//        foreach ($list as $nItem){
//            if($nItem->call_state == 2){
//                $where = [];
//                $where[] = ['UserID',$nItem->UserID];
//                $where[] = ['pay_at', '>=', date('Y-m-d H:i:s', strtotime($nItem->CallbackDate))];
//
//                $payTotalMoney = DB::connection('write')->table('agent.dbo.order')
//                    ->where($where)->selectRaw('sum(amount) as amount')->first();
//
//                $totalMoney = isset($payTotalMoney->amount) ? number_float($payTotalMoney->amount / NumConfig::NUM_VALUE) : 0;
//
//                $nItem->pay = $totalMoney;
//                $currentPay+=$totalMoney;
//            } else{
//                $nItem->pay = 0;
//            }
//        }

        return view('admin.custom.userall', compact('list', 'gameID','cstartTime', 'cendTime','startTime', 'endTime','lstartTime','lendTime','callState','state','prize','adminName','currentPrize' ,'admin_id','prizeA','currentPay','currentWithdraw'));

    }


    public function follow($id){

        $list = DB::connection('read')->table(TableName::agent() . 'CallFollow')
            ->where('UserID', $id)
            ->select('UserID', 'f_type', 'admin_id', 'f_content', 'created')
            ->orderBy('ID','DESC')
            ->take(30)->get()->toArray();


//        <option value="1">what's app</option>
//        <option value="2">Email</option>
//        <option value="3">短信</option>
//        <option value="4">Telegram</option>
//        <option value="5">电话</option>

        $followType = [
            1 => "What's App",
            2 => "Email",
            3 => "短信",
            4 => "Telegram",
            5 => "电话",
        ];

        $adminName = DB::connection('write')->table('agent.dbo.admin_users')
            ->pluck('nickname', 'id')->toArray();


        foreach ($list as &$val) {

            $val->admin  = isset($adminName[$val->admin_id]) ? $adminName[$val->admin_id] : $val->admin_id;
        }

        //isset($adminName[$val->admin_id]) ? $adminName[$val->admin_id] : '';


        return view('admin.custom.list', compact('list', 'id','followType','adminName'));

    }

    public function followAdd(Request $request){
        $admin_id = session('admin')->id;
        $follow = [
            'UserID' => $request->UserID,
            'admin_id' => $admin_id,
            'f_type' => $request->f_type,
            'f_content' => $request->f_content,
            'created' => time()
        ];

        DB::table(TableName::agent() . 'CallFollow')->insert($follow);

        return redirect('/admin/custom/follow/'.$request->UserID);
    }

    public function sendCallbackMail($UserID){

        $key = 'mail_callback_'.$UserID;

        $res = SetNXLock::getExclusiveLock($key, 5);
        if (!$res) {
            return apiReturnFail('操作频繁');
        }

        $mailCheck = (new Custom())->checkSend($UserID);
        if($mailCheck){
            return apiReturnFail('请勿重复发送');
        }

        $total = (new AccountsInfo())->accountTotalStatistics([$UserID]);
        $recharge =  @$total[0]->Recharge ??  0;

        $withdraw =  @$total[0]->Withdraw ?? 0;


        $bonus = intval(($recharge*100-$withdraw)*0.1);
        if($bonus<2000){
            $bonus = 20*100;
        }

        if($bonus>50000){
            $bonus = 500*100;
        }


        $data = [
            'MailType' => 2,
            'MailStatus' => 1,
            'UserID' => $UserID,
            'CreateTime' => date('Y-m-d H:i:s', time()),
            'TitleString' => 'Prêmio de feedback Super VIP',
            'TextString' => 'Caro jogador,

Feliz Ano Novo! Gostaríamos de agradecer o seu apoio ao nosso jogo de cassino. Você foi sorteado para receber um reembolso especial! Você receberá uma certa quantidade de moedas de ouro para que possa desfrutar de mais diversão e emoção no jogo.

Desejamos-lhe um Feliz Ano Novo e muita diversão no jogo!

Atenciosamente',
            'BonusString' => '30000,'.$bonus,
            'FromAgentID' => session('admin')->id,
            'type' => 3,
            'amount' => $bonus,
            'admin_type' => 1
        ];


        DB::table('QPAccountsDB.dbo.PrivateMail')->insert($data);

        return apiReturnSuc();

    }



}
