<?php


namespace App\Console\Commands\WashData;


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

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

    /**
     * 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_migrate_test',
                'db_username'   => 'company_migrate_test',
                'db_password'   => '7dSTAAxa64AkHB8R'
            ]
        ];

        $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);

//        $dataCount = count($tables);
//
//        $this->info("总共有数据表：{$dataCount} 个");
//
//        $this->info('开始处理...');
//
//        $bar = $this->output->createProgressBar($dataCount);

        $tableName = 'kailin_question_chapter';

        $insertDataArray = [
            [
                'name'          => '法规',
                'parent_id'     => 1,
                'status'        => 0,
                'weight'        => 0,
                'level'         => 1,
                'created_id'    => 0,
                'updated_id'    => 0,
                'insert_time'   => time(),
                'update_time'   => time(),
            ]
        ];

        $needWashDataArray = [
            [
                'chapterName' => '中药综',
                'filePath'    => 'E:\\鸭题库数据初始化目录\\中药综'
            ]

        ];

        foreach ($needWashDataArray as $value) {
            $parentId = DB::connection('company')->table($tableName)->where('name', $value['chapterName'])->value('id');
            //获取路径下的子级文件夹名称
            $returnFiles = [];
            $this->getSubdirectories($value['filePath'], 0, $value['chapterName'], $returnFiles);
//dd($returnFiles);
            foreach ($returnFiles as $returnFile) {
                if ($returnFile['level'] == 1) {
                    if ($returnFile['parent'] == $value['chapterName']) {
                        $insertData = [
                            'name'          => $returnFile['name'],
                            'parent_id'     => $parentId,
                            'status'        => 0,
                            'weight'        => 0,
                            'level'         => $returnFile['level'] + 1,
                            'created_id'    => 0,
                            'updated_id'    => 0,
                            'insert_time'   => time(),
                            'update_time'   => time(),
                        ];
                        if (!DB::connection('company')->table($tableName)->where('name', $returnFile['name'])->exists()) {
                            DB::connection('company')->table($tableName)->insert($insertData);
                        }
                    }
                }

                $secondParentId = DB::connection('company')->table($tableName)->where('name', $returnFile['parent'])->value('id');
                if ($returnFile['level'] == 2) {
                    $insertData = [
                        'name'          => $returnFile['name'],
                        'parent_id'     => $secondParentId,
                        'status'        => 0,
                        'weight'        => 0,
                        'level'         => $returnFile['level'] + 1,
                        'created_id'    => 0,
                        'updated_id'    => 0,
                        'insert_time'   => time(),
                        'update_time'   => time(),
                    ];
                    DB::connection('company')->table($tableName)->insert($insertData);
                }

                $thirdParentId = DB::connection('company')->table($tableName)->where('name', $returnFile['parent'])->value('id');
                if ($returnFile['level'] == 3) {
                    $insertData = [
                        'name'          => $returnFile['name'],
                        'parent_id'     => $thirdParentId,
                        'status'        => 0,
                        'weight'        => 0,
                        'level'         => $returnFile['level'] + 1,
                        'created_id'    => 0,
                        'updated_id'    => 0,
                        'insert_time'   => time(),
                        'update_time'   => time(),
                    ];
                    DB::connection('company')->table($tableName)->insert($insertData);
                }

            }

            //dd($returnFiles);
        }



//        $parentId = DB::connection('company')->table($tableName)->where('level', 1)->pluck('id')->toArray();
//
//        dd($parentId);

        //DB::connection('company')->table($tableName)->insert($insertDataArray);

        $this->info('success~');

    }


//    function getSubdirectories($directory, $level = 0, &$result = []) {
//        // 打开目录
//        if (!is_dir($directory)) {
//            return; // 如果不是目录，直接返回
//        }
//
//        // 获取目录中的所有条目
//        $entries = scandir($directory);
//
//        // 遍历目录中的每个条目
//        foreach ($entries as $entry) {
//            // 跳过当前目录（.）和上级目录（..）
//            if ($entry === '.' || $entry === '..') {
//                continue;
//            }
//
//            // 构造完整的子目录路径
//            $subdir = $directory . DIRECTORY_SEPARATOR . $entry;
//
//            // 检查是否是目录
//            if (is_dir($subdir)) {
//                // 将目录名称和级数存储到结果数组中
//                $result[] = ['name' => $entry, 'level' => $level + 1];
//
//                // 递归调用，进入下一级目录
//                $this->getSubdirectories($subdir, $level + 1, $result);
//            }
//        }
//    }

//    function getSubdirectories($directory, $level = 0, $parentName = '', &$result = []) {
//        // 打开目录
//        if (!is_dir($directory)) {
//            return; // 如果不是目录，直接返回
//        }
//
//        // 获取目录中的所有条目
//        $entries = scandir($directory);
//
//        // 遍历目录中的每个条目
//        foreach ($entries as $entry) {
//            // 跳过当前目录（.）和上级目录（..）
//            if ($entry === '.' || $entry === '..') {
//                continue;
//            }
//
//            // 构造完整的子目录路径
//            $subdir = $directory . DIRECTORY_SEPARATOR . $entry;
//
//            // 检查是否是目录
//            if (is_dir($subdir)) {
//                // 将目录名称、级数和父级目录名称存储到结果数组中
//                $result[] = [
//                    'name' => $entry,
//                    'level' => $level + 1,
//                    'parent' => $parentName
//                ];
//
//                // 递归调用，进入下一级目录
//                $this->getSubdirectories($subdir, $level + 1, $entry, $result);
//            }
//        }
//    }
    function getSubdirectories($directory, $level = 0, $parentName = '', &$result = []) {
        // 打开目录
        if (!is_dir($directory)) {
            return; // 如果不是目录，直接返回
        }

        // 获取目录中的所有条目
        $entries = scandir($directory);

        // 遍历目录中的每个条目
        foreach ($entries as $entry) {
            // 跳过当前目录（.）和上级目录（..）
            if ($entry === '.' || $entry === '..') {
                continue;
            }

            // 构造完整的子目录路径
            $subdir = $directory . DIRECTORY_SEPARATOR . $entry;

            // 检查是否是目录
            if (is_dir($subdir)) {
                // 过滤掉目录名称中的数字
                $filteredName = preg_replace('/\d+/', '', $entry);

                // 将目录名称、级数和父级目录名称存储到结果数组中
                $result[] = [
                    'name' => $filteredName,
                    'level' => $level + 1,
                    'parent' => $parentName
                ];

                // 递归调用，进入下一级目录
                $this->getSubdirectories($subdir, $level + 1, $filteredName, $result);
            }
        }
    }


}