<?php

namespace App\Console\Commands;


use App\Models\School;
use App\Models\SchoolPlan;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Overtrue\Pinyin\Pinyin;
use Illuminate\Support\Facades\Http;
use App\Models\AreaProvinceModel;
use App\Models\SchoolProvincescore;
use App\Models\MajorCategory;
use App\Models\Major;
use App\Models\SchoolPlanBefore;
use App\Models\MajorReSchool;
use App\Models\SchoolMajorScore;
use App\Models\MajorDetail;
class UpdateCourseCode extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'test:data   {begin} {end}';

    protected $categoryModel;

    protected $courseModel;

    protected $orderSubModel;

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '爬数据,';

    /**
     * Execute the console command.
     *
     * @return int
     */

    public static $domain = 'https://gaozhaoapi.eoffcn.com';



    public function handle(){

        //招生简章列表：https://static-data.gaokao.cn/www/2.0/school/140/news/list.json?a=www.gaokao.cn

        $begin = (int)$this->argument('begin');
        $end = (int)$this->argument('end');
        dump($begin, $end);

        $url = "https://static-data.gaokao.cn/www/2.0/config/dicprovince/dic.json?a=www.gaokao.cn";
        $response = Http::withHeaders([
            'Content-Type' => 'application/json',
            'authority' => 'api.zjzw.cn',
        ])->get($url, []);
        $bodyData = $response->json(); // 如果响应是 JSON 格式，解析为数组或对象
        if ($bodyData['code'] != '0000') {
            dd($bodyData);
        }
        $batchData = $bodyData['data'];

        $areaProvinceModel = new AreaProvinceModel();
        $pdata = $areaProvinceModel->selectDataWithField(['country' => 1], ['id', 'name']);
        $provinceData = array_column($pdata, 'name', 'id');


        $School = new School();
        $SchoolPlanBefore = new SchoolPlanBefore();

        $filed = ['id','school_id'];
        $School::select($filed)->where([['id', '>=', $begin], ['id','<', $end], ['level_name', 'like', "本科%"]])->chunkById(10, function ($list) use (&$SchoolPlanBefore, &$batchData, &$provinceData) {
            $userList = $list->toArray();
            foreach ($userList as $v) {
                $schoolId = $v['school_id'];

                try {
                    //专业对应检索条件
                    $url = "https://static-data.gaokao.cn/www/2.0/school/{$schoolId}/dic/specialplan.json?a=www.gaokao.cn";
                    $response = Http::withHeaders([
                        'Content-Type' => 'application/json',
                        'authority' => 'api.zjzw.cn',
                    ])->get($url, []);
                    $bodyData = $response->json(); // 如果响应是 JSON 格式，解析为数组或对象
                    if ($bodyData['code'] != '0000') {
                        continue;
                    }
                    if (!isset($bodyData['data']) || empty($bodyData['data'])) {
                        continue;
                    }

                    $provinceDataRePid = $bodyData['data']['pids'];
                    if(empty($provinceDataRePid)){
                        continue;
                    }

                } catch (\Exception $e) {
                    echo $url . ' ';
                    continue;
                }

                    foreach ($provinceDataRePid as $pki => $pid){


                        $ret = $SchoolPlanBefore->findDataWithField(['school_id'=>$schoolId,'year'=>2025,'province_id'=>$pid], ['id']);
                        if(!empty($ret)){
                            continue;
                        }


                        $year = 2025;
                        sleep(2);

                        try {
                            $url = "https://static-data.gaokao.cn/www/2.0/schoolspecialplan/{$schoolId}/{$year}/{$pid}.json?a=www.gaokao.cn";
                            $response = Http::withHeaders([
                                'Content-Type' => 'application/json',
                                'authority' => 'api.zjzw.cn',
                            ])->get($url, []);
                            $bodyData = $response->json(); // 如果响应是 JSON 格式，解析为数组或对象
                            if ($bodyData['code'] != '0000') {
                                dump($v['id'], $bodyData);
                                continue;
                            }
                            if (!isset($bodyData['data']) || empty($bodyData['data'])) {
                                continue;
                            }

                            foreach ($bodyData['data'] as $key => $value) {

                                $ex = explode('_', $key);

                                $groupId = $ex[2];
                                if ($groupId != 0) {
                                    continue;
                                }
                                $iData = [];
                                foreach ($value['item'] as $it => $item) {
                                    $tmp = [
                                        'school_id' => $schoolId,
                                        'year' => $year,
                                        'province_id' => $item['province'],
                                        'province_name' => $provinceData[$pid] ?? "",
                                        'local_type_id' => $item['type'],
                                        'local_type_name' => $batchData[$item['type']] ?? "",
                                        'local_batch_id' => $item['batch'],
                                        'local_batch_name' => $batchData[$item['batch']] ?? "",
                                        'num' => $item['num'],
                                        'level1' => $item['level1'],
                                        'level1_name' => $item['level1_name'],
                                        'level2' => $item['level2'],
                                        'level2_name' => $item['level2_name'],
                                        'level3' => $item['level3'],
                                        'level3_name' => $item['level3_name'],
                                        'sg_info' => $item['sg_info'],
                                        'sg_name' => $item['sg_name'],
                                        'sg_sxk' => $item['sg_sxk'],
                                        'sg_type' => $item['sg_type'],
                                        'sp_name' => $item['sp_name'],
                                        'special_group' => $item['special_group'],
                                        'special_id' => $item['special_id'],
                                        'spe_id' => $item['spe_id'],
//                                        'special_group_all' =>json_encode($special_group, JSON_UNESCAPED_UNICODE),
                                        'all_data' => json_encode($item, JSON_UNESCAPED_UNICODE),
                                    ];

                                    $iData[] = $tmp;
                                }

                                $SchoolPlanBefore->insertMultiData($iData);

                            }

                        } catch (\Exception $e) {
                            dump("****************************************");
                            dump($pid, $e->getMessage());
                            dump("****************************************");
                            sleep(2);
                        }
                    }


                echo $v['id'] . ' ';

            }
        });

    }

    public function handle13(){

        $begin = (int)$this->argument('begin');
        $end = (int)$this->argument('end');
        dump($begin, $end);


        $areaProvinceModel = new AreaProvinceModel();
        $pdata = $areaProvinceModel->selectDataWithField(['country' => 1], ['id', 'name']);
        $provinceData = array_column($pdata, 'name', 'id');

        $date = [2024];

        $Major = new Major();
        $MajorReSchool = new MajorReSchool();
        $MajorDetail = new MajorDetail();
        $filed = ['id','special_id'];


        $Major::select($filed)->where([['id', '>=', $begin], ['id','<', $end]])->chunkById(30, function ($list) use (&$MajorDetail, &$MajorReSchool,&$provinceData, &$date) {

            $userList = $list->toArray();

            foreach ($userList as $key => $value) {

                try {

                    //专业概况
                    $url = "https://static-data.gaokao.cn/www/2.0/special/{$value['special_id']}/pc_special_detail.json?a=www.gaokao.cn";
                    $response = Http::withHeaders([
                        'Content-Type' => 'application/json',
                        'authority' => 'api.zjzw.cn',
                    ])->get($url, []);
                    $bodyData = $response->json(); // 如果响应是 JSON 格式，解析为数组或对象
                    if ($bodyData['code'] != '0000') {
                        dd($value['id'], $bodyData);
                    }

                    $jsonData = $bodyData['data'];

                    $MajorDetail->insertData(['special_id'=>$value['special_id'], 'content'=>json_encode($jsonData, JSON_UNESCAPED_UNICODE)]);

                    //专业对应检索条件
                    $url = "https://static-data.gaokao.cn/www/2.0/specialscoresort/{$value['special_id']}/dicspecialscore.json?a=www.gaokao.cn";
                    $response = Http::withHeaders([
                        'Content-Type' => 'application/json',
                        'authority' => 'api.zjzw.cn',
                    ])->get($url, []);
                    $bodyData = $response->json(); // 如果响应是 JSON 格式，解析为数组或对象
                    if ($bodyData['code'] != '0000') {
                        dd($value['id'], $bodyData);
                    }

                    $searchJsonData = $bodyData['data']['batch'] ?? [];
                    if(empty($searchJsonData)){
                        continue;
                    }


                    foreach ($searchJsonData as $yearIndex => $batchidValue){
                        $explode = explode('_', $yearIndex);
                        $year = $explode[1];
                        if($year < 2022){
                            continue;
                        }
                        $local_province_id = $explode[0];
                        if($year == "" || $local_province_id == ""){
                            continue;
                        }
                        if(empty($batchidValue)){
                            continue;
                        }

                        foreach ($batchidValue as $kbIndex => $local_batch_idV){

                            $local_batch_id = $local_batch_idV['id'];

                            $max = 1;
                            for ($i = 1; $i <= $max; $i++) {
                                sleep(10);
                                $localUrl = "https://api.zjzw.cn/web/api/?is_single=2&local_batch_id={$local_batch_id}&local_province_id={$local_province_id}&local_type_id=&page={$i}&province_id=&request_type=1&size=20&spe_id={$value['special_id']}&special_id={$value['special_id']}&type=&uri=apidata/api/gk/score/special&year={$year}&signsafe=30ef56fe7c548e83d4b5517381244dda" . mt_rand(100, 999);
//                    dd($localUrl);
                                $response = Http::withHeaders([
                                    'Content-Type' => 'application/json',
                                    'Origin' => 'https://www.gaokao.cn',
                                    'Referer' => 'https://www.gaokao.cn',
//                        'User-Agent:' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36',
                                ])->post($localUrl, []);
                                $bodyDatas = $response->json(); // 如果响应是 JSON 格式，解析为数组或对象
                                if ($bodyDatas['code'] != '0000') {
                                    dump($value['id'],$bodyDatas);
                                    continue;
                                }
                                if (!isset($bodyDatas['data']) || empty($bodyData['data'])) {
                                    dump($value['id'], $bodyDatas);
                                    continue;
                                }

                                $numFound = $bodyDatas['data']['numFound'];
                                $allData = $bodyDatas['data']['item'];
                                if (empty($allData)) {
                                    continue;
                                }

                                if (ceil($numFound / 20) > 1) {
                                    $max = ceil($numFound / 20);
                                }

                                $inData = [];
                                foreach ($allData as $k => $v){
                                    $tmp = [
                                        'school_id' => $v['school_id'],
                                        'special_id' => $value['special_id'],
                                        'name' => $v['name'],
                                        'year' => $year,
                                        'local_province_id' => $local_province_id,
                                        'local_province_name' => $provinceData[$local_province_id] ?? "",
                                        'local_type_name' => $v['local_type_name'],
                                        'local_batch_name' => $v['local_batch_name'],
                                        'content'=>json_encode($jsonData, JSON_UNESCAPED_UNICODE)
                                    ];

                                    $inData[] = $tmp;
                                }
                                $MajorReSchool->insertMultiData($inData);
                            }

                        }

                    }



                } catch (\Exception $e) {
                    dump("****************************************");
                    dump($value['id'], $e->getMessage());
                }
            }

        });
    }

    public function handle9(){

        try {

            $url = "https://static-data.gaokao.cn/www/2.0/config/special/information.json?a=www.gaokao.cn";
            $response = Http::withHeaders([
                'Content-Type' => 'application/json',
                'authority' => 'api.zjzw.cn',
            ])->get($url, []);
            $bodyData = $response->json(); // 如果响应是 JSON 格式，解析为数组或对象
            if ($bodyData['code'] != '0000') {
                dd(00,$bodyData);
            }
            if (!isset($bodyData['data']) || empty($bodyData['data'])) {
                dd(11,$bodyData);
            }

            $jsonData = $bodyData['data'];


            $MajorCategory = new MajorCategory();
            $Major = new Major();
            foreach ($jsonData['id_1']['item'] as $key => $value){

                $insertData = [
                    'name' =>  $value['name'],
                    'code' =>  $value['code'],
                    'spe_id' =>  $value['spe_id'],
                    'level1' =>  $value['level1'],
                    'pid' =>  0,
                ];
                $insertId = $MajorCategory->insertData($insertData);

                if(!isset($jsonData["id_".$value['spe_id']])){
                    continue;
                }

                $level2 = $jsonData["id_".$value['spe_id']]['root_id'];
                foreach ($jsonData["id_".$value['spe_id']]['item'] as $index => $item){

                    sleep(15);
                    $sinsertData = [
                        'name' =>  $item['name'],
                        'code' =>  $item['code'],
                        'spe_id' =>  $item['spe_id'],
                        'level1' =>  $item['level1'],
                        'pid' =>  $insertId,
                    ];
                    $MajorCategory->insertData($sinsertData);


                    $localUrl = "https://api.zjzw.cn/web/api/?keyword=&level1=1&level2={$level2}&level3={$item['spe_id']}&page=1&size=30&sort=&uri=apidata/api/gkv3/special/lists&signsafe=0b8c62335685625f3e2e05eeb98708b5".mt_rand(100,999);
//                    dd($localUrl);
                    $response = Http::withHeaders([
                        'Content-Type' => 'application/json',
//                        'authority' => 'api.zjzw.cn',
                        'Origin' => 'https://www.gaokao.cn',
                        'Referer' => 'https://www.gaokao.cn',
//                        'User-Agent:' => 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/116.0.0.0 Safari/537.36',
                    ])->post($localUrl, []);
                    $bodyDatas = $response->json(); // 如果响应是 JSON 格式，解析为数组或对象
                    if ($bodyDatas['code'] != '0000') {
                        dd($bodyDatas);
                    }
                    if (!isset($bodyDatas['data']) || empty($bodyData['data'])) {
                        dd(22,$bodyData);
                    }

                    $iData = [];
                    foreach ($bodyDatas['data']['item'] as $k => $z){
                        $tmp = [
                            'boy_rate'=>$z['boy_rate'],
                            'degree'=>$z['degree'],
                            'fivesalaryavg'=>$z['fivesalaryavg'],
                            'girl_rate'=>$z['girl_rate'],
                            'hightitle'=>$z['hightitle'],
                            'mid'=>$z['id'],
                            'level1'=>$z['level1'],
                            'level1_name'=>$z['level1_name'],
                            'level2'=>$z['level2'],
                            'level2_name'=>$z['level2_name'],
                            'level3'=>$z['level3'],
                            'level3_name'=>$z['level3_name'],
                            'limit_year'=>$z['limit_year'],
                            'name'=>$z['name'],
                            'salaryavg'=>$z['salaryavg'],
                            'spcode'=>$z['spcode'],
                            'special_id'=>$z['special_id'],
                        ];

                        $iData[] = $tmp;
                    }

                    $Major->insertMultiData($iData);

                }



            }

        } catch (\Exception $e) {
            dump("****************************************");
            dump($e->getMessage());
            dump("****************************************");
            sleep(10);
        }

    }


    //专业介绍： https://static-data.gaokao.cn/www/2.0/special/267/pc_special_detail.json?a=www.gaokao.cn
    //排行：https://api.zjzw.cn/web/api/?is_single=2&local_province_id=11&page=1&province_id=&request_type=1&size=20&special_id=267&top_school_id=512,518&type=&uri=apidata/api/gk/special/school&signsafe=a937326294ba583f19643d4d8b7c30dd
    //https://api.zjzw.cn/web/api/?is_single=2&local_province_id=11&page=1&province_id=&request_type=1&size=20&sort=xueke_rank&sorttype=asc&special_id=267&top_school_id=512,518&type=&uri=apidata/api/gk/special/school&signsafe=a66aa2fab43a2cecfdac61f69eec4733

    public function handle6()
    {


        $directoryPath = './public/uploads/plan';

        $files = scandir($directoryPath);

        foreach ($files as $file) {
            if ($file === '.' || $file === '..') { // 跳过目录中的"."和".."
                continue;
            }
            $filePath = $directoryPath . '/' . $file;
            $sfiles = scandir($filePath);
            foreach ($sfiles as $json) {
                if ($json === '.' || $json === '..') { // 跳过目录中的"."和".."
                    continue;
                }
                $jsonFilePath = $directoryPath . '/' . $file . '/' . $json;

//                $jsonFilePath = './public/uploads/plan/140/140_219989_68000.json';
//                $jsonFilePath = './public/uploads/plan/1000/1000_42469_68001.json';
                $jsonContent = file_get_contents($jsonFilePath);
                $bom = pack('H*', 'EFBBBF');
                $jsonContent = preg_replace("/^$bom/", '', $jsonContent);
                $jsonData = json_decode($jsonContent, true);
                if (json_last_error() !== JSON_ERROR_NONE) {
                    continue;
                }

                if (empty($jsonData)) {
                    continue;
                }

                $html = $jsonData['html'];

                $dom = new DOMDocument();
                libxml_use_internal_errors(true); // 忽略 HTML 解析警告
//        $dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
                // 编码处理关键步骤
                $html = '<?xml encoding="UTF-8"><!DOCTYPE html>' . $html;
                $dom->loadHTML($html, LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
                $dom->encoding = 'UTF-8';

                $saveDir = './public/uploads/planimg';
                // 创建保存目录（如果不存在）
                if (!file_exists($saveDir)) {
                    if (!mkdir($saveDir, 0755, true)) {
                        dd("无法创建保存目录");
                    }
                }


                // 目标域名（需处理的域名）
                $targetDomains = ['static-data.eol.cn', 'static-data.gaokao.cn'];

// 遍历所有图片
                $jishu = 0;
                foreach ($dom->getElementsByTagName('img') as $img) {
                    $img->removeAttribute('alt');

                    $originalSrc = $img->getAttribute('src');
                    // 解析 URL 获取域名部分
                    $parsedUrl = parse_url($originalSrc);
                    $host = $parsedUrl['host'] ?? '';

                    if (in_array($host, $targetDomains)) {

                        $filename = basename($originalSrc);

                        $localPath = $saveDir . '/' . $filename;

                        $downRet = $this->downloadWithCurl($originalSrc, $localPath);
                        if(isset($downRet['error'])){
                            dump($downRet);
                            continue;
                        }
//                        dd($downRet, $originalSrc,$localPath);
//                        file_put_contents($localPath, $imageData);

                        // 替换为本地路径
                        $basePath = '/uploads/planimg/' . $filename;
                        $srcUrl = self::$domain . $basePath;
                        $img->setAttribute('src', $srcUrl);
                        $jishu ++;
                    }
                }

                if($jishu == 0){
                    dump("continue: " .$jsonFilePath);
                    continue; //如果么有替换过，就没必要重新写一份。
                }

// 获取修改后的 HTML
                $modifiedHtml = $dom->saveHTML();
                $modifiedHtml = str_replace(
                    ['<?xml encoding="UTF-8">', '<!DOCTYPE html>'],
                    '',
                    $modifiedHtml
                );


// 添加新字段
                $jsonData['new_html'] = html_entity_decode($modifiedHtml, ENT_QUOTES, 'UTF-8');;

// 写回文件（保留中文并美化格式）
                file_put_contents(
                    $jsonFilePath, json_encode($jsonData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE)
                );

                dump("done: " .$jsonFilePath);

            }


        }
    }

    public function downloadWithCurl($url, $savePath) {
        $ch = curl_init();
        // 基础配置
        curl_setopt_array($ch, [
            CURLOPT_URL            => $url,
            CURLOPT_RETURNTRANSFER => true,   // 返回内容不直接输出
            CURLOPT_FOLLOWLOCATION => true,   // 跟随重定向
            CURLOPT_MAXREDIRS      => 3,      // 最大重定向次数
            CURLOPT_TIMEOUT        => 30,     // 超时时间(秒)
            CURLOPT_SSL_VERIFYPEER => false,  // 禁用SSL验证 (仅测试环境使用)
            CURLOPT_SSL_VERIFYHOST => 0,
            CURLOPT_USERAGENT      => 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36' // 模拟浏览器
        ]);

        // 执行请求
        $data = curl_exec($ch);
        $error = curl_error($ch);
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

        curl_close($ch);

        // 错误处理
        if ($error) {
            return ['error' => "CURL错误: $error"];
        }

        if ($httpCode !== 200) {
            return ['error' => "HTTP状态码: $httpCode"];
        }

        // 保存文件
        if (!file_put_contents($savePath, $data)) {
            return ['error' => '文件写入失败'];
        }

        return ['success' => true];
    }


    //招生简章
    public function handle0(){


        //招生简章列表：https://static-data.gaokao.cn/www/2.0/school/140/news/list.json?a=www.gaokao.cn

        $begin = (int)$this->argument('begin');
        $end = (int)$this->argument('end');
        dump($begin, $end);

        $School = new School();
        $SchoolPlan = new SchoolPlan();

        $filed = ['id','school_id'];
        $School::select($filed)->where([['id', '>=', $begin], ['id','<', $end], ['level_name', 'like', "本科%"]])->chunkById(30, function ($list) use (&$SchoolPlan) {
            $userList = $list->toArray();
            foreach ($userList as $v) {
                sleep(5);
                $schoolId = $v['school_id'];

                    try {

                        $url = "https://static-data.gaokao.cn/www/2.0/school/" . $schoolId . "/news/list.json?a=www.gaokao.cn";
                        $response = Http::withHeaders([
                            'Content-Type' => 'application/json',
                            'authority' => 'api.zjzw.cn',
                        ])->get($url, []);
                        $bodyData = $response->json(); // 如果响应是 JSON 格式，解析为数组或对象
                        if ($bodyData['code'] != '0000') {
                            dump($v['id'], $bodyData);
                            continue;
                        }
                        if (!isset($bodyData['data']) || empty($bodyData['data'])) {
                            continue;
                        }

                        foreach ($bodyData['data'] as $item){

                            sleep(5);

                            //https://static-data.gaokao.cn/www/2.0/school/140/news/68000/219989.json?a=www.gaokao.cn
                            $planid = $item['id'];
                            $type = $item['type'];
                            $url = "https://static-data.gaokao.cn/www/2.0/school/" . $schoolId . "/news/".$type."/".$planid.".json?a=www.gaokao.cn";
                            $response = Http::withHeaders([
                                'Content-Type' => 'application/json',
                                'authority' => 'api.zjzw.cn',
                            ])->get($url, []);
                            $bodyData = $response->json(); // 如果响应是 JSON 格式，解析为数组或对象
                            if ($bodyData['code'] != '0000') {
                                dump($v['id'], $bodyData);
                                continue;
                            }
                            if (!isset($bodyData['data']) || empty($bodyData['data'])) {
                                continue;
                            }

                            $htmlContent = $bodyData['data']['content'];
                            $data = [
                                'html' => $htmlContent,
                                'timestamp' => date('Y-m-d H:i:s')
                            ];
                            $jsonData = json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
                            if ($jsonData === false) {
                                dump('JSON 编码错误: ' . json_last_error_msg());
                                continue;
                            }


                            $saveDir = './public/uploads/plan/'.$schoolId;
                            // 创建保存目录（如果不存在）
                            if (!file_exists($saveDir)) {
                                if (!mkdir($saveDir, 0755, true)) {
                                   dd("无法创建保存目录");
                                }
                            }

                            $filePath = $saveDir.'/'. $schoolId.'_'.$planid.'_'.$type.'.json';
                            $basePath = '/uploads/plan/'.$schoolId.'/'. $schoolId.'_'.$planid.'_'.$type.'.json';
                            $result = file_put_contents($filePath, $jsonData);

                            if ($result === false) {
                                dump('文件写入失败');
                                continue;
                            }

                            $insertData = [
                                'plan_id'=>$planid,
                                'type'=>$type,
                                'school_id'=>$schoolId,
                                'title'=>$item['title'],
                                'year'=>$item['year'],
                                'content'=>$basePath,
                            ];
                            $SchoolPlan->insertData($insertData);

                        }

                    } catch (\Exception $e) {
                        dump("****************************************");
                        dump($v['id'],$e->getMessage());
                        dump("****************************************");
                        sleep(10);
                    }

                echo $v['id'] . ' ';

            }
        });

    }




    public function handle1(){
        $begin = (int)$this->argument('begin');
        $end = (int)$this->argument('end');

        dump($begin, $end);
        $schoolProvincescore = new SchoolProvincescore();

        $filed = ['id','school_id','year','province_id','local_type_id', 'local_batch_id','special_group_id','sg_name','special_group'];
        $schoolProvincescore::select($filed)->where([['id', '>=', $begin], ['id', '<', $end]])->chunkById(30, function ($list) use (&$schoolProvincescore) {
            $userList = $list->toArray();


            foreach ($userList as $v) {
                $schoolId = $v['school_id'];
                $provinceid = $v['province_id'];
                $typeid = $v['local_type_id'];
                $year = $v['year'];

                if (!empty($v['sg_name']) && $v['special_group'] == "[]") {
                    sleep(1);

                    try {

                        $reqData = ["local_batch_id" => $v['local_batch_id'], "local_province_id" => $provinceid, "local_type_id" => $typeid, "page" => 1, "school_id" => $schoolId, "signsafe" => "b264caa87b003f5903c78a51f09c7341", "size" => 20, "special_group" => $v['special_group_id'], "uri" => "apidata/api/gkv3/plan/school", "year" => $year];

                        $localUrl = "https://api.zjzw.cn/web/api/?local_batch_id=" . $v['local_batch_id'] . "&local_province_id=" . $provinceid . "&local_type_id=" . $typeid . "&page=1&school_id=" . $schoolId . "&size=20&special_group=" . $v['special_group_id'] . "&uri=apidata/api/gkv3/plan/school&year=" . $year . "&signsafe=b264caa87b003f5903c78a51f09c7341";
                        $response = Http::withHeaders([
                            'Content-Type' => 'application/json',
                            'authority' => 'api.zjzw.cn',
                        ])->post($localUrl, $reqData);
                        $bodyDatas = $response->json(); // 如果响应是 JSON 格式，解析为数组或对象
                        if($bodyDatas['code'] == 1069){
                            dump($v,$bodyDatas);
                            sleep(60);
                        }

                        if ($bodyDatas['code'] == '0000') {
                            $zhuanye = $bodyDatas['data'];

                            $updateData = [
                                'special_group' => json_encode($zhuanye, JSON_UNESCAPED_UNICODE),
                            ];

                            $schoolProvincescore->updateData(['id' => $v['id']], $updateData);
                        }

                    } catch (\Exception $e) {
                        dump($e->getMessage());
                        sleep(20);
                    }
                }


                echo $v['id'] . ' ';

            }
        });

    }

    public function handle3()
    {


        $begin = (int)$this->argument('begin');
        $end = (int)$this->argument('end');

        dump($begin, $end);

        $school = new School();
        $schoolProvincescore = new SchoolProvincescore();
        $areaProvinceModel = new AreaProvinceModel();
        $pdata = $areaProvinceModel->selectDataWithField(['country' => 1], ['id', 'name']);
        $provinceData = array_column($pdata, 'name', 'id');

        $school::select(['id','school_id'])->where([['id', '>=', $begin], ['id','<', $end], ['level_name', 'like', "本科%"]])->chunkById(30, function ($list) use (&$provinceData, &$schoolProvincescore) {
            $userList = $list->toArray();

            foreach ($userList as $userInfo) {

                try {


                    $schoolId = $userInfo['school_id'];
                    //获取科目
                    $url = "https://static-data.gaokao.cn/www/2.0/school/" . $schoolId . "/dic/provincescore.json?a=www.gaokao.cn";
                    $response = Http::withHeaders([
                        'Content-Type' => 'application/json',
                        'authority' => 'api.zjzw.cn',
                    ])->get($url, []);
                    $bodyData = $response->json(); // 如果响应是 JSON 格式，解析为数组或对象
                    if ($bodyData['code'] != '0000') {
                        dump($schoolId, $bodyData);
                        continue;
                    }
                    if (!isset($bodyData['data']['newsdata'])) {
                        dump('newsdata error：' . $schoolId);
                        continue;
                    }
                    if (!isset($bodyData['data']['newsdata']['type'])) {
                        dump('type error：' . $schoolId);
                        continue;
                    }

                    $typeArr = $bodyData['data']['newsdata']['type'];

                    foreach ($typeArr as $index => $item) {
                        sleep(3);
                        //62_2022
                        $strArr = explode('_', $index);

                        $year = $strArr[1];
                        $provinceid = $strArr[0];

                        $ret = $schoolProvincescore->findDataWithField(['year'=>$year, 'school_id'=>$schoolId,'province_id'=>$provinceid],['id']);
                        if(!empty($ret)){
                            continue;
                        }

                        foreach ($item as $typeid) {

//                            sleep(3);

                            $reqData = ["local_province_id" => $provinceid, "local_type_id" => $typeid, "page" => 1, "platform" => "2", "school_id" => $schoolId, "signsafe" => "29aef999992363fe732a38f251131980", "size" => 20, "uri" => "v1/school/province_score", "year" => $year];

                            $url = "https://api-gaokao.zjzw.cn/apidata/web?local_province_id=" . $provinceid . "&local_type_id=" . $typeid . "&page=1&platform=2&school_id=" . $schoolId . "&size=20&uri=v1/school/province_score&year=" . $year . "&signsafe=29aef999992363fe732a38f251131980";
                            $response = Http::withHeaders([
                                'Content-Type' => 'application/json',
                                'authority' => 'api.zjzw.cn',
                            ])->post($url, $reqData);
                            $bodyDatas = $response->json(); // 如果响应是 JSON 格式，解析为数组或对象
                            if ($bodyDatas['code'] != '0000') {
                                dump($schoolId, $typeid, $bodyDatas);
                                continue;
                            }

                            $provinceScoreData = $bodyDatas['data']['item'];
//                        dd($provinceScoreData);
                            if (empty($provinceScoreData)) {
                                dump('暂无往年信息 $schoolId:' . $schoolId . ' $typeid: ' . $typeid . ' $bodyDatas: ' . $bodyDatas);
                                continue;
                            }

//                        sleep(5);
                            $schoolProvincescoreData = [];
                            foreach ($provinceScoreData as $i => $v) {
//                                sleep(1);

                                $zhuanye = [];
//                                if (!empty($v['sg_name'])) {
//                                    $reqData = ["local_batch_id" => $v['local_batch_id'], "local_province_id" => $provinceid, "local_type_id" => $typeid, "page" => 1, "school_id" => $schoolId, "signsafe" => "b264caa87b003f5903c78a51f09c7341", "size" => 20, "special_group" => $v['special_group'], "uri" => "apidata/api/gkv3/plan/school", "year" => $year];
//                                    $localUrl = "https://api.zjzw.cn/web/api/?local_batch_id=" . $v['local_batch_id'] . "&local_province_id=" . $provinceid . "&local_type_id=" . $typeid . "&page=1&school_id=" . $schoolId . "&size=20&special_group=" . $v['special_group'] . "&uri=apidata/api/gkv3/plan/school&year=" . $year . "&signsafe=b264caa87b003f5903c78a51f09c7341";
//                                    $response = Http::withHeaders([
//                                        'Content-Type' => 'application/json',
//                                        'authority' => 'api.zjzw.cn',
//                                    ])->post($localUrl, $reqData);
//                                    $bodyDatas = $response->json(); // 如果响应是 JSON 格式，解析为数组或对象
//                                    if ($bodyDatas['code'] != '0000') {
////                                    dump('专业组error $schoolId:'.$schoolId .' $typeid: '. $typeid . ' $bodyDatas: ');
//                                        dump('返回异常：'.$localUrl);
//                                        sleep(6);
//                                        $zhuanye = [];
//                                    } else {
//                                        $zhuanye = $bodyDatas['data'];
//                                    }
//                                }


                                $tmp = [
                                    'school_id' => $schoolId,
                                    'year' => $year,
                                    'province_id' => $provinceid,
                                    'province_name' => $provinceData[$provinceid] ?? "",
                                    'local_type_id' => $typeid,
                                    'local_type_name' => $v['local_type_name'],
                                    'local_batch_id' => $v['local_batch_id'],
                                    'local_batch_name' => $v['local_batch_name'],
                                    'diff' => $v['diff'],
                                    'num' => $v['num'],
                                    'min' => $v['min'],
                                    'min_section' => $v['min_section'],
                                    'sg_info' => $v['sg_info'],
                                    'sg_name' => $v['sg_name'],
                                    'zslx_name' => $v['zslx_name'],
                                    'special_group_id' => $v['special_group'],
                                    'special_group' => json_encode($zhuanye, JSON_UNESCAPED_UNICODE),
                                    'all_data' => json_encode($v, JSON_UNESCAPED_UNICODE),
                                ];
                                $schoolProvincescoreData[] = $tmp;
                            }

                            $schoolProvincescore->insertMultiData($schoolProvincescoreData);

                        }
                    }

                    echo $schoolId . '-' . $userInfo['id'] . ' ';

                } catch (\Exception $e) {
                    echo $schoolId . '-' . $userInfo['id'] . ' ';
                    dump($e->getMessage());
                    sleep(10);
                }
            }
        });








    }

    public function handle222()
    {



        $school = new School();


        for ($i = 21; $i<= 148; $i ++){

            $url = "https://api.zjzw.cn/web/api/?keyword=&page=".$i."&province_id=&ranktype=&request_type=1&size=20&type=&uri=apidata/api/gkv3/school/lists&signsafe=d72360cd2d5143988b6dcf5e909b644c";
            $response = Http::withHeaders([
                'Content-Type' => 'application/json',
                'authority' => 'api.zjzw.cn',
            ])->post($url, []);

            $bodyData = $response->json(); // 如果响应是 JSON 格式，解析为数组或对象
            if($bodyData['code'] != '0000'){
                dd($bodyData);
            }

            $reqAllData = $bodyData['data']['item'];

            $insertData = [];
            foreach ($reqAllData as $key => $reqData){
                $data = [
                    'sid' => $reqData['school_id'],
                    'hightitle' => $reqData['hightitle'],
                    'name' => $reqData['name'],
                    'belong' => $reqData['belong'],
                    'province_id' => $reqData['province_id'],
                    'province_name' => $reqData['province_name'],
                    'city_id' => $reqData['city_id'],
                    'dual_class' => $reqData['dual_class'],
                    'dual_class_name' => $reqData['dual_class_name'],
                    'feyy' => $reqData['f211'],
                    'fjbw' => $reqData['f985'],
                    'level_name' => $reqData['level_name'],
                    'nature_name' => $reqData['nature_name'],
                    'tag_name' => $reqData['tag_name'],
                    'type_name' => $reqData['type_name'],
                    'central' => $reqData['central'],
//                    'xueke_rank_score' => $reqData['xueke_rank_score'],
                    'recommend_master_level' => $reqData['recommend_master_level'],
                    'all_data' => json_encode($reqData, JSON_UNESCAPED_UNICODE),
                ];

                $insertData[] = $data;
            }

            $school->insertMultiData($insertData);

            sleep(5);

            dump($i);
        }

    }






}



























































