<?php


namespace App\Console\Commands\WashData;


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

class InitQuestionTopicCommand extends Command
{

    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'washdata:initTopic';

    /**
     * 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';

        $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'];

//            if (strpos($chapterName, '节')) {
//                $chapterName = explode('节', $chapterName)[1];
//                $chapterName = trim($chapterName);
//                //通过chapterName获取chapterId
//                $chapterId  = DB::connection('company')->table($tableNameChapter)->where('name', 'like', '%' . $chapterName . '%')->value('id');
//            } else {
//                //通过chapterName获取chapterId
//                $chapterId  = DB::connection('company')->table($tableNameChapter)->where('name', $chapterName)->value('id');
//            }

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

            foreach ($data['data'] as $value) {

                //题目类型
                $style = $value['style'];
                //$styleName = $this->getStyleName($style);
                //dd($styleName);
                //题目
//                $title = '';
//                if (!empty($value['exerciseQuestionsTopicPo'])) {
//                    $title  = $value['exerciseQuestionsTopicPo']['content'] . "\r\n";
//                }
//                $title = $title  . $value['title'];
                $title  = $value['title'];
                $questions_ex = null;
                if (!empty($value['exerciseQuestionsTopicPo'])) {
                    $questions_ex = $value['exerciseQuestionsTopicPo']['content'];
                }

                //解析
                $explain = $value['explain'];

                //准确率
                $accuracy = $value['accuracy'];

                //
                $correctAnswerStr = ''; //正确选项Str
                $correctAnswers = [];  //正确答案数据
                $selectAContent = '';
                $selectBContent = '';
                $selectCContent = '';
                $selectDContent = '';
                $selectEContent = '';

                //考点
                $examPointStr = '';
                $examPointNames = [];
                $examPoints = $value['points'];
                foreach ($examPoints as $examPoint) {
                    $examPointNames [] = $examPoint['name'];
                }
                $examPointStr = implode(',', $examPointNames);//考点
                //dd($examPointStr);


                //$answerFlag = false;

//                $answer = $data['answer'];
//
//                if (in_array($answer, $answerArray)) {
//                    $answerFlag = true; //获取answer成功
//                }


                $questionCount = $value['questionCount'] ; //选项数量
                //获取选项：
                $questionsOptionsPos = $value['questionsOptionsPos'];

                foreach ($questionsOptionsPos as $key => $item) {
                    //配伍题的选项在$questions_ex 答案不能混淆
                    //解析中包含A、B、C、D、E的时候也不能混淆
                    if (strpos($explain, 'A') || strpos($explain, 'B') || strpos($explain, 'C') || strpos($explain, 'D') || strpos($explain, 'E')) {
                        if ($key == 0 && $key <= $questionCount - 1) {
                            $selectAContent = $item['option'];
                            if ($item['isTrue'] == true) {
                                $correctAnswers [] = 'A';
                            }
                        } elseif ($key == 1 && $key <= $questionCount - 1) {
                            $selectBContent = $item['option'];
                            if ($item['isTrue'] == true) {
                                $correctAnswers [] = 'B';
                            }
                        } elseif ($key == 2 && $key <= $questionCount - 1) {
                            $selectCContent = $item['option'];
                            if ($item['isTrue'] == true) {
                                $correctAnswers [] = 'C';
                            }
                        } elseif ($key == 3 && $key <= $questionCount - 1) {
                            $selectDContent = $item['option'];
                            if ($item['isTrue'] == true) {
                                $correctAnswers [] = 'D';
                            }
                        } elseif ($key == 4 && $key <= $questionCount - 1) {
                            $selectEContent = $item['option'];
                            if ($item['isTrue'] == true) {
                                $correctAnswers [] = 'E';
                            }
                        }
                    } else {
                        if ($style == 6) {
                            if ($key == 0 && $key <= $questionCount - 1) {
                                $selectAContent = $item['option'];
                                if ($item['isTrue'] == true) {
                                    $correctAnswers [] = 'A';
                                }
                            } elseif ($key == 1 && $key <= $questionCount - 1) {
                                $selectBContent = $item['option'];
                                if ($item['isTrue'] == true) {
                                    $correctAnswers [] = 'B';
                                }
                            } elseif ($key == 2 && $key <= $questionCount - 1) {
                                $selectCContent = $item['option'];
                                if ($item['isTrue'] == true) {
                                    $correctAnswers [] = 'C';
                                }
                            } elseif ($key == 3 && $key <= $questionCount - 1) {
                                $selectDContent = $item['option'];
                                if ($item['isTrue'] == true) {
                                    $correctAnswers [] = 'D';
                                }
                            } elseif ($key == 4 && $key <= $questionCount - 1) {
                                $selectEContent = $item['option'];
                                if ($item['isTrue'] == true) {
                                    $correctAnswers [] = 'E';
                                }
                            }
                        } else {

                            if ($key == 0 && $key <= $questionCount - 1) {
                                $selectCContent = $item['option'];
                                if ($item['isTrue'] == true) {
                                    $correctAnswers [] = 'C';
                                }
                            } elseif ($key == 1 && $key <= $questionCount - 1) {
                                $selectDContent = $item['option'];
                                if ($item['isTrue'] == true) {
                                    $correctAnswers [] = 'D';
                                }
                            } elseif ($key == 2 && $key <= $questionCount - 1) {
                                $selectAContent = $item['option'];
                                if ($item['isTrue'] == true) {
                                    $correctAnswers [] = 'A';
                                }
                            } elseif ($key == 3 && $key <= $questionCount - 1) {
                                $selectBContent = $item['option'];
                                if ($item['isTrue'] == true) {
                                    $correctAnswers [] = 'B';
                                }
                            } elseif ($key == 4 && $key <= $questionCount - 1) {
                                $selectEContent = $item['option'];
                                if ($item['isTrue'] == true) {
                                    $correctAnswers [] = 'E';
                                }
                            }
                        }
                    }
                }
                sort($correctAnswers);
                $correctAnswerStr = implode(',', $correctAnswers); //正确答案
                //dd($correctAnswerStr);

                if ($style == 6) {
                    $selectAContent = '';
                    $selectBContent = '';
                    $selectCContent = '';
                    $selectDContent = '';
                    $selectEContent = '';
                }

                $insertData = [
                    'title'     => $title,
                    'style'     => $style,
                    'select_a'  => $selectAContent,
                    'select_b'  => $selectBContent,
                    'select_c'  => $selectCContent,
                    'select_d'  => $selectDContent,
                    'select_e'  => $selectEContent,
                    'question_count'    => $questionCount,
                    'questions_ex'      => $questions_ex,
                    'explain'           => $explain,
                    'correct_answer'    => $correctAnswerStr,
                    'accuracy'          => $accuracy,
                    'chapter_id'        => $chapterId,
                    'point_id'          => 0,
                    'insert_time'       => time(),
                    'update_time'       => time()
                ];

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

//                $exportData = [];
//
//                $exportData['style'] = $styleName;
//                $exportData['title'] = $title;
//
//                $exportData['selectA'] =  $selectAContent;
//                $exportData['selectB'] =  $selectBContent;
//                $exportData['selectC'] =  $selectCContent;
//                $exportData['selectD'] =  $selectDContent;
//                $exportData['selectE'] =  $selectEContent;
//                $exportData['answer']  = $correctAnswerStr;
//                $exportData['explain'] = $explain;
//                $exportData['accuracy'] = $accuracy;
//                $exportData['point']    = $examPointStr;
//                $this->putRow($exportData);

            }


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

}