<?php

namespace app\admin\controller\game;

use app\admin\controller\Dashboard;
use app\admin\model\User;
use app\common\controller\Backend;
use app\common\library\Auth;
use think\Log;
/**
 * 会员管理
 *
 * @icon fa fa-user
 */
class Game extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';
    protected $noNeedLogin = ['index'];
    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Game;
    }

    /**
     * 查看
     */
    public function index()
    {
        // 设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            // 如果发送的来源是 Selectpage，则转发到 Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->model
                ->where($where);

            if($this->auth->id != 1){
                $list = $list->where('admin_id',$this->auth->id);
            }

            $list = $list->order($sort, $order)
                ->paginate($limit);
            // 获取所有的 UID 并去重
            $uids = array_unique(array_column($list->toArray()['data'], 'uid'));

            // 一次性查询所有 UID 对应的 username，减少 SQL 查询次数
            $usernames = User::whereIn('id', $uids)->where('admin_id',$this->auth->id)->column('username', 'id');

            // 将 username 映射到 $list 中的每个元素
            foreach ($list as $k => $v) {
                // 映射 username
                $v->username = isset($usernames[$v->uid]) ? $usernames[$v->uid] : null;
                $game_data = $this->get_ecpm($v->appid);
                if($game_data['code'] == 1){
                    $v->totalCost = $game_data['arr']['totalCost'];
                    $v->totalCount = $game_data['arr']['totalCount'];
                    $v->ecpm = $game_data['arr']['ecpm'];
                }else{
                    $v->totalCost = 0;
                    $v->totalCount = 0;
                    $v->ecpm = 0;
                }
               // if($this->auth->id == 1){
                    $getLine15 = $this->getLine15($v->dy);
                    $v->is_dc = $getLine15;
                    if($getLine15 == 1){
                        $v->dy_content = '不强弹';
                    }elseif($getLine15 == 2){
                        $v->dy_content = '强弹';
                    }else{
                        $v->dy_content = '未创建文件';
                    }
              //  }

            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $this->assignconfig('admin_id',$this->auth->id);
        return $this->view->fetch();
    }

//    public function test()
//    {
//        // 设置过滤方法
//        $this->request->filter(['strip_tags', 'trim']);
//        if ($this->request->isAjax()) {
//            // 如果发送的来源是 Selectpage，则转发到 Selectpage
//            if ($this->request->request('keyField')) {
//                return $this->selectpage();
//            }
//            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
//            $list = $this->model
//                ->where($where)
//                ->order($sort, $order)
//                ->paginate($limit);
//
//            // 获取所有的 UID 并去重
//            $uids = array_unique(array_column($list->toArray()['data'], 'uid'));
//
//            // 一次性查询所有 UID 对应的 username，减少 SQL 查询次数
//            $usernames = User::whereIn('id', $uids)->column('username', 'id');
//
//            // 将 username 映射到 $list 中的每个元素
//            foreach ($list as $k => $v) {
//                // 映射 username
//                $v->username = isset($usernames[$v->uid]) ? $usernames[$v->uid] : null;
//                $game_data = $this->get_ecpm($v->appid);
//                if($game_data['code'] == 1){
//                    $v->totalCost = $game_data['arr']['totalCost'];
//                    $v->totalCount = $game_data['arr']['totalCount'];
//                    $v->ecpm = $game_data['arr']['ecpm'];
//                }else{
//                    $v->totalCost = 0;
//                    $v->totalCount = 0;
//                    $v->ecpm = 0;
//                }
//                $getLine15 = $this->getLine15($v->dy);
//                $v->is_dc = $getLine15;
//                if($getLine15 == 1){
//                    $v->dy_content = '不强弹';
//                }elseif($getLine15 == 2){
//                    $v->dy_content = '强弹';
//                }else{
//                    $v->dy_content = '未创建文件';
//                }
//
//            }
//
//            $result = array("total" => $list->total(), "rows" => $list->items());
//
//            return json($result);
//        }
//        return $this->view->fetch();
//    }

    public function get_ecpm($game_list){
        // 检查缓存
        $cacheKey = "ecpm_cache_$game_list";
        $cachedResult = \think\Cache::store('redis')->get($cacheKey);
        if ($cachedResult) {
            return $cachedResult;
        }


        $time = date('Y-m-d', time());
        $arr = $this->get_total($game_list, "", $time);
        if(!$arr){
            Log::info('null有错误记录下appid'.$game_list);
            $result = array("code" => 0, "arr" =>  ['code' => 0 , 'err_msg' => '密钥失效'],'game_list' => $game_list,"time" => $time);
            return $result;
        }elseif($arr['code'] == 1){
            $result = array("code" => 1, "arr" => $arr,'game_list' => $game_list,"time" => $time);
        }else{
            $arr = $this->get_total($game_list, "", $time,1,500,1);
            if($arr['code'] == 1){
                $result = array("code" => 1, "arr" => $arr,'game_list' => $game_list,"time" => $time);
            }else{
                $result = array("code" => 0, "arr" => $arr,'game_list' => $game_list,"time" => $time);
            }
        }

        // 原有代码逻辑...
        // 获取数据并返回结果
        \think\Cache::store('redis')->set($cacheKey, $result, 300); // 缓存1小时
        return $result;
    }

    public function get_total($mpid, $openid = '', $datehour = '', $pageno = 1, $pagesize = 500,$type = 0)
    {
        // 检查 mpid 是否为空且是否存在于 appIds 中
        $appIds = \app\admin\model\Game::where('status',1)->column('secret', 'appid');

        if (!empty($mpid) && isset($appIds[$mpid])) {
            // 如果 openid 为空，设置为空字符串
            if (empty($openid)) {
                $openid = '';
            }

            // 如果 datehour 为空，则使用当前时间
            if (empty($datehour)) {
                $datehour = date('Y-m-d H'); // 使用当前时间
            } elseif (strlen($datehour) > 10) {
                // 修剪 datehour 的长度并替换空格
                $datehour = substr($datehour, 0, 13);
                $datehour = str_replace(' ', '%20', $datehour);
            }

            // 如果 pageno 或 pagesize 为空，设置默认值
            if (empty($pageno)) {
                $pageno = 1;
            }
            if (empty($pagesize)) {
                $pagesize = 20;
            }

            // 构建请求参数
            $paramMap = [
                'mp_id' => $mpid,
                'open_id' => $openid,
                'date_hour' => $datehour,
                'page_no' => $pageno,
                'page_size' => $pagesize,
                'access_token' => $this->getToken($mpid,$type)
            ];
            // 构建 URL 并发送 HTTP GET 请求
            $url = "https://minigame.zijieapi.com/mgplatform/api/apps/data/get_ecpm?" . http_build_query($paramMap);
            $result = file_get_contents($url);
            Log::info('检测BUG');
            Log::info('access_token：'.$paramMap['access_token']);
            Log::info('url:'.$url);
            Log::info( [
                'mp_id' => $mpid,
                'open_id' => $openid,
                'date_hour' => $datehour,
                'page_no' => $pageno,
                'page_size' => $pagesize,
                'access_token' => $this->getToken($mpid,$type)
            ]);
            Log::info($result);
            // 如果 result 为空，记录日志并返回
            if ($result === false) {
                return false;
            }
            $totalCost = 0;
            $json = json_decode($result, true);
            if ($json['err_no'] == 0) {
                $jsonData = $json['data'];
                $jsonArray = $jsonData['records'];

                // 计算总成本
                foreach ($jsonArray as $record) {
                    $cost = $record['cost'];
                    $totalCost += intval($cost);
                }

                $totalCount = $jsonData['total'];
                // 分页处理
                for ($i = 1; $i <= ceil($totalCount / 500); $i++) {
                    $paramMap2 = [
                        'mp_id' => $mpid,
                        'open_id' => '',
                        'date_hour' => $datehour,
                        'page_no' => strval($i + 1),
                        'page_size' => '500',
                        'access_token' => $this->getToken($mpid)
                    ];

                    $url2 = "https://minigame.zijieapi.com/mgplatform/api/apps/data/get_ecpm?" . http_build_query($paramMap2);
                    $result2 = file_get_contents($url2);

                    if ($result2 === false) {
                        return false;
                    }

                    $json2 = json_decode($result2, true);
                    if ($json2['err_no'] == 0) {
                        $jsonData2 = $json2['data'];
                        $jsonArray2 = $jsonData2['records'];

                        // 计算每一页的总成本
                        foreach ($jsonArray2 as $record2) {
                            $cost2 = $record2['cost'];
                            $totalCost += intval($cost2);
                        }
                    }
                }

                // 计算 ecpm
                $ecpm = 0;
                if ($totalCount > 0) {
                    $ecpm = ($totalCost / 100000) * 1000 / $totalCount;
                }
                return ['code' => 1 ,'ecpm' => number_format($ecpm, 2) , 'totalCost' => number_format($totalCost / 100000,2), 'totalCount' => $totalCount];

            }else{
                return ['code' => 0 , 'err_msg' => $json['err_msg']];
            }
        }
    }

    public function getToken($appid,$type = 0)
    {
        // 检查 mpid 是否为空且是否存在于 appIds 中
        $appIds = \app\admin\model\Game::where('status',1)->column('secret', 'appid');


        $now = microtime(true) * 1000;
        $redis_key = "token_cache_$appid";

        // 检查 Redis 中是否已有 token 且未过期
        $token = \think\Cache::store('redis')->get($redis_key);
        if ($token && $type == 0) {
            return $token;
        }

        // 如果 token 过期或不存在，重新获取 token
        $paramMap = [
            'appid' => $appid,
            'grant_type' => 'client_credential',
            'secret' => $appIds[$appid]
        ];

        $url = "https://minigame.zijieapi.com/mgplatform/api/apps/v2/token";

        // 使用 cURL 发送 POST 请求
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($paramMap));
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 禁用 SSL 验证

        $result = curl_exec($ch);

// 获取请求信息
        $info = curl_getinfo($ch);
        if ($result === false) {
            echo 'Curl error: ' . curl_error($ch);
        }

        // 如果获取失败，记录日志并返回空字符串
        if ($result === false) {
            return '';
        }

        // 解析 JSON 响应并检查是否成功
        $json = json_decode($result, true);
        if ($json['err_no'] === 0) {
            $token = $json['data']['access_token'];
            // 将新 token 存入 Redis
            \think\Cache::store('redis')->set($redis_key, $token, 3600); // 1 小时缓存
            return $token;
        }

        return '';
    }
    /**
     * 添加
     */
//    public function add()
//    {
//        if ($this->request->isPost()) {
//            $this->token();
//        }
//        return parent::add();
//    }
    public function add()
    {
        if ($this->request->isPost()) {
            $this->token();
            // 获取当前请求的数据
            $request = $this->request->request();

            $request['row']['admin_id'] = $this->auth->id;
            if($this->auth->id != 1){
                $count = \app\admin\model\Game::where('admin_id',$this->auth->id)->count();
                $game_count = $this->auth->game_count;
                if($count >= $game_count){
                    $this->error('已达上限，请联系管理员');
                }
            }
            // 将数据手动插入数据库
            $gameModel = new \app\admin\model\Game();
            if ($gameModel->save($request['row'])) {
                $this->success('游戏添加成功');
            } else {
                $this->error('游戏添加失败');
            }
        }else{
         // return parent::add();

            $this->assign('auth_id', $this->auth->id);
            return $this->view->fetch();
        }
    }
    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $this->token();
            $row = $this->model->get($ids);

            if (!$row) {
                $this->error(__('No Results were found'));
            }
            return parent::edit($ids);

        }else{
            $row = $this->model->get($ids);

            if (!$row) {
                $this->error(__('No Results were found'));
            }
            $this->assign('row', $row);
            $this->assign('auth_id', $this->auth->id);
            return $this->view->fetch();
        }

//        $this->view->assign('groupList', build_select('row[group_id]', \app\admin\model\UserGroup::column('id,name'), $row['group_id'], ['class' => 'form-control selectpicker']));
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        // 处理可能是单个数字或多个数字的情况
        $idsToDelete = is_array($ids) ? $ids : explode(',', $ids);
        // 删除记录
        $result = \app\admin\model\Game::whereIn('id', $idsToDelete);

        if($this->auth->id != 1){
            $result = $result->where('admin_id',$this->auth->id);
        }

        $result->delete();
        $this->success();
    }

    public function getLine15($dy){
        if(!$dy || $dy == null || $dy == 0){
            return 0;
        }
        // 定义文件路径
        $filePath = '/www/wwwroot/dy.hemei.chat/dy.'.$dy.'/qt.php';

        // 检查文件是否存在
        if (file_exists($filePath)) {
            // 使用 file() 读取文件的所有行
            $fileLines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

            // 检查文件是否至少有18行
            if (isset($fileLines[15])) {
                $lineContent = trim($fileLines[15]);
                // 返回第18行内容，数组索引从0开始，所以第18行是 $fileLines[15]
                if($lineContent  == '$qt = false;'){
                    return 1;
                }elseif($lineContent  == '$qt = true;'){
                    return 2;
                }else{
                    return 0;
                }
            } else {
                // 如果文件不足18行，返回提示信息
                return 0;
            }
        } else {
            // 如果文件不存在，返回错误信息
            return 0;
        }
    }

    public function qt($ids){
        $dy = \app\admin\model\Game::where('id',$ids)->value('dy');
        if(!$dy || $dy == null || $dy == 0){
            return 0;
        }
        // 定义文件路径
        $filePath = '/www/wwwroot/dy.hemei.chat/dy.'.$dy.'/qt.php';

        // 检查文件是否存在
        if (file_exists($filePath)) {
            // 使用 file() 读取文件的所有行
            $fileLines = file($filePath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

            // 检查文件是否至少有18行
            if (isset($fileLines[15])) {
                $lineContent = trim($fileLines[15]);
                // 返回第18行内容，数组索引从0开始，所以第18行是 $fileLines[15]
                if($lineContent  == '$qt = false;'){
                    $result =  $this->qt_open($dy);
                    if($result){
                        $this->success(__('开启强弹成功'));
                    }else{
                        $this->error(__('设置失败,请联系技术员处理2'));
                    }
                }elseif($lineContent  == '$qt = true;'){

                    $result = $this->qt_close($dy);
                    if($result){
                        $this->success(__('关闭强弹成功'));
                    }else{
                        $this->error(__('设置失败,请联系技术员处理1'));
                    }
                }else{
                    $this->error(__('设置失败,请联系技术员处理3'));
                }
            } else {
                // 如果文件不足18行，返回提示信息
                $this->error(__('设置失败,请联系技术员处理4'));
            }
        } else {
            // 如果文件不存在，返回错误信息
            $this->error(__('文件名ID不存在'));
        }
    }

    public function qt_open($dy){
        // 定义文件路径
        $filePath = '/www/wwwroot/dy.hemei.chat/dy.'.$dy.'/qt.php';

        // 检查文件是否存在
        if (file_exists($filePath)) {
            // 读取文件内容
            $fileContent = file_get_contents($filePath);

            // 检查文件内容是否包含 $qt = false;
            if (strpos($fileContent, '$qt = false;') !== false) {
                // 替换 $qt = false; 为 $qt = true;
                $newContent = str_replace('$qt = false;', '$qt = true;', $fileContent);

                // 将新内容写回到文件
                file_put_contents($filePath, $newContent);

                // 返回成功信息
                return true;//"修改成功：\$qt = true;";
            } else {
                // 如果没有找到 $qt = false;，则返回提示信息
                return false;
            }
        } else {
            // 如果文件不存在，返回错误信息
            return false;
        }
    }

    public function qt_close($dy){
        // 定义文件路径
        $filePath = '/www/wwwroot/dy.hemei.chat/dy.'.$dy.'/qt.php';

        // 检查文件是否存在
        if (file_exists($filePath)) {
            // 读取文件内容
            $fileContent = file_get_contents($filePath);

            // 检查文件内容是否包含 $qt = false;
            if (strpos($fileContent, '$qt = true;') !== false) {
                // 替换 $qt = false; 为 $qt = true;
                $newContent = str_replace('$qt = true;', '$qt = false;', $fileContent);

                // 将新内容写回到文件
                file_put_contents($filePath, $newContent);

                // 返回成功信息
                return true;
            } else {
                // 如果没有找到 $qt = false;，则返回提示信息
                return false;
            }
        } else {
            // 如果文件不存在，返回错误信息
            return false;
        }
    }



}
