<?php


namespace App\Console\Commands\WashData;


use GuzzleHttp\Client as HttpClient;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

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

    /**
     * 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_point';
        $tableNameChapterPoint      = 'kailin_question_chapter_point';
        $tableNameChapter           = 'kailin_question_chapter';



        $directory = "E:\\鸭题库数据初始化考点\\中药综\\13第十三章 中药用药安全";

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

        $dataCount = count($needExchangeTopics);

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

        foreach ($needExchangeTopics as $needExchangeTopic) {
            $chapterName =  $needExchangeTopic['fileName'];
            $chapterId  = DB::connection('company')->table($tableNameChapter)->where('name', $chapterName)->value('id');

            $this->info('获取章节id =' . $chapterId);
            if (empty($chapterId)) {
                $this->info('获取章节id失败!');
                $this->info('章节名称='.$chapterName);
                return ;
            }

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

            $data = json_decode($data, true);

            if (empty($data['data'])) {
                continue;
            }

            $pointIds = [];

            foreach ($data['data'] as $value) {
                $pointIds [] = $value['pointId'];
            }
            //dd($pointIds);

            foreach ($pointIds as $pointId) {
                $http = new HttpClient(['verify' => false]);
                //https://app.yatiku.com/youxue/api/v2/back/exercise/getPointInfo?pointId=898
                $pointApi = 'https://app.yatiku.com/youxue/api/v2/back/exercise/getPointInfo?' . http_build_query([
                        'pointId' => $pointId
                    ]);

                //获取考点信息：
                $pointResult = $http->get($pointApi);

                $pointInfos = json_decode($pointResult->getBody()->getContents(), JSON_UNESCAPED_UNICODE);

                $pointInfos = $pointInfos['data'];

                $stars = 0;
                $difficultyStars = 0;

                if (isset($pointInfos['stars']) && !empty($pointInfos['stars'])) {
                    $stars = $pointInfos['stars'];
                }

                if (isset($pointInfos['difficultyStars']) && !empty($pointInfos['difficultyStars'])) {
                    $difficultyStars = $pointInfos['difficultyStars'];
                }

//dd($pointInfos['difficultyStars']);
                $insertData['name']                 = isset($pointInfos['name']) ? $pointInfos['name'] : '' ;
                $insertData['describe']             = isset($pointInfos['describe']) ? $pointInfos['describe'] : '';
                $insertData['detail']               = isset($pointInfos['detail']) ? $pointInfos['detail'] : '';
                $insertData['video']                = !empty($pointInfos['video']) ? $pointInfos['video'] : '';
                $insertData['image']                = '';
                $insertData['voice']                = '';
                $insertData['status']               = 0;
                $insertData['stars']                = $stars;
                $insertData['difficultyStars']      = $difficultyStars;
                $insertData['created_id']           = '';
                $insertData['updated_id']           = '';
                $insertData['insert_time']          = time();
                $insertData['update_time']          = time();
//dd($insertData);
                $returnId = DB::connection('company')->table($tableName)->insertGetId($insertData);


                $insertChapterPoint['point_id']     = $returnId;
                $insertChapterPoint['chapter_id']   = $chapterId;
                $insertChapterPoint['insert_time']  = time();
                $insertChapterPoint['update_time']  = time();

                //$tableNameChapterPoint

                DB::connection('company')->table($tableNameChapterPoint)->insert($insertChapterPoint);

                //dd($insertData);
            }

            $bar->advance();
        }

        $bar->finish();
        $this->info('success!');
    }

    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;
    }

}