package com.sundot.airport.web.controller.exam;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sundot.airport.common.utils.SecurityUtils;
import com.sundot.airport.exam.adapter.DailyTaskToExamAdapter;
import com.sundot.airport.exam.common.ClientTypeConstant;
import com.sundot.airport.exam.common.HttpResult;
import com.sundot.airport.exam.common.PageData;
import com.sundot.airport.exam.domain.DailyTask;
import com.sundot.airport.exam.domain.DailyTaskDetail;
import com.sundot.airport.exam.dto.SubmitAnswerDTO;
import com.sundot.airport.exam.dto.SubmitResultDTO;
import com.sundot.airport.exam.logic.eighteen.model.params.ExamRecAddParam;
import com.sundot.airport.exam.logic.eighteen.model.params.Get18ExamIntroParams;
import com.sundot.airport.exam.logic.eighteen.model.params.SubmitExamParam;
import com.sundot.airport.exam.logic.eighteen.model.result.ExamGetResult;
import com.sundot.airport.exam.logic.eighteen.model.result.Get18ExamIntroResult;
import com.sundot.airport.exam.logic.eighteen.model.result.SubmitExamResult;
import com.sundot.airport.exam.logic.eighteen.model.result.subresult.ItemIn18ExamRecordListResult;
import com.sundot.airport.exam.mapper.DailyTaskDetailMapper;
import com.sundot.airport.exam.mapper.DailyTaskMapper;
import com.sundot.airport.exam.service.IDailyAnswerService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <b>功能名：</b>DailyExamController<br>
 * <b>说明：</b> 每日抽问抽答接口控制层（兼容十八大考试格式） <br>
 * <b>著作权：</b> Copyright (C) 2025 SUNDOT CORPORATION<br>
 * <b>修改履历：</b><br>
 *
 * @author 2025-01-16
 */
@RestController
@RequestMapping("/v1/cs/app/daily-exam")
public class DailyExamController {

    private static final Logger log = LoggerFactory.getLogger(DailyExamController.class);

    @Autowired
    private DailyTaskMapper dailyTaskMapper;

    @Autowired
    private DailyTaskDetailMapper dailyTaskDetailMapper;

    @Autowired
    private IDailyAnswerService dailyAnswerService;

    @Autowired
    private DailyTaskToExamAdapter dailyTaskAdapter;

    /**
     * <b>方法名: </b> getExamIntro <br>
     * <b>说明: </b> 查询考试基本信息（兼容接口，实际返回当日任务信息） <br>
     *
     * @param param Get18ExamIntroParams 查询考试基本信息参数类
     * @return HttpResult<Get18ExamIntroResult>
     * <b>修改履历: </b>
     * @author 2025-01-16
     */
    @PostMapping("/get_exam_intro")
    public HttpResult<Get18ExamIntroResult> getExamIntro(@Validated @RequestBody Get18ExamIntroParams param) {
        log.info("获取每日任务基本信息: userId={}", SecurityUtils.getUserId());

        // 构造返回结果（固定信息）
        Get18ExamIntroResult result = new Get18ExamIntroResult();
        result.setExId("DAILY_TASK");
        result.setExName("每日抽问抽答");
        result.setExDetailImg("");
        result.setExBgImg("");

        return HttpResult.success(result);
    }

    /**
     * <b>方法名: </b> applyExam <br>
     * <b>说明: </b> 开始答题（获取今日待完成任务） <br>
     *
     * @param token java.lang.String token信息
     * @param param com.sundot.airport.exam.logic.eighteen.model.params.ExamRecAddParam 获取考试信息和试题请求参数
     * @return com.sundot.airport.exam.common.HttpResult<com.sundot.airport.exam.logic.eighteen.model.result.ExamGetResult><br>
     * <b>修改履历: </b>
     * @author 2025-01-16
     */
    @PostMapping("/get_exam")
    public HttpResult<ExamGetResult> applyExam(
            @RequestHeader(value = "Authorization", required = true) String token,
            @Validated @RequestBody ExamRecAddParam param) {

        Long userId = SecurityUtils.getUserId();
        log.info("用户申请每日答题: userId={}, param={}", userId, param);

        try {
            // 1. 查询今日待完成任务
            LambdaQueryWrapper<DailyTask> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(DailyTask::getDtUserId, userId);
            wrapper.eq(DailyTask::getDtStatus, "PENDING");
            wrapper.eq(DailyTask::getDelStatus, 0);
            wrapper.orderByAsc(DailyTask::getCreateTime);
            wrapper.last("LIMIT 1");

            DailyTask task = dailyTaskMapper.selectOne(wrapper);

            if (task == null) {
                log.warn("用户今日无待完成任务: userId={}", userId);
                return HttpResult.error("今日暂无答题任务");
            }

            // 2. 更新任务状态为答题中
            task.setDtStatus("IN_PROGRESS");
            task.setDtStartTime(new java.util.Date());
            dailyTaskMapper.updateById(task);

            // 3. 查询任务明细（题目列表）
            LambdaQueryWrapper<DailyTaskDetail> detailWrapper = new LambdaQueryWrapper<>();
            detailWrapper.eq(DailyTaskDetail::getDtdTaskId, task.getDtId());
            detailWrapper.eq(DailyTaskDetail::getDelStatus, 0);
            detailWrapper.orderByAsc(DailyTaskDetail::getDtdQuestionNo);
            List<DailyTaskDetail> details = dailyTaskDetailMapper.selectList(detailWrapper);

            // 4. 转换为考试格式返回
            ExamGetResult result = dailyTaskAdapter.convertDailyTaskToExam(task, details);

            log.info("每日答题获取成功: userId={}, taskId={}, questionCount={}",
                    userId, task.getDtId(), details.size());

            return HttpResult.success(result);

        } catch (Exception e) {
            log.error("获取每日答题失败: userId={}", userId, e);
            return HttpResult.error("获取每日答题失败：" + e.getMessage());
        }
    }

    /**
     * <b>方法名: </b> getExamRecordList <br>
     * <b>说明: </b> 查询测试记录列表（用户历史任务列表） <br>
     *
     * @return HttpResult<PageData < ItemIn18ExamRecordListResult>>
     * <b>修改履历: </b>
     * @author 2025-01-16
     */
    @PostMapping("/get_exam_record_list")
    public HttpResult<PageData<ItemIn18ExamRecordListResult>> getExamRecordList() {
        Long userId = SecurityUtils.getUserId();
        log.info("查询用户任务记录列表: userId={}", userId);

        try {
            // 查询用户所有任务记录
            LambdaQueryWrapper<DailyTask> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(DailyTask::getDtUserId, userId);
            wrapper.eq(DailyTask::getDelStatus, 0);
            wrapper.orderByDesc(DailyTask::getDtBusinessDate);
            wrapper.orderByDesc(DailyTask::getCreateTime);

            List<DailyTask> tasks = dailyTaskMapper.selectList(wrapper);

            // 转换为考试记录列表格式
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            List<ItemIn18ExamRecordListResult> results = new ArrayList<>();

            for (DailyTask task : tasks) {
                ItemIn18ExamRecordListResult item = new ItemIn18ExamRecordListResult();
                item.setErId(task.getDtId());
                item.setErExId("DAILY_TASK_" + task.getDtBusinessDate());
                item.setErExName("每日抽问抽答");
                item.setErScore(task.getDtTotalScore() != null ? task.getDtTotalScore().intValue() : 0);
                item.setCreateTime(task.getCreateTime() != null ? sdf.format(task.getCreateTime()) : "");
                item.setErExEnableCert(false); // 每日任务不启用证书
                item.setGetCert(false);

                results.add(item);
            }

            PageData<ItemIn18ExamRecordListResult> pageData = new PageData<>();
            pageData.setList(results);
            pageData.setTotal(results.size());

            return HttpResult.success(pageData);

        } catch (Exception e) {
            log.error("查询任务记录列表失败: userId={}", userId, e);
            return HttpResult.error("查询记录列表失败：" + e.getMessage());
        }
    }

    /**
     * <b>方法名: </b> getExamRecord <br>
     * <b>说明: </b> 查询测试记录详情（任务详情） <br>
     *
     * @param erId 任务ID
     * @return HttpResult
     * <b>修改履历: </b>
     * @author 2025-01-16
     */
    @PostMapping("/get_exam_record")
    public HttpResult getExamRecord(@RequestParam String erId) {
        Long userId = SecurityUtils.getUserId();
        log.info("查询任务记录详情: userId={}, taskId={}", userId, erId);

        try {
            // 查询任务主记录
            LambdaQueryWrapper<DailyTask> taskWrapper = new LambdaQueryWrapper<>();
            taskWrapper.eq(DailyTask::getDtId, erId);
            taskWrapper.eq(DailyTask::getDelStatus, 0);
            DailyTask task = dailyTaskMapper.selectOne(taskWrapper);

            if (task == null) {
                return HttpResult.error("任务不存在");
            }

            // 验证权限
            if (!task.getDtUserId().equals(userId)) {
                return HttpResult.error("无权查看该任务");
            }

            // 查询任务明细
            LambdaQueryWrapper<DailyTaskDetail> detailWrapper = new LambdaQueryWrapper<>();
            detailWrapper.eq(DailyTaskDetail::getDtdTaskId, erId);
            detailWrapper.eq(DailyTaskDetail::getDelStatus, 0);
            detailWrapper.orderByAsc(DailyTaskDetail::getDtdQuestionNo);
            List<DailyTaskDetail> details = dailyTaskDetailMapper.selectList(detailWrapper);

            // 组装返回结果
            Map<String, Object> data = new HashMap<>();
            data.put("task", task);
            data.put("details", details);

            return HttpResult.success(data);

        } catch (Exception e) {
            log.error("查询任务记录详情失败: userId={}, taskId={}", userId, erId, e);
            return HttpResult.error("查询记录详情失败：" + e.getMessage());
        }
    }

    /**
     * <b>方法名: </b> submitExam <br>
     * <b>说明: </b> 提交考试答案 <br>
     *
     * @param param SubmitExamParam 提交考试参数类
     * @return HttpResult<SubmitExamResult>
     * <b>修改履历: </b>
     * @author 2025-01-16
     */
    @PostMapping("/submit_exam")
    public HttpResult<SubmitExamResult> submitExam(@Validated @RequestBody SubmitExamParam param) {
        Long userId = SecurityUtils.getUserId();
        log.info("提交每日答题: userId={}, param={}", userId, param);

        try {
            // 1. 转换参数格式
            SubmitAnswerDTO taskDto = dailyTaskAdapter.convertExamParamToTaskSubmit(param);

            // 2. 调用答题服务提交
            SubmitResultDTO taskResult = dailyAnswerService.submitAnswer(userId, taskDto);

            // 3. 转换为考试提交结果格式
            SubmitExamResult examResult = dailyTaskAdapter.convertTaskResultToExamResult(taskResult);

            log.info("每日答题提交成功: userId={}, taskId={}, score={}",
                    userId, taskResult.getTaskId(), taskResult.getTotalScore());

            return HttpResult.success(examResult);

        } catch (Exception e) {
            log.error("提交每日答题失败: userId={}, erId={}", userId, param.getErId(), e);
            return HttpResult.error("提交答题失败：" + e.getMessage());
        }
    }
}
