<?php

namespace App\Console\Commands\Test;

use App\Helper\Arr;
use App\Models\Com\Notify;
use App\Models\Devops\ServerConfig;
use App\Models\Devops\ServersIp;
use App\Models\Domain\DomainInfo;
use App\Models\Product\Keyword;
use App\Models\Project\Project;
use App\Services\BatchExportService;
use App\Services\ProjectServer;
use Illuminate\Console\Command;
use Symfony\Component\Process\Process;

class Temp extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'test_temp';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '临时脚本';

    /**
     * 关键词首字母
     * @author Akun
     * @date 2024/10/30 15:37
     */
    public function handle()
    {
        $projects = Project::where('id', '>', 52)->select(['id'])->orderBy('id', 'asc')->get();
        foreach ($projects as $project) {
            ProjectServer::useProject($project->id);

            //处理关键词首字母
            try {
                Keyword::select(['id', 'title', 'first_word'])->chunk(1000, function ($query) {
                    foreach ($query as $item) {
                        if ($item->first_word === null) {
                            $item->first_word = $this->getTitleFirstLetter($item->title);
                            $item->save();
                        }
                    }
                });
            } catch (\Exception $e) {
                $this->output($e->getMessage());
                continue;
            }


            $this->output('ID:' . $project->id . ',success');
        }
    }

    protected function getTitleFirstLetter($title)
    {
        $first = mb_strtolower(mb_substr($title, 0, 1, 'utf-8'), 'utf-8');
        if (in_array($first, ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"])) {
            $firstLetter = 0;
        } else {
            if (in_array($first, ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'])) {
                $rule = [
                    "a" => 1,
                    "b" => 2,
                    "c" => 3,
                    "d" => 4,
                    "e" => 5,
                    "f" => 6,
                    "g" => 7,
                    "h" => 8,
                    "i" => 9,
                    "j" => 10,
                    "k" => 11,
                    "l" => 12,
                    "m" => 13,
                    "n" => 14,
                    "o" => 15,
                    "p" => 16,
                    "q" => 17,
                    "r" => 18,
                    "s" => 19,
                    "t" => 20,
                    "u" => 21,
                    "v" => 22,
                    "w" => 23,
                    "x" => 24,
                    "y" => 25,
                    "z" => 26,
                ];
                $firstLetter = $rule[$first];
            } else {
                $firstLetter = 27;
            }
        }
        return $firstLetter;
    }


    /**
     * 获取指定服务器所有项目
     * @author Akun
     * @date 2024/09/30 17:01
     */
    public function handle3()
    {
        $server_id = 1;

        $server_ip_model = new ServersIp();

        $server_ip_ids = $server_ip_model->where('servers_id', $server_id)->get()->pluck('id')->toArray();

        $project_list = Project::select(['id', 'serve_id', 'title'])->whereIn('serve_id', $server_ip_ids)->get();

        $domain_model = new DomainInfo();
        $data = [];
        foreach ($project_list as $value) {
            $domain_info = $domain_model->read(['project_id' => $value->id, 'status' => 1], ['id', 'domain']);
            if (!$domain_info) {
                //过滤未绑定正式域名的项目
                continue;
            }
            $domain = $domain_info['domain'];

            $data[] = [
                $value->id,
                $value->title,
                $domain
            ];
        }
        $map = ['项目id', '名称', '域名'];
        if ($data) {
            $table = new BatchExportService("240云服务器项目");
            $file = $table->head($map)->data($data)->save();
            if (!$file) {
                $this->output('文件生成失败,请重试');
            } else {
                $this->output('export success');
            }
        } else {
            $this->output('no data');
        }
    }


    /**
     * 检查不在所属服务器解析上的域名
     * @author Akun
     * @date 2024/09/26 10:48
     */
    public function handle2()
    {
        $server_id = 15;

        $server_ip_model = new ServersIp();

        $server_ip_ids = $server_ip_model->where('servers_id', $server_id)->get()->pluck('id')->toArray();

        $project_list = Project::select(['id', 'serve_id', 'title'])->whereIn('serve_id', $server_ip_ids)->get();

        $domain_model = new DomainInfo();
        $data = [];
        foreach ($project_list as $value) {
            $domain_info = $domain_model->read(['project_id' => $value->id, 'status' => 1], ['id', 'domain']);
            if (!$domain_info) {
                //过滤未绑定正式域名的项目
                continue;
            }
            $domain = $domain_info['domain'];

            $check = dns_get_record($domain, DNS_A);
            $ip = $check[0]['ip'] ?? '';
            $ip_info = $server_ip_model->read(['ip' => $ip]);
            if ($ip_info === false || $ip_info['servers_id'] != $server_id) {
                $data[] = [
                    $value->id,
                    $value->title,
                    $domain,
                    $ip,
                    $ip_info ? $ip_info['servers_id'] : '',
                ];
            }
        }
        $map = ['项目id', '名称', '域名', 'IP', '服务器ID',];
        if ($data) {
            $table = new BatchExportService("美服2项目解析未在当前服务器项目");
            $file = $table->head($map)->data($data)->save();
            if (!$file) {
                $this->output('文件生成失败,请重试');
            } else {
                $this->output('export success');
            }
        } else {
            $this->output('no data');
        }
    }

    /**
     * 创建所有amp站页面生成任务
     * @author Akun
     * @date 2024/09/26 10:48
     */
    public function handle1()
    {
        $notify_model = new Notify();
        $project_model = new Project();
        $serve_ip_model = new ServersIp();

        $domain_list = DomainInfo::where('status', 1)->where('amp_status', 1)->get();

        foreach ($domain_list as $domain_info) {
            $project_id = $domain_info->project_id;
            $domain = $domain_info->domain;

            $this->output('项目id:' . $project_id . ',start');

            //获取项目所在服务器
            $project_info = $project_model->read(['id' => $project_id], ['serve_id']);
            if (!$project_info) {
                $this->output('未查询到项目数据');
            }
            $serve_ip_info = $serve_ip_model->read(['id' => $project_info['serve_id']], ['servers_id']);
            if (!$serve_ip_info) {
                $this->output('未查询到服务器数据');
            }
            $servers_id = $serve_ip_info['servers_id'];

            if ($servers_id == ServerConfig::SELF_SITE_ID) {
                //自建站服务器:如果项目已经上线,不请求C端接口,数据直接入库
                //判断是否已有更新进行中
                $data = [
                    'project_id' => $project_id,
                    'type' => 3,
                    'route' => 1,
                    'server_id' => ServerConfig::SELF_SITE_ID,
                    'status' => ['!=', Notify::STATUS_FINISH_SITEMAP]
                ];
                $notify = $notify_model->read($data, ['id']);

                if (!$notify) {
                    $domain_array = parse_url($domain);
                    $host = $domain_array['host'] ?? $domain_array['path'];
                    $host_array = explode('.', $host);
                    if (count($host_array) <= 2) {
                        array_unshift($host_array, 'm');
                    } else {
                        $host_array[0] = 'm';
                    }
                    $domain = implode('.', $host_array);

                    $data['data'] = Arr::a2s(['domain' => $domain, 'url' => [], 'language' => []]);
                    $data['status'] = Notify::STATUS_INIT;
                    $notify_model->add($data);
                }
            } else {
                //其他服务器:请求对应C端接口
                $c_url = $domain . '/api/update_page/?project_id=' . $project_id . '&type=3';
                $re = http_get($c_url);
                $this->output($re['message'] ?? '');
            }
            $this->output('项目id:' . $project_id . ',end');
        }
    }

    public function output($msg)
    {
        echo $msg . PHP_EOL;
    }
}