<?php
// +----------------------------------------------------------------------
// | likeadmin快速开发前后端分离管理后台（PHP版）
// +----------------------------------------------------------------------
// | 欢迎阅读学习系统程序代码，建议反馈是我们前进的动力
// | 开源版本可自由商用，可去除界面版权logo
// | gitee下载：https://gitee.com/likeshop_gitee/likeadmin
// | github下载：https://github.com/likeshop-github/likeadmin
// | 访问官网：https://www.likeadmin.cn
// | likeadmin团队 版权所有 拥有最终解释权
// +----------------------------------------------------------------------
// | author: likeadminTeam
// +----------------------------------------------------------------------

namespace app\adminapi\logic\training;


use app\common\model\training\TrainingQuestions;
use app\common\logic\BaseLogic;
use think\facade\Db;


/**
 * TrainingQuestions逻辑
 * Class TrainingQuestionsLogic
 * @package app\adminapi\logic
 */
class TrainingQuestionsLogic extends BaseLogic
{

    public static $select_value = [];
    /**
     * @notes 添加
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2025/02/14 13:49
     */
    public static function add(array $params): bool
    {
        if($params['subclass']) $params['subclass'] = end($params['subclass']);
        Db::startTrans();
        try {
            TrainingQuestions::create([
                'training_course_id' => $params['training_course_id'],
                'title' => $params['title'],
                'question_type' => $params['question_type'],
                //'question_selects' => $params['question_selects'],
                'question_selects' => self::configureReservedField($params['question_selects']??[]),
                'question_answer' => self::$select_value?implode(',',self::$select_value):'',
                'question_analysis' => $params['question_analysis'],
                'subclass' => $params['subclass']??0,
            ]);

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 编辑
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2025/02/14 13:49
     */
    public static function edit(array $params): bool
    {

        Db::startTrans();
        try {
            TrainingQuestions::where('id', $params['id'])->update([
                'training_course_id' => $params['training_course_id'],
                'title' => $params['title'],
                'question_type' => $params['question_type'],
                'question_selects' => json_encode(self::configureReservedField($params['question_selects']??[])),
                'question_answer' => self::$select_value?implode(',',self::$select_value):'',
                'question_analysis' => $params['question_analysis'],
            ]);

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    /**
     * @notes 删除
     * @param array $params
     * @return bool
     * @author likeadmin
     * @date 2025/02/14 13:49
     */
    public static function delete(array $params): bool
    {
        return TrainingQuestions::destroy($params['id']);
    }


    /**
     * @notes 获取详情
     * @param $params
     * @return array
     * @author likeadmin
     * @date 2025/02/14 13:49
     */
    public static function detail($params): array
    {
        return TrainingQuestions::findOrEmpty($params['id'])->toArray();
    }

    public static function configureReservedField($data): array
    {
        $select_value = [];
        foreach ($data as $key => &$item) {
            $data[$key]['block_key'] = $key+1;
            if($item['select_value']){
                $select_value[] = $data[$key]['block_key'];
                $item['select_value'] = \true;
            }else{
                $item['select_value'] = \false;
            }
        }
        self::$select_value = $select_value;
        return $data??[];
    }

    public static function questionImport($questions)
    {
        $newQuestionArray = [];
        $time = time();
        foreach ($questions as $key => $question) {
            $newQuestionArray[$key]['title'] = $question['title'];
            $newQuestionArray[$key]['question_analysis'] = '暂无';
            $newQuestionArray[$key]['subclass'] = self::getSubclass($question['subclass']??'');
            $newQuestionArray[$key]['create_time'] = $time;
            $newQuestionArray[$key]['update_time'] = $time;

            $typeAnswer = self::getQuestionTypeAnswer($question['question_answer']);
            $newQuestionArray[$key]['question_type'] = $typeAnswer['question_type']??0;
            $newQuestionArray[$key]['question_answer'] = $typeAnswer['question_answer']??'';
            $newQuestionArray[$key]['question_selects'] = self::getQuestionSelects($question,$typeAnswer['question_answer'])??'';

        }

        Db::startTrans();
        try {

            TrainingQuestions::insertAll($newQuestionArray);

            Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
            self::setError($e->getMessage());
            return false;
        }
    }


    public static function getSubclass($subclass)
    {
        if(empty($subclass)) return 0;
        if(is_numeric($subclass)) return $subclass;
        return \app\common\model\goods_category\GoodsCategory::where('name', $subclass)->value('id')??0;
    }

    public static function getQuestionTypeAnswer($answer)
    {
        // 统一转大写
        $answer = strtoupper($answer);
        $optionMap = [
            'A' => 1,
            'B' => 2,
            'C' => 3,
            'D' => 4,
            'E' => 5,
            'F' => 6
        ];
        $cleanedAnswer = preg_replace('/[^A-Z]/', '', $answer);
        if (strlen($cleanedAnswer) === 0) {
            $question_type = 0;
        } elseif (strlen($cleanedAnswer) === 1) {
            $question_type = 1;
        } else {
            $question_type = 2;
        }
        $newArray = [];
        for ($i = 0; $i < strlen($cleanedAnswer); $i++) {
            $letter = $cleanedAnswer[$i];
            if (isset($optionMap[$letter])) {
                $newArray[] = $optionMap[$letter];
            }
        }
        $question_answer = implode(',', $newArray);
        return ['question_type'=>$question_type,'question_answer'=>$question_answer];
    }
    public static function getQuestionSelects($options_data,$question_answer)
    {
        $keyArr = [
                "options_a" => "0",
                "options_b" => "1",
                "options_c" => "2",
                "options_d" => "3",
                "options_e" => "4",
                "options_f" => "5"
        ];
        $res = [];
        foreach ($options_data as $key => $item) {
            isset($keyArr[$key]) && $res[$keyArr[$key]] = $item;
        }

        $arr = array_values($res);
        $answerArr = explode(',', $question_answer);
        $data = [];
        foreach ($arr as $key => $name) {
            $data[$key]['block_key'] = $key+1;
            $data[$key]['name'] = trim($name);
            if(in_array($data[$key]['block_key'],$answerArr)){
                $data[$key]['select_value'] = \true;
            }else{
                $data[$key]['select_value'] = \false;
            }
        }
        return json_encode($data);
    }



}