<?php


namespace App\Console\Commands\WashData;


use Illuminate\Console\Command;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;

class InitQuestionTopicPointCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'washdata:initTopicPoint';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '题库关联考点初始化';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        //连接数据库

        $dataBaseInfos = [
            //saas-company
            'company' => [
                'host' => '39.108.116.125',
                'port' => 3306,
                'db_name' => 'company_61',
                'db_username' => 'company_61',
                'db_password' => 'N35fYCPHziAAGd4L'
            ]
        ];

        $companyConnectionConfig = [
            'driver' => 'mysql',
            'host' => $dataBaseInfos['company']['host'],
            'port' => $dataBaseInfos['company']['port'],
            'database' => $dataBaseInfos['company']['db_name'],
            'username' => $dataBaseInfos['company']['db_username'],
            'password' => $dataBaseInfos['company']['db_password'],
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'unix_socket' => env('DB_SOCKET', ''),
            'prefix' => env('DB_PREFIX', ''),
            'strict' => false,
            'sticky' => true,
            'engine' => null,
            'options' => [],
        ];

        Config::set("database.connections.company", $companyConnectionConfig);

        $tableName = 'kailin_question_topic';

        $tableNamePoint = 'kailin_question_point';

        $directory = "E:\\鸭题库数据初始化题目\\中药综";

        $needExchangeTopics = $this->getFilesRecursively($directory);
//dd($needExchangeTopics);

        $dataCount = count($needExchangeTopics);

        $this->info('开始转换');
        $this->info("总共有：{$dataCount} 节");
        $bar = $this->output->createProgressBar($dataCount);

        foreach ($needExchangeTopics as $needExchangeTopic) {

            $data = file_get_contents($needExchangeTopic['data']);

            $data = json_decode($data, true);

            foreach ($data['data'] as $value) {
                $title  = $value['title'];

                $topicId    = DB::connection('company')->table($tableName)->where('title', $title)->value('id');

                if ($topicId) {
                    $examPointNames = [];
                    $examPoints = $value['points'];
                    foreach ($examPoints as $examPoint) {
                        $examPointNames [] = $examPoint['name'];
                    }
                    $pointIds = [];
                    foreach ($examPointNames as $examPointName) {
                        //通过考点名称,获取考点的id
                        $pointId = DB::connection('company')->table($tableNamePoint)->where('name', $examPointName)->value('id');

                        if (!empty($pointId)) {
                            $pointIds [] = $pointId;
                        }
                    }

                    $pointStr = implode(',', $pointIds);

                    DB::connection('company')->table($tableName)->where('id', $topicId)->update(['point_id' => $pointStr]);

                }

                //通过title获取到kailin_question_topic的id
            }

            $bar->advance();

        }

        $bar->finish();

        $this->info('');
        $this->info('初始化完成');
    }

    public function getFilesRecursively($directory) {
        // 检查目录是否存在
        if (!is_dir($directory)) {
            return "目录不存在";
        }

        // 获取目录下的所有文件和子目录
        $files = scandir($directory);

        // 过滤掉 "." 和 ".."（当前目录和上一级目录）
        $files = array_diff($files, array('.', '..'));

        $result = [];
        foreach ($files as $file) {
            // 拼接完整的文件路径
            $filePath = $directory . DIRECTORY_SEPARATOR . $file;

            // 判断是否为文件
            if (is_file($filePath)) {
                // 过滤掉文件名中包含“数据源”的文件
                if (strpos($file, '数据源') === false) {
                    // 获取文件名的主名称（去除.txt后缀）
                    $fileNameWithoutExtension = pathinfo($file, PATHINFO_FILENAME);
                    // 获取文件所在的目录路径
                    $fileDir = dirname($filePath);

                    // 去除文件名中的数字（如1, 2, 3...10, 11, 12等）
                    // 去除文件名中的数字和连字符（-）
                    $fileNameWithoutNumbers = preg_replace('/\d+/', '', $fileNameWithoutExtension);
                    // 获取文件的大小
                    $fileSize = filesize($filePath);
                    $result[] = [
                        'fileName' => $fileNameWithoutNumbers, // 文件名（去除.txt后缀）
                        'data' => $filePath, // 完整路径
                        'directory' => $fileDir, // 文件所在目录
                        'size' => $fileSize // 文件大小
                    ];
                }
            } elseif (is_dir($filePath)) {
                // 如果是目录，则递归调用
                $result = array_merge($result, $this->getFilesRecursively($filePath));
            }
        }

        return $result;
    }

}