<?php

namespace app\index\controller;

use app\admin\model\Admin;
use app\admin\model\Game;
use app\admin\model\OpenIdInfo;
use app\common\controller\Frontend;

class Index extends Frontend
{

    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';
    protected $layout = '';

    /**
     * 查看
     */
    public function phone()
    {
        $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();

            $filter = $this->request->request();
            //时间
            $time = !empty($filter['time']) ? $filter['time'] : date('Y-m-d', time());
            $limit = 500;

            if(!empty($filter['pageSize'])){
                $limit = $filter['pageSize'];
            }
            if($limit == 0 || $limit == 999999){
                $limit = 500;
            }

            $order = 'cost';
            //分页 根据 $offset 和 $limit 进行分页

            //选择游戏
            if(empty($filter['game_list'])){
                $result = array("total" => 0, "rows" => [],'open_list' => "","time" => $time);
                return json($result);
            }

            if(!empty($filter['sort'])){
                $sort = $filter['sort'];
            }

            if(!empty($filter['order'])){
                $order = $filter['order'];
            }
            //选择open_id
            $open_id = !empty($filter['open_id_list']) ? $filter['open_id_list'] : "";
            $pageNum = 1;//intval($offset / $limit) + 1;
            if(!empty($filter['page'])){
                $pageNum = $filter['page'];
            }
            $pageSize = $limit;
            $arr = $this->get_arr($filter['game_list'], $open_id, $time, $pageNum, $pageSize,0);
            if($arr['code'] == 0){
                $arr = $this->get_arr($filter['game_list'], $open_id, $time, $pageNum, $pageSize,1);
                if($arr['code'] == 0){
                    $result = array("code" => 0, "err_msg" => $arr['err_msg']);
                    return json($result);
                }else{
                    $arr = $arr['arr'];
                }

            }else{
                $arr = $arr['arr'];
            }
            if(array_key_exists('records',$arr)){
                $records = $arr['records']; // 获取 records 数组
            }else{
                $records = [];
            }
            if(array_key_exists('total',$arr)){
                $total = $arr['total']; // 获取总数
            }else{
                $total = 0;
            }

            // 根据 $sort 和 $order 排序
            // 根据 $sort 和 $order 排序
            if (!empty($sort)) {
                usort($records, function($a, $b) use ($sort, $order) {
                    return ($order === 'asc') ? ($a[$sort] <=> $b[$sort]) : ($b[$sort] <=> $a[$sort]);

                });
            }
            // 初始化一个数组用于存储去重后的 open_id
            $openIds = [];
            $openIdData = [];//"openid1"=>100,"openid2"=>150
            $timeData = [];//"00:00-01:00"=>100,"01:00-02:00"=>150
            $OpenIdInfo = OpenIdInfo::column('*', 'open_id');

            // 处理每个记录（如果需要）
            foreach ($records as $k => &$v) {
                $openId = $v['open_id'];
                $v['cost'] = $v['cost'] / 100000;

                // 检查 open_id 是否已经存在于 $openIds 数组中，如果不存在则加入
                if (isset($v['open_id']) && !in_array($v['open_id'], $openIds)) {
                    $openIds[] = $v['open_id'];
                }


                // 累加 open_id 对应的 cost
                if (!isset($openIdData[$openId])) {
                    $openIdData[$openId] = 0;
                }
                $openIdData[$openId] += $v['cost'];

                // 获取事件时间并按小时区分
                $eventTime = new \DateTime($v['event_time']);
                $hourKey = $eventTime->format('H');

                // 累加时间段的 cost
                if (!isset($timeData[$hourKey])) {
                    $timeData[$hourKey] = 0;
                }
                $timeData[$hourKey] += $v['cost'];


                $records[$k]['brand'] = isset($OpenIdInfo[$openId]['brand']) ? $OpenIdInfo[$openId]['brand'] : '';
                $records[$k]['model'] = isset($OpenIdInfo[$openId]['model']) ? $OpenIdInfo[$openId]['model'] : '';
                $records[$k]['ip'] = isset($OpenIdInfo[$openId]['ip']) ? $OpenIdInfo[$openId]['ip'] : '';
                $records[$k]['edition'] = isset($OpenIdInfo[$openId]['edition']) ? $OpenIdInfo[$openId]['edition'] : '';
                $records[$k]['avatar'] = isset($OpenIdInfo[$openId]['avatar']) ? $OpenIdInfo[$openId]['avatar'] : '';
                $records[$k]['dy_name'] = isset($OpenIdInfo[$openId]['dy_name']) ? $OpenIdInfo[$openId]['dy_name'] : '';
                $records[$k]['location'] = isset($OpenIdInfo[$openId]['location']) ? $OpenIdInfo[$openId]['location'] : '';
                
            }


            $openIdData = json_encode($openIdData);
            $timeData = json_encode($timeData,true);
            $result = array("code"=> 1, "total" => $total, "rows" => $records,'open_list' => $openIds,"time" => $time,  "openIdData"=> $openIdData,  "timeData" => $timeData);

            return json($result);
        }
        $code = $this->request->request("code");
        $uid = \app\admin\model\User::where('url',$code)->where('status',1)->value('id');
        $game_list = Game::where('status',1)->where('uid',$uid)->column('name', 'appid');
        $this->assign('game_list',json_encode($game_list) );
        $admin_id = \app\admin\model\User::where('id',$uid)->value('admin_id');
        $gongsi = Admin::where('id',$admin_id)->value('title');
        // $dy = Game::where('appid',json_encode($game_list) )->value('dy');
        // $dy_id = $this->getLine15($dy);
        $this->assign('gongsi',$gongsi);
        return $this->view->fetch();
    }


    
    /**
     * 查看
     */
    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();

            $filter = $this->request->request();
            //时间
            $time = !empty($filter['time']) ? $filter['time'] : date('Y-m-d', time());
            $limit = 500;

            if(!empty($filter['pageSize'])){
                $limit = $filter['pageSize'];
            }
            if($limit == 0 || $limit == 999999){
                $limit = 500;
            }

            $order = 'cost';
            //分页 根据 $offset 和 $limit 进行分页

            //选择游戏
            if(empty($filter['game_list'])){
                $result = array("total" => 0, "rows" => [],'open_list' => "","time" => $time);
                return json($result);
            }

            if(!empty($filter['sort'])){
                $sort = $filter['sort'];
            }

            if(!empty($filter['order'])){
                $order = $filter['order'];
            }
            //选择open_id
            $open_id = !empty($filter['open_id_list']) ? $filter['open_id_list'] : "";
            $pageNum = 1;//intval($offset / $limit) + 1;
            if(!empty($filter['page'])){
                $pageNum = $filter['page'];
            }
            $pageSize = $limit;
            $arr = $this->get_arr($filter['game_list'], $open_id, $time, $pageNum, $pageSize,0);
            if($arr['code'] == 0){
                $arr = $this->get_arr($filter['game_list'], $open_id, $time, $pageNum, $pageSize,1);
                if($arr['code'] == 0){
                    $result = array("code" => 0, "err_msg" => $arr['err_msg']);
                    return json($result);
                }else{
                    $arr = $arr['arr'];
                }

            }else{
                $arr = $arr['arr'];
            }
            if(array_key_exists('records',$arr)){
                $records = $arr['records']; // 获取 records 数组
            }else{
                $records = [];
            }
            if(array_key_exists('total',$arr)){
                $total = $arr['total']; // 获取总数
            }else{
                $total = 0;
            }

            // 根据 $sort 和 $order 排序
            // 根据 $sort 和 $order 排序
            if (!empty($sort)) {
                usort($records, function($a, $b) use ($sort, $order) {
                    return ($order === 'asc') ? ($a[$sort] <=> $b[$sort]) : ($b[$sort] <=> $a[$sort]);

                });
            }
            // 初始化一个数组用于存储去重后的 open_id
            $openIds = [];
            $openIdData = [];//"openid1"=>100,"openid2"=>150
            $timeData = [];//"00:00-01:00"=>100,"01:00-02:00"=>150
            $OpenIdInfo = OpenIdInfo::column('*', 'open_id');

            // 处理每个记录（如果需要）
            foreach ($records as $k => &$v) {
                $openId = $v['open_id'];
                $v['cost'] = $v['cost'] / 100000;

                // 检查 open_id 是否已经存在于 $openIds 数组中，如果不存在则加入
                if (isset($v['open_id']) && !in_array($v['open_id'], $openIds)) {
                    $openIds[] = $v['open_id'];
                }


                // 累加 open_id 对应的 cost
                if (!isset($openIdData[$openId])) {
                    $openIdData[$openId] = 0;
                }
                $openIdData[$openId] += $v['cost'];

                // 获取事件时间并按小时区分
                $eventTime = new \DateTime($v['event_time']);
                $hourKey = $eventTime->format('H');

                // 累加时间段的 cost
                if (!isset($timeData[$hourKey])) {
                    $timeData[$hourKey] = 0;
                }
                $timeData[$hourKey] += $v['cost'];

                $records[$k]['brand'] = isset($OpenIdInfo[$openId]['brand']) ? $OpenIdInfo[$openId]['brand'] : '';
                $records[$k]['model'] = isset($OpenIdInfo[$openId]['model']) ? $OpenIdInfo[$openId]['model'] : '';
                $records[$k]['ip'] = isset($OpenIdInfo[$openId]['ip']) ? $OpenIdInfo[$openId]['ip'] : '';
                $records[$k]['edition'] = isset($OpenIdInfo[$openId]['edition']) ? $OpenIdInfo[$openId]['edition'] : '';
                $records[$k]['avatar'] = isset($OpenIdInfo[$openId]['avatar']) ? $OpenIdInfo[$openId]['avatar'] : '';
                $records[$k]['dy_name'] = isset($OpenIdInfo[$openId]['dy_name']) ? $OpenIdInfo[$openId]['dy_name'] : '';
                $records[$k]['location'] = isset($OpenIdInfo[$openId]['location']) ? $OpenIdInfo[$openId]['location'] : '';

            }


            $openIdData = json_encode($openIdData);
            $timeData = json_encode($timeData,true);
            
            $dy = Game::where('appid',$filter['game_list'])->value('dy');
            $dy_id = $this->getLine15($dy);
            $result = array("code"=> 1, "total" => $total, "rows" => $records,'open_list' => $openIds,"time" => $time,  "openIdData"=> $openIdData,  "timeData" => $timeData , 'dy'=>$dy_id);

            return json($result);
        }
        $code = $this->request->request("code");
        $uid = \app\admin\model\User::where('url',$code)->where('status',1)->value('id');
        $game_list = Game::where('status',1)->where('uid',$uid)->column('name', 'appid');
        $this->assign('game_list',json_encode($game_list) );
        $admin_id = \app\admin\model\User::where('id',$uid)->value('admin_id');
        $gongsi = Admin::where('id',$admin_id)->value('title');
        // $dy = Game::where('appid',json_encode($game_list) )->value('dy');
        // $dy_id = $this->getLine15($dy);
        $this->assign('gongsi',$gongsi);
        return $this->view->fetch();
    }


    public function get_arr($mpid, $openid = '', $datehour = '', $pageno = 1, $pagesize = 10,$type = 0)
    {
        // 检查 mpid 是否为空且是否存在于 appIds 中
        $appIds = 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);

            // 如果 result 为空，记录日志并返回
            if ($result === false) {
                return false;
            }
            $result = json_decode($result,true);
            if ($result['err_no'] === 0) {
                return ['code' => 1, 'arr'=>$result['data']];
            }else{
                return ['code' => 0, 'err_msg'=>$result['err_msg']];
            }
        }
    }


    public function getToken($appid,$type = 0)
    {
        // 检查 mpid 是否为空且是否存在于 appIds 中
        $appIds = 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 get_total($mpid, $openid = '', $datehour = '', $pageno = 1, $pagesize = 500,$type = 0)
    {
        // 检查 mpid 是否为空且是否存在于 appIds 中
        $appIds = 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);

            // 如果 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)];

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


    public function get_ecpm(){
        $game_list = $this->request->request('game_list');
        $time = $this->request->request('time');
        $arr = $this->get_total($game_list, "", $time,1,500,0);
        if($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);
            }
        }
        return json($result);
    }
    
    public function qt(){
         $ids = $this->request->request('game_list');
         $dy = \app\admin\model\Game::where('appid',$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;
        }
    }

     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;
         }
     }


}
