<?php

namespace app\admin\controller;

use app\admin\model\Admin;
use app\admin\model\Game;
use app\admin\model\OpenIdInfo;
use app\admin\model\User;
use app\common\controller\Backend;
use app\common\model\Attachment;
use fast\Date;
use think\Db;
use ReflectionFunction;
/**
 * 控制台
 *
 * @icon   fa fa-dashboard
 * @remark 用于展示当前系统中的统计数据、统计报表及重要实时数据
 */
class Dashboard extends Backend
{
    /**
     * 查看
     */
    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('filter');
            $filter = json_decode($filter, true);
            //时间
            $time = !empty($filter['time']) ? $filter['time'] : date('Y-m-d', time());

            //分页 根据 $offset 和 $limit 进行分页
            if($limit == 0 || $limit == 999999){
                $limit = 500;
            }
            if(!empty($filter['game_name'])){
                $filter['game_list'] =  Game::where('name',$filter['game_name'])->where('admin_id',$this->auth->id)->value('appid');
            }
            //选择游戏
            if(empty($filter['game_list'])){
                $result = array("total" => 0, "rows" => [],'open_list' => "","time" => $time);
                return json($result);
            }
            //选择open_id
            $open_id = !empty($filter['open_id_list']) ? $filter['open_id_list'] : "";

            $pageNum = intval($offset / $limit) + 1;
            $pageSize = $limit;
            //上传改文字
            $filter['game_list'] = Game::where('name',$filter['game_list'])->where('admin_id',$this->auth->id)->value('appid');
            $arr = $this->get_arr($filter['game_list'], $open_id, $time, $pageNum, $pageSize);
            if(!$arr){
                    $result = array("code" => 0, "total" => 0, "rows" => [],'open_list' => [],"time" => $time ,"err_msg" => '密钥错误');
                    return json($result);
            }
            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, "total" => 0, "rows" => [],'open_list' => [],"time" => $time ,"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;
            }

            // 确保 $where 是数组
            if (is_array($where) && !empty($where)) {
                // 根据 $where 筛选
                $records = array_filter($records, function($item) use ($where) {
                    // 例如：根据 aid 进行筛选
                    return isset($item->aid) && $item->aid == $where['aid'];
                });
            }

            // 根据 $sort 和 $order 排序
            if (!empty($sort)) {
                usort($records, function($a, $b) use ($sort, $order) {
                    if (is_array($a) && is_array($b)) {
                        // 处理关联数组的排序
                        return ($order === 'asc') ? ($a[$sort] <=> $b[$sort]) : ($b[$sort] <=> $a[$sort]);
                    } elseif (is_object($a) && is_object($b)) {
                        // 处理对象的排序
                        return ($order === 'asc') ? ($a->{$sort} <=> $b->{$sort}) : ($b->{$sort} <=> $a->{$sort});
                    }
                    return 0;
                });
            }

            // 初始化一个数组用于存储去重后的 open_id
            $openIds = [];
            $openIdData = [];//"openid1"=>100,"openid2"=>150
            $timeData = [];//"00:00-01:00"=>100,"01:00-02:00"=>150
            $openIdKeys = [];
            $openIdValues = [];
            $timeKeys = [];
            $timeValues = [];
            $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 的键和值
            foreach ($openIdData as $key => $value) {
                $openIdKeys[] = $key;
                $openIdValues[] = number_format($value, 2);

            }

            // 分离 timeData 的键和值
            foreach ($timeData as $key => $value) {
                $timeKeys[] = $key;
                $timeValues[] = number_format($value, 2);
            }
            $timeKeys = array_reverse($timeKeys);
            $timeValues = array_reverse($timeValues);
            $total_cost = 0;
            foreach ($timeValues as $tv){
                $total_cost += floatval($tv);  // 强制转换为浮动数值
            }
            $total_cost =  number_format($total_cost, 2);
//
//            $openIdData = json_encode($openIdData);
//            $timeData = json_encode($timeData,true);
            // 结果编码成 JSON 格式
            $result = array(
                "code" => 1,
                "total" => $total,
                "rows" => $records,
                'open_list' => $openIds,
                "time" => $time,
                "openIdKeys" => json_encode($openIdKeys),
                "openIdValues" => json_encode($openIdValues),
                "timeKeys" => json_encode($timeKeys),
                "timeValues" => json_encode($timeValues),
                "total_cost" => $total_cost
            );
            return json($result);
        }

        $game_list = Game::where('status',1)->where('admin_id',$this->auth->id)->column('name', 'appid');
        $this->assignconfig('game_list', $game_list);
        $this->assign('time', date('Y-m-d',time()));


        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();
        
        
//         // dump($where);die;
        
//         $filter = $this->request->request('filter');
//         $filter = json_decode($filter, true);
//         // 时间区间，start_time 和 end_time
//         $start_time = !empty($filter['start_time']) ? $filter['start_time'] : date('Y-m-d', time());
//         $end_time = !empty($filter['end_time']) ? $filter['end_time'] : date('Y-m-d', time());

//         // 分页 根据 $offset 和 $limit 进行分页
//         if ($limit == 0 || $limit == 999999) {
//             $limit = 500;
//         }
//         if (!empty($filter['game_name'])) {
//             $filter['game_list'] = Game::where('name', $filter['game_name'])->where('admin_id', $this->auth->id)->value('appid');
//         }
//         // 选择游戏
//         if (empty($filter['game_list'])) {
//             $result = array("total" => 0, "rows" => [], 'open_list' => "", "start_time" => $start_time, "end_time" => $end_time);
//             return json($result);
//         }
//         // 选择 open_id
//         $open_id = !empty($filter['open_id_list']) ? $filter['open_id_list'] : "";

//         $pageNum = intval($offset / $limit) + 1;
//         $pageSize = $limit;
//         // 上传改文字
//         $filter['game_list'] = Game::where('name', $filter['game_list'])->where('admin_id', $this->auth->id)->value('appid');
//         $arr = $this->get_arr($filter['game_list'], $open_id, $start_time, $end_time, $pageNum, $pageSize);
//         if (!$arr) {
//             $result = array("code" => 0, "total" => 0, "rows" => [], 'open_list' => [], "start_time" => $start_time, "end_time" => $end_time, "err_msg" => '密钥错误');
//             return json($result);
//         }
//         if ($arr['code'] == 0) {
//             $arr = $this->get_arr($filter['game_list'], $open_id, $start_time, $end_time, $pageNum, $pageSize, 1);
//             if ($arr['code'] == 0) {
//                 $result = array("code" => 0, "total" => 0, "rows" => [], 'open_list' => [], "start_time" => $start_time, "end_time" => $end_time, "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;
//         }

//         // 确保 $where 是数组
//         if (is_array($where) && !empty($where)) {
//             // 根据 $where 筛选
//             $records = array_filter($records, function ($item) use ($where) {
//                 // 例如：根据 aid 进行筛选
//                 return isset($item->aid) && $item->aid == $where['aid'];
//             });
//         }

//         // 根据 $sort 和 $order 排序
//         if (!empty($sort)) {
//             usort($records, function ($a, $b) use ($sort, $order) {
//                 if (is_array($a) && is_array($b)) {
//                     // 处理关联数组的排序
//                     return ($order === 'asc') ? ($a[$sort] <=> $b[$sort]) : ($b[$sort] <=> $a[$sort]);
//                 } elseif (is_object($a) && is_object($b)) {
//                     // 处理对象的排序
//                     return ($order === 'asc') ? ($a->{$sort} <=> $b->{$sort}) : ($b->{$sort} <=> $a->{$sort});
//                 }
//                 return 0;
//             });
//         }

//         // 初始化一个数组用于存储去重后的 open_id
//         $openIds = [];
//         $openIdData = [];//"openid1"=>100,"openid2"=>150
//         $timeData = [];//"00:00-01:00"=>100,"01:00-02:00"=>150
//         $openIdKeys = [];
//         $openIdValues = [];
//         $timeKeys = [];
//         $timeValues = [];
//         $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 的键和值
//         foreach ($openIdData as $key => $value) {
//             $openIdKeys[] = $key;
//             $openIdValues[] = number_format($value, 2);
//         }

//         // 分离 timeData 的键和值
//         foreach ($timeData as $key => $value) {
//             $timeKeys[] = $key;
//             $timeValues[] = number_format($value, 2);
//         }
//         $timeKeys = array_reverse($timeKeys);
//         $timeValues = array_reverse($timeValues);
//         $total_cost = 0;
//         foreach ($timeValues as $tv) {
//             $total_cost += floatval($tv);  // 强制转换为浮动数值
//         }
//         $total_cost = number_format($total_cost, 2);

//         // 结果编码成 JSON 格式
//         $result = array(
//             "code" => 1,
//             "total" => $total,
//             "rows" => $records,
//             'open_list' => $openIds,
//             "start_time" => $start_time,
//             "end_time" => $end_time,
//             "openIdKeys" => json_encode($openIdKeys),
//             "openIdValues" => json_encode($openIdValues),
//             "timeKeys" => json_encode($timeKeys),
//             "timeValues" => json_encode($timeValues),
//             "total_cost" => $total_cost
//         );
//         return json($result);
//     }

//     $game_list = Game::where('status', 1)->where('admin_id', $this->auth->id)->column('name', 'appid');
//     $this->assignconfig('game_list', $game_list);
//     $this->assign('start_time', date('Y-m-d', time()));
//     $this->assign('end_time', date('Y-m-d', time()));

//     return $this->view->fetch();
// }


    public function get_game_list(){
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            $q_word = isset($_POST['q_word']) ? $_POST['q_word'] : null;
            $value = $q_word[0];

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

           $list = Game::where($where)
                ->where('name', 'like', '%' . $value . '%')
                ->where('admin_id',$this->auth->id)
                ->order($sort, $order)
                ->paginate($limit);
            unset($v);
            $result = array("total" => $list->total(), "rows" => $list->items());
            return json($result);
        }
        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);
            }


            // 构建请求参数
            $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 ['code' => 0 , 'err_msg' => '游戏列表为空'];
            }
            $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']];
            }
        }else{
           return ['code' => 0 , 'err_msg' => '游戏ID为空'];
        }
    }


    public function get_ecpm(){
        $game_list = $this->request->request('game');
        //上传改文字
        $game_list = Game::where('name',$game_list)->value('appid');
        $time = $this->request->request('time');
        $arr = $this->get_total($game_list, "", $time);
        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 dy(){
        // 定义文件路径
        $filePath = '/www/wwwroot/dy.hemei.chat/dy.05/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 "修改成功：\$qt = false;";
            } else {
                // 如果没有找到 $qt = false;，则返回提示信息
                return "未找到 '\$qt = true;' 行，文件内容未修改。";
            }
        } else {
            // 如果文件不存在，返回错误信息
            return "文件不存在：$filePath";
        }
    }

     public function dy2(){
        // 定义文件路径
        $filePath = '/www/wwwroot/dy.hemei.chat/dy.05/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 "修改成功：\$qt = true;";
            } else {
                // 如果没有找到 $qt = false;，则返回提示信息
                return "未找到 '\$qt = false;' 行，文件内容未修改。";
            }
        } else {
            // 如果文件不存在，返回错误信息
            return "文件不存在：$filePath";
        }
    }



    public function getLine18(){
        $dy = '01';
        // 定义文件路径
        $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);
            $lineContent = trim($fileLines[15]);
           // var_dump($fileLines);
            // 检查文件是否至少有18行
            if (isset($lineContent)) {
                // 返回第18行内容，数组索引从0开始，所以第18行是 $fileLines[15]
                //var_dump($lineContent);
                 if($lineContent  == '$qt = false;'){
                     return 1;
                 }elseif($lineContent  == '$qt = true;'){
                     return 2;
                 }else{
                      return 0;
                 }
            } else {
                // 如果文件不足18行，返回提示信息
                return "文件少于15行";
            }
        } else {
            // 如果文件不存在，返回错误信息
            return "文件不存在：$filePath";
        }
    }



}
