package com.education.api.controller.admin.education;

import com.education.auth.annotation.Logical;
import com.education.auth.annotation.RequiresPermissions;
import com.education.business.parser.ExcelQuestionImportResult;
import com.education.business.parser.QuestionImportResult;
import com.education.business.parser.TxtQuestionImportResult;
import com.education.business.service.education.QuestionInfoService;
import com.education.business.service.education.ai.question.QuestionWorkFlowRunner;
import com.education.common.annotation.Param;
import com.education.common.annotation.ParamsType;
import com.education.common.annotation.ParamsValidate;
import com.education.common.base.BaseController;
import com.education.common.config.OssProperties;
import com.education.common.utils.ObjectUtils;
import com.education.common.utils.Result;
import com.education.common.utils.ResultCode;
import com.education.model.dto.QuestionInfoDto;
import com.education.model.entity.QuestionInfo;
import com.education.model.request.PageParam;
import com.education.model.request.QuestionInfoQuery;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 试题管理接口
 * @author zengjintao
 * @version 1.0
 * @create_at 2020/11/19 10:45
 */
@RestController
@RequestMapping("/system/question")
public class QuestionInfoController extends BaseController {

    @Resource
    private QuestionInfoService questionInfoService;
    private final Logger logger = LoggerFactory.getLogger(QuestionInfoController.class);

    @Resource
    private OssProperties ossProperties;

    @Resource
    QuestionWorkFlowRunner questionWorkFlowRunner;

//    public static void main(String[] args) {
//        String filepath = "D:\\home\\words\\2025\\03\\13\\145804-ae8aec8e6f9747f38122ca25e347e956.pdf";
//        String question = "根据文件出1道选择题, 请把题干放到title属性，选项插入到options数组属性内，答案放到anwser属性。例如：{title:'题干',options:[{'label':'A', text:'1'}],answer:'B'}这样的格式，输出JSON文本";//requestData.getQuestion();
//        Map<String, Object> result = null;
//
//        // 处理逻辑，例如判断是否为空
//        if (filepath == null || filepath.isEmpty()) {
//            filepath = "默认文件路径";
//        }
//        if (question == null || question.isEmpty()) {
//            question = "默认问题";
//        }
//
//        try {
//            // 1. 指定 Python 脚本路径
//            String pythonScript = "D:\\home\\test.py";//ossProperties.getBucketName()+"test.py";
//
//            // 2. 构造 JSON 数据
//            Map<String, String> data = new HashMap<>();
//            data.put("filepath", filepath);
//            data.put("question", question);
//
//            // 3. 使用 Gson 生成 JSON 字符串
//            Gson gson = new Gson();
//            String jsonInput = gson.toJson(data);
//
//            // 4. 启动 Python 进程
//            ProcessBuilder processBuilder = new ProcessBuilder("python", pythonScript);
//            processBuilder.environment().put("PYTHONIOENCODING", "UTF-8");
//            processBuilder.redirectErrorStream(true);
//            Process process = processBuilder.start();
//
//            // 5. 传递 JSON 参数
//            OutputStream os = process.getOutputStream();
//            os.write(jsonInput.getBytes(StandardCharsets.UTF_8));
//            os.flush();
//            os.close();
//
//            // 6. 读取 Python 输出
//            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8));
//            StringBuilder output = new StringBuilder();
//            String line;
//            while ((line = reader.readLine()) != null) {
//                output.append(line).append("\n");
//            }
////            System.out.println("Python 返回1: " + output.toString().trim());
//            // 7. 解析 Python 返回的 JSON 数据
//            String jsonOutput = output.toString();
//            System.out.println("Python 返回1: " + jsonOutput);
//            String[] split = jsonOutput.split("\n");
//            String s = split[split.length - 1];
//            // 8. 让 Gson 解析 JSON，并正确显示中文
//            result = gson.fromJson(s, Map.class);
//            System.out.println("解析后的结果: " + result);
//
//            // 8. 等待 Python 进程结束
//            int exitCode = process.waitFor();
//            System.out.println("Python 进程退出码: " + exitCode);
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }

    @PostMapping("/process")
    public Response processFile(@RequestBody RequestData requestData) {

        // 获取前端传来的数据
        String filepath = requestData.getFilepath();  //"D:\\home\\words\\2025\\03\\13\\145804-ae8aec8e6f9747f38122ca25e347e956.pdf";
        String question = requestData.getQuestion(); //"根据文件出1道选择题, 请把题干放到title属性，选项插入到options数组属性内，答案放到anwser属性。例如：{title:'题干',options:[{'label':'A', text:'1'}],answer:'B'}这样的格式，输出JSON文本";//requestData.getQuestion();
        Map<String, Object> result = null;

        // 处理逻辑，例如判断是否为空
        if (filepath == null || filepath.isEmpty()) {
            filepath = "";
        }
        if (question == null || question.isEmpty()) {
            question = "";
        }


        //设置出题提示词
        questionWorkFlowRunner.setPrompt(question);

        //设置上下文
        questionWorkFlowRunner.getCollector();
        questionWorkFlowRunner.run();

        filepath = ossProperties.getBucketName() + filepath;

        try {
            // 1. 指定 Python 脚本路径
            String pythonScript = ossProperties.getBucketName()+"question.py";//"D:\\home\\test.py";

            // 2. 构造 JSON 数据
            Map<String, String> data = new HashMap<>();
            data.put("filepath", filepath);
            data.put("question", question);

            // 3. 使用 Gson 生成 JSON 字符串
            Gson gson = new Gson();
            String jsonInput = gson.toJson(data);

            // 4. 启动 Python 进程
            ProcessBuilder processBuilder = new ProcessBuilder("python", pythonScript);
            processBuilder.environment().put("PYTHONIOENCODING", "UTF-8");
            processBuilder.redirectErrorStream(true);
            Process process = processBuilder.start();

            // 5. 传递 JSON 参数
            OutputStream os = process.getOutputStream();
            os.write(jsonInput.getBytes(StandardCharsets.UTF_8));
            os.flush();
            os.close();

            // 6. 读取 Python 输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8));
            StringBuilder output = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                output.append(line).append("\n");
            }
//            System.out.println("Python 返回1: " + output.toString().trim());
            // 7. 解析 Python 返回的 JSON 数据
            String jsonOutput = output.toString();
            System.out.println("Python 返回1: " + jsonOutput);
            String[] split = jsonOutput.split("\n");
            String s = split[split.length - 1];
            // 8. 让 Gson 解析 JSON，并正确显示中文
            result = gson.fromJson(s, Map.class);
            System.out.println("解析后的结果: " + result);

            // 8. 等待 Python 进程结束
            int exitCode = process.waitFor();
            System.out.println("Python 进程退出码: " + exitCode);

        } catch (Exception e) {
            e.printStackTrace();
        }

        // 构造返回信息
        return new Response("接收到的数据", result);
    }

    // 定义请求数据的 JavaBean
   static class RequestData {
        private String filepath;
        private String question;

        public String getFilepath() {
            return filepath;
        }

        public void setFilepath(String filepath) {
            this.filepath = filepath;
        }

        public String getQuestion() {
            return question;
        }

        public void setQuestion(String question) {
            this.question = question;
        }
    }

    // 定义返回数据的 JavaBean
  static  class Response {
        private String message;
        private Map<String, Object> content;


        public Response(String message, Map<String, Object> content) {
            this.message = message;
            this.content = content;

        }
        public String getMessage() {
            return message;
        }

        public Map<String, Object> getContent() {
            return content;
        }

    }

    /**
     * 试题列表
     * @param pageParam
     * @param questionInfoQuery
     * @return
     */
    @GetMapping
    //@RequiresPermissions("system:question:list")
    public Result list(PageParam pageParam, QuestionInfoQuery questionInfoQuery) {
        return Result.success(questionInfoService.selectPageList(pageParam, questionInfoQuery));
    }

    /**
     * 添加或修改试题
     * @param questionInfoDto
     * @return
     */
    @PostMapping("saveOrUpdate")
    //@RequiresPermissions(value = {"system:question:save", "system:question:update"}, logical = Logical.OR)
    @ParamsValidate(params = {
        @Param(name = "schoolType", message = "请选择所属阶段"),
        @Param(name = "gradeInfoId", message = "请选择所属年级"),
        @Param(name = "subjectId", message = "请选择所属科目"),
        @Param(name = "questionType", message = "请选择试题类型"),
        @Param(name = "content", message = "请输入试题内容"),
        @Param(name = "answer", message = "请输入试题答案")
    }, paramsType = ParamsType.JSON_DATA)
    public Result saveOrUpdate(@RequestBody QuestionInfoDto questionInfoDto) {
        return Result.success(questionInfoService.saveOrUpdateQuestionInfo(questionInfoDto));
    }

    @PostMapping("saveQuestionInfoDtos")
    public Result saveQuestionInfoDtos(@RequestBody JsonNode jsonArray) throws JsonProcessingException {
        List<QuestionInfoDto> questionInfoDtos = new ArrayList<>();
        if (jsonArray.isArray()) {
            QuestionInfoDto questionInfoDto = null;
            for (JsonNode jsonObject : jsonArray) {
                questionInfoDto = new QuestionInfoDto();
                // 处理每个 JSON 对象
                String title = jsonObject.get("title").asText();
                questionInfoDto.setContent(title);
                JsonNode optionsNode = jsonObject.get("options");
                if (optionsNode.isArray()) {
                   /* for (JsonNode option : optionsNode) {
                        String label = option.get("label").asText();
                        String text = option.get("text").asText();
                        System.out.println("选项标签: " + label + ", 选项文本: " + text);
                    }*/
                    ObjectMapper objectMapper = new ObjectMapper();
                    questionInfoDto.setOptions(objectMapper.writeValueAsString(optionsNode).replace("text","option_name"));

                }
                String answer = jsonObject.get("answer").asText();
                int subjectId = jsonObject.get("subjectId").asInt();
                int gradeId = jsonObject.get("gradeId").asInt();
                int schoolType = jsonObject.get("schoolType").asInt();
                JsonNode questionTypeJson = jsonObject.get("questionType");
                if(questionTypeJson == null || questionTypeJson.isEmpty()) {
                    questionInfoDto.setQuestionType(1);
                }else {
                    questionInfoDto.setQuestionType(questionTypeJson.asInt());

                }

                questionInfoDto.setAnswer(answer);
                questionInfoDto.setSubjectId(subjectId);
                questionInfoDto.setGradeInfoId(gradeId);
                questionInfoDto.setSchoolType(schoolType);
                questionInfoDtos.add(questionInfoDto);
            }
        }else {
            return Result.success(new ResultCode(ResultCode.FAIL, "数据格式错误"));
        }
        List<String> emptyFields = validateQuestionInfoDtos(questionInfoDtos);
        if (emptyFields.isEmpty()) {
            // 调用服务层方法处理 QuestionInfoDto 列表
            return Result.success(questionInfoService.saveQuestionInfoList(questionInfoDtos));
        } else {
            return Result.success(new ResultCode(ResultCode.FAIL, emptyFields.get(0)));
        }

    }

    public  List<String> validateQuestionInfoDtos(List<QuestionInfoDto> questionInfoDtos) {
        List<String> emptyFields = new ArrayList<>();
        for (int i = 0; i < questionInfoDtos.size(); i++) {
            QuestionInfoDto dto = questionInfoDtos.get(i);
            if (dto.getSchoolType() == null) {
                emptyFields.add("第 " + (i + 1) + " 个对象的 schoolType 字段为空");
            }
            if (dto.getGradeInfoId() == null) {
                emptyFields.add("第 " + (i + 1) + " 个对象的 gradeInfoId 字段为空");
            }
            if (dto.getSubjectId() == null) {
                emptyFields.add("第 " + (i + 1) + " 个对象的 subjectId 字段为空");
            }
//            if (dto.getQuestionType() == null ) {
//                emptyFields.add("第 " + (i + 1) + " 个对象的 questionType 字段为空");
//            }
            if (dto.getContent() == null || dto.getContent().trim().isEmpty()) {
                emptyFields.add("第 " + (i + 1) + " 个对象的 content 字段为空");
            }
            if (dto.getAnswer() == null || dto.getAnswer().trim().isEmpty()) {
                emptyFields.add("第 " + (i + 1) + " 个对象的 answer 字段为空");
            }
        }
        return emptyFields;
    }

    /**
     * 试题详情
     * @param id
     * @return
     */
    @GetMapping("selectById")
    public Result selectById(Integer id) {
        return Result.success(questionInfoService.selectById(id));
    }

    /**
     * 根据id 删除试题
     * @param id
     * @return
     */
    @DeleteMapping("{id}")
    //@RequiresPermissions("system:question:deleteById")
    public Result deleteById(@PathVariable Integer id) {
        return Result.success(questionInfoService.deleteById(id));
    }

    /**
     * 导入试题
     * @param gradeInfoId
     * @param subjectId
     * @param file
     * @return
     */
    @PostMapping("importQuestion")
    @ParamsValidate(params = {
        @Param(name = "schoolType", message = "请选择导入所属阶段"),
        @Param(name = "gradeInfoId", message = "请选择导入所属年级"),
        @Param(name = "subjectId", message = "请选择导入所属科目")
    })
    public Result importQuestion(
                                 HttpServletResponse response,
                                 @RequestParam Integer schoolType,
                                 @RequestParam Integer gradeInfoId,
                                 @RequestParam Integer subjectId,
                                 @RequestParam MultipartFile file) {
        String contentType = file.getContentType();
        if (!excelTypes.contains(contentType) && !textTypes.contains(contentType)) {
            return Result.fail(ResultCode.FAIL, "只能导入excel或者txt类型文件");
        }
        try {
            QuestionImportResult questionImportResult = null;
            if (excelTypes.contains(contentType)) {
                questionImportResult = new ExcelQuestionImportResult(file, response);
            } else {
                questionImportResult = new TxtQuestionImportResult(file);
            }

            questionImportResult.readTemplate();

            if (!questionImportResult.isHasData()) {
                return Result.success(ResultCode.FAIL, questionImportResult.getErrorMsg());
            }

            List<QuestionInfo> questionInfoList = questionImportResult.getSuccessImportQuestionList();
            int successCount = questionInfoService.importQuestion(schoolType, gradeInfoId,
                    subjectId, questionInfoList);

            int failCount = 0;
            List<QuestionInfo> failQuestionList = questionImportResult.getFailImportQuestionList();

            if (failQuestionList != null) {
                failCount = failQuestionList.size();
            }

            // excel 数据校验失败
            String msg = successCount + "道试题导入成功";
            if (ObjectUtils.isNotEmpty(questionImportResult.getErrorMsg())) {
                if (failCount > 0) {
                    msg += "," + failCount + "道试题导入失败(分别为)" + questionImportResult.getErrorMsg();
                }
                return Result.success(ResultCode.EXCEL_VERIFICATION_FAIL,
                       msg, questionImportResult.getErrorFileUrl());
            }
            return Result.success(ResultCode.SUCCESS, msg);
        } catch (Exception e) {
            logger.error("数据导入失败", e);
        }
        return Result.fail(ResultCode.FAIL, "数据导入失败");
    }
}
