<?php


namespace App\Services;


use App\Facade\Redis;
use App\Facade\TableName;
use App\Http\helper\HttpCurl;
use App\Http\helper\NumConfig;
use App\Http\logic\admin\GlobalLogicController;
use App\Http\logic\api\BaseApiLogic;
use App\Models\AccountsInfo;
use App\Models\Control;
use App\Models\Order;
use App\Models\RecordPlatformData;
use App\Models\Withdrawal;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class Custom extends BaseApiLogic
{

    public function needCallUser($lastDay=7,$limit=5, $minRecharge='', $maxRecharge='')
    {
        $field = ['ai.GameID','ai.UserID', 'ai.NickName','ai.LastLogonDate', 'ai.RegisterDate', 'ap.PhoneNum'];
        $Sql = DB::connection('read')->table(TableName::QPAccountsDB() . 'AccountsInfo as ai')
            ->leftJoin(TableName::QPTreasureDB() . 'GameScoreInfo as gi', 'ai.UserID', 'gi.UserID')
            ->leftJoin(TableName::QPAccountsDB() . 'AccountPhone as ap', 'ai.UserID', 'ap.UserID')
            ->leftJoin(TableName::QPRecordDB().'RecordUserTotalStatistics as rut','ai.UserID', 'rut.UserID')
            ->select($field);
        $where = [];
        $where[] = ['ai.Present','=',0];

        if (!empty($lastDay))
            $where[] = ['ai.LastLogonDate', '<=', date('Y-m-d H:i:s',strtotime("-{$lastDay} days"))];


        if (!empty($minRecharge))
            $where[] = ['rut.Recharge', '>=', $minRecharge];
        if (!empty($maxRecharge))
            $where[] = ['rut.Recharge', '<=', $maxRecharge];

        $orderBy = 'ai.LastLogonDate desc';

        $list = $Sql->where($where)->orderByRaw($orderBy)->take($limit)->get()->toArray();
        return $list;
    }


    public function myCallUser($lastDay=7,$state=-1,$admin=0){

    }

    public function userNewList($admin_id,$gameID,$cstartTime, $cendTime, $startTime, $endTime, $lstartTime, $lendTime,$state)
    {
        $field = ['ai.GameID','ai.Channel','ai.UserID', 'ai.NickName','gi.Score', 'ai.LastLogonDate','ub.call_state','ub.Email','ub.CallbackDate','ub.AddDate', 'ai.RegisterDate',  'ub.PhoneNum','ub.recharge','ub.withdraw','admin_id'];
        $Sql = DB::connection('read')->table('agent.dbo.UserCallBack as ub')
            ->leftJoin(TableName::QPAccountsDB() . 'AccountsInfo as ai','ai.UserID', 'ub.UserID')
            ->leftJoin(TableName::QPTreasureDB() . 'GameScoreInfo as gi', 'ub.UserID', 'gi.UserID')
            ->leftJoin(TableName::QPRecordDB().'RecordUserTotalStatistics as rut','ub.UserID', 'rut.UserID')
            ->select($field);


//        return DB::connection('read')->table('QPRecordDB.dbo.RecordUserTotalStatistics')
//            ->selectRaw('Recharge,Withdraw,Handsel,(WinScore + LostScore) Score,ServiceFee,UserID,Revenue')
//            ->whereIn('UserID', $UserIDs)
//            ->get();


        $where = [];

        if ($admin_id)
            $where[] = ['admin_id', $admin_id];

        if ($state!=-1)
            $where[] = ['call_state', $state];

        if (!empty($gameID))
            $where[] = ['ai.GameID', $gameID];


        if (!empty($startTime))
            $where[] = ['ub.CallbackDate', '>=', $startTime];
        if (!empty($endTime))
            $where[] = ['ub.CallbackDate', '<=', $endTime];


        if (!empty($cstartTime))
            $where[] = ['ub.AddDate', '>=', $cstartTime];
        if (!empty($cendTime))
            $where[] = ['ub.AddDate', '<=', $cendTime];



        if (!empty($lstartTime))
            $where[] = ['ai.LastLogonDate', '>=', $lstartTime];
        if (!empty($lendTime))
            $where[] = ['ai.LastLogonDate', '<=', $lendTime];


        $orderBy = 'AddDate desc';

        $list = $Sql->where($where)->orderByRaw($orderBy)->paginate(10);

        foreach ($list as &$value) {
            $value->Score = $value->Score / NumConfig::NUM_VALUE;
        }
        return $list;
    }


    public function userCallCount($admin_id,$start,$end,$state=2)
    {
        $Sql = DB::connection('read')->table('agent.dbo.UserCallBack');

        $where = [];

        $where[] = ['call_state', $state];

        if($admin_id){
            $where[] = ['admin_id', $admin_id];
        }

        if ($start)
            $where[] = ['AddDate', '>=', $start];
        if ($end)
            $where[] = ['AddDate', '<=', $end];

        return $Sql->where($where)->count();
    }


    public function userCallProfit($admin_id,$start,$end)
    {
        $Sql = DB::connection('read')->table('agent.dbo.UserCallBack');

        $where = [];


        if($admin_id){
            $where[] = ['admin_id', $admin_id];
        }

        if ($start)
            $where[] = ['AddDate', '>=', $start];
        if ($end)
            $where[] = ['AddDate', '<=', $end];

        return $Sql->where($where)->selectRaw('sum(recharge) as total_recharge,sum(withdraw) as total_withdraw')
            ->first();
    }


    public function checkSend($UserID){

        $mail = DB::connection('read')->table(TableName::QPAccountsDB() . 'PrivateMail')
            ->where('UserID', $UserID)
            //->where('MailStatus', 1)
            ->where('admin_type', 1)
            ->first();
        return $mail?1:0;
    }


    public function clearUnBackUser(){
        $data = DB::connection('write')->table('agent.dbo.UserCallBack')
            ->where('call_state',0)
            ->where('AddDate','<=', date('Y-m-d H:i:s',time()-86400*2))
            //->select('ServerName', 'UserID')
            ->pluck('UserID', 'UserID')->toArray();

        $userId = [];
        if($data){
            $userId = array_values($data);
        }
        if($userId){
            //删除 分配记录
            DB::connection('write')->table('agent.dbo.UserCallBack')
                ->where('call_state',0)
                ->whereIn('UserID',$userId)
                ->delete();

            // 删除标记
            DB::connection('write')->table(TableName::QPAccountsDB() . 'AccountsInfo')
                ->whereIn('UserID',$userId)
                ->update(['Present' => 0]);

            DB::connection('write')->table(TableName::QPAccountsDB() . 'PrivateMail')
                ->whereIn('UserID',$userId)
                ->where('admin_type', 1)
                ->delete();
        }

        Log::info('【用户召回清理】' .count($userId));
        //return count($userId);

        //TODO 明天开启


        $activeLost = DB::connection('read')->table(TableName::QPAccountsDB() . 'AccountsInfo as ai')
            ->join('agent.dbo.UserCallBack as au', 'ai.UserID', 'au.UserID')
            ->where('call_state','>', 0)
            ->where('ai.LastLogonDate','<', date('Y-m-d H:i:s',strtotime("-7 days")))
            ->pluck('au.UserID', 'au.UserID')->toArray();


        $lostID = [];
        if($activeLost){
            $lostID = array_values($activeLost);
        }
        if($lostID){
            //删除 分配记录
            DB::connection('write')->table('agent.dbo.UserCallBack')
                //->where('call_state',0)
                ->whereIn('UserID',$lostID)
                ->delete();

            // 删除标记
            DB::connection('write')->table(TableName::QPAccountsDB() . 'AccountsInfo')
                ->whereIn('UserID',$lostID)
                ->update(['Present' => 0]);

            DB::connection('write')->table(TableName::QPAccountsDB() . 'PrivateMail')
                ->whereIn('UserID',$lostID)
                ->where('admin_type', 1)
                ->delete();
        }
        Log::info('【用户召回后再次流失清理】' .count($lostID));
        return count($userId);
    }


    public function checkPhoneUnique($phone){
        return 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();
    }

    public static function updateAdminBonus($admin_id,$bonus,$type=1){
//        if(date('Ym')<202403){
//            return false;
//        }


        $adminBonus = DB::connection('read')->table('agent.dbo.CallBackBonus')
            ->where('Admin_ID', $admin_id)
            ->where('Month', date('Ym'))
            ->first();
        if($adminBonus){
            Log::info('【更新奖励】' .$admin_id.'-'.$bonus);
            $update = [
                'Bonus' => $adminBonus->Bonus+$bonus,
            ];
            if($type==1){
                $update['CallBackCount'] = $adminBonus->CallBackCount+1;
            }
            if($type==2){
                $update['ActiveCount'] = $adminBonus->ActiveCount+1;
            }
            DB::connection('read')->table('agent.dbo.CallBackBonus')
                ->where('Admin_ID', $admin_id)
                ->where('Month', date('Ym'))
                ->update($update);
        }else{
            Log::info('【新增奖励】' .$admin_id.'-'.$bonus);
            $insert = [
                'Admin_ID' => $admin_id,
                'Month' => date('Ym'),
                'Bonus' => $bonus,
            ];
            if($type==1){
                $insert['CallBackCount'] = 1;
            }
            if($type==2){
                $insert['ActiveCount'] = 1;
            }

            DB::connection('read')->table('agent.dbo.CallBackBonus')->insert($insert);
        }

        return true;
    }

}
