package com.sundot.airport.exam.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.sundot.airport.common.annotation.Log;
import com.sundot.airport.common.core.controller.BaseController;
import com.sundot.airport.common.core.domain.AjaxResult;
import com.sundot.airport.common.core.page.TableDataInfo;
import com.sundot.airport.common.enums.BusinessType;
import com.sundot.airport.exam.domain.DailyTask;
import com.sundot.airport.exam.domain.DailyTaskDetail;
import com.sundot.airport.exam.dto.DailyTaskAdminQueryDTO;
import com.sundot.airport.exam.enums.DailyTaskStatusEnum;
import com.sundot.airport.exam.domain.QuesOpt;
import com.sundot.airport.exam.mapper.DailyTaskDetailMapper;
import com.sundot.airport.exam.mapper.DailyTaskMapper;
import com.sundot.airport.exam.mapper.QuesOptMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <b>功能名：</b>DailyTaskAdminController<br>
 * <b>说明：</b> 每日答题任务管理员Controller <br>
 * <b>著作权：</b> Copyright (C) 2025 SUNDOT CORPORATION<br>
 * <b>修改履历：
 *
 * @author 2025-01-18
 */
@RestController
@RequestMapping("/exam/daily/task/admin")
public class DailyTaskAdminController extends BaseController {

    @Autowired
    private DailyTaskMapper dailyTaskMapper;

    @Autowired
    private DailyTaskDetailMapper dailyTaskDetailMapper;

    @Autowired
    private QuesOptMapper quesOptMapper;

    /**
     * 查询任务列表（管理员）
     * 支持多条件筛选
     */
    @PreAuthorize("@ss.hasPermi('exam:daily:task:admin:list') or @ss.hasRole('test') or @ss.hasRole('zhijianke')")
    @GetMapping("/list")
    public TableDataInfo list(DailyTaskAdminQueryDTO queryDTO) {
        LambdaQueryWrapper<DailyTask> wrapper = new LambdaQueryWrapper<>();

        // 用户ID筛选
        if (queryDTO.getUserId() != null) {
            wrapper.eq(DailyTask::getDtUserId, queryDTO.getUserId());
        }

        // 用户姓名模糊查询
        if (StringUtils.isNotBlank(queryDTO.getUserName())) {
            wrapper.like(DailyTask::getDtUserName, queryDTO.getUserName());
        }

        // 部门ID筛选
        if (queryDTO.getDeptId() != null) {
            wrapper.eq(DailyTask::getDtDeptId, queryDTO.getDeptId());
        }

        // 部门名称模糊查询（班组名称）
        if (StringUtils.isNotBlank(queryDTO.getDeptName())) {
            wrapper.like(DailyTask::getDtDeptName, queryDTO.getDeptName());
        }

        // 科室ID筛选
        if (queryDTO.getDepartmentId() != null) {
            wrapper.eq(DailyTask::getDtDepartmentId, queryDTO.getDepartmentId());
        }

        // 科室名称模糊查询
        if (StringUtils.isNotBlank(queryDTO.getDepartmentName())) {
            wrapper.like(DailyTask::getDtDepartmentName, queryDTO.getDepartmentName());
        }

        // 角色筛选（模糊匹配，支持多角色逗号分隔的场景）
        if (StringUtils.isNotBlank(queryDTO.getRole())) {
            wrapper.like(DailyTask::getDtRole, queryDTO.getRole());
        }

        // 任务状态筛选
        if (StringUtils.isNotBlank(queryDTO.getStatus())) {
            wrapper.eq(DailyTask::getDtStatus, queryDTO.getStatus());
        }

        // 业务日期范围筛选
        if (queryDTO.getBusinessDateStart() != null) {
            wrapper.ge(DailyTask::getDtBusinessDate, queryDTO.getBusinessDateStart());
        }
        if (queryDTO.getBusinessDateEnd() != null) {
            wrapper.le(DailyTask::getDtBusinessDate, queryDTO.getBusinessDateEnd());
        }

        // 创建时间范围筛选
        if (queryDTO.getCreateTimeStart() != null) {
            wrapper.ge(DailyTask::getCreateTime, queryDTO.getCreateTimeStart());
        }
        if (queryDTO.getCreateTimeEnd() != null) {
            wrapper.le(DailyTask::getCreateTime, queryDTO.getCreateTimeEnd());
        }

        // 配置ID筛选
        if (StringUtils.isNotBlank(queryDTO.getConfigId())) {
            wrapper.eq(DailyTask::getDtConfigId, queryDTO.getConfigId());
        }

        // 未删除的记录
        wrapper.eq(DailyTask::getDelStatus, 0);

        // 排序
        wrapper.orderByDesc(DailyTask::getDtBusinessDate);
        wrapper.orderByDesc(DailyTask::getCreateTime);

        startPage();
        List<DailyTask> list = dailyTaskMapper.selectList(wrapper);
        return getDataTable(list);
    }

    /**
     * 查询任务详情（管理员）
     * 管理员可以查看任何用户的任务详情
     */
    @PreAuthorize("@ss.hasPermi('exam:daily:task:admin:query') or @ss.hasRole('test') or @ss.hasRole('zhijianke')")
    @GetMapping("/{taskId}")
    public AjaxResult getTaskDetail(@PathVariable String taskId) {
        // 查询任务主记录
        LambdaQueryWrapper<DailyTask> taskWrapper = new LambdaQueryWrapper<>();
        taskWrapper.eq(DailyTask::getDtId, taskId);
        taskWrapper.eq(DailyTask::getDelStatus, 0);
        DailyTask task = dailyTaskMapper.selectOne(taskWrapper);

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

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

        // 查询所有题目的选项
        Map<String, List<Map<String, Object>>> optionsMap = new HashMap<>();
        if (!details.isEmpty()) {
            // 收集所有题目ID
            List<String> quesIds = details.stream()
                    .map(DailyTaskDetail::getDtdQuesId)
                    .filter(id -> id != null && !id.isEmpty())
                    .distinct()
                    .collect(Collectors.toList());

            if (!quesIds.isEmpty()) {
                // 查询这些题目的选项（使用自定义方法，忽略逻辑删除条件）
                List<QuesOpt> allOptions = quesOptMapper.selectByQuesIds(quesIds);

                // 按题目ID分组
                for (QuesOpt opt : allOptions) {
                    String quId = opt.getQuId();
                    optionsMap.computeIfAbsent(quId, k -> new ArrayList<>());
                    Map<String, Object> optInfo = new HashMap<>();
                    optInfo.put("sort", opt.getSort());
                    optInfo.put("content", opt.getQoOption());
                    optInfo.put("isCorrect", opt.getQoCorrect());
                    optionsMap.get(quId).add(optInfo);
                }
            }
        }

        // 组装返回结果
        AjaxResult result = AjaxResult.success();
        result.put("task", task);
        result.put("details", details);
        result.put("optionsMap", optionsMap);
        return result;
    }

    /**
     * 任务统计（管理员）
     * 按状态、部门、角色等维度统计
     */
    @PreAuthorize("@ss.hasPermi('exam:daily:task:admin:statistics') or @ss.hasRole('test') or @ss.hasRole('zhijianke')")
    @GetMapping("/statistics")
    public AjaxResult statistics(DailyTaskAdminQueryDTO queryDTO) {
        LambdaQueryWrapper<DailyTask> wrapper = new LambdaQueryWrapper<>();

        // 应用筛选条件
        applyQueryConditions(wrapper, queryDTO);

        // 统计总数
        Long totalCount = dailyTaskMapper.selectCount(wrapper);

        // 按状态统计
        Map<String, Long> statusStatistics = new HashMap<>();
        for (String status : new String[]{"PENDING", "IN_PROGRESS", "COMPLETED", "EXPIRED"}) {
            LambdaQueryWrapper<DailyTask> statusWrapper = new LambdaQueryWrapper<>();
            applyQueryConditions(statusWrapper, queryDTO);
            statusWrapper.eq(DailyTask::getDtStatus, status);
            Long count = dailyTaskMapper.selectCount(statusWrapper);
            statusStatistics.put(status, count);
        }

        // 组装返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("totalCount", totalCount);
        result.put("statusStatistics", statusStatistics);

        return AjaxResult.success(result);
    }

    /**
     * 按部门统计任务完成情况
     */
    @PreAuthorize("@ss.hasPermi('exam:daily:task:admin:statistics') or @ss.hasRole('test') or @ss.hasRole('zhijianke')")
    @GetMapping("/statistics/by-dept")
    public AjaxResult statisticsByDept(DailyTaskAdminQueryDTO queryDTO) {
        try {
            List<com.sundot.airport.exam.dto.DailyTaskDeptStatisticsDTO> statistics =
                dailyTaskMapper.statisticsByDept(queryDTO);
            return AjaxResult.success(statistics);
        } catch (Exception e) {
            logger.error("按部门统计任务失败", e);
            return error("统计失败：" + e.getMessage());
        }
    }

    /**
     * 按用户统计任务完成情况
     */
    @PreAuthorize("@ss.hasPermi('exam:daily:task:admin:statistics') or @ss.hasRole('test') or @ss.hasRole('zhijianke')")
    @GetMapping("/statistics/by-user")
    public AjaxResult statisticsByUser(DailyTaskAdminQueryDTO queryDTO) {
        try {
            List<com.sundot.airport.exam.dto.DailyTaskUserStatisticsDTO> statistics =
                dailyTaskMapper.statisticsByUser(queryDTO);
            return AjaxResult.success(statistics);
        } catch (Exception e) {
            logger.error("按用户统计任务失败", e);
            return error("统计失败：" + e.getMessage());
        }
    }

    /**
     * 删除任务（逻辑删除）
     */
    @PreAuthorize("@ss.hasPermi('exam:daily:task:admin:remove') or @ss.hasRole('test') or @ss.hasRole('zhijianke')")
    @Log(title = "删除每日任务", businessType = BusinessType.DELETE)
    @DeleteMapping("/{taskId}")
    public AjaxResult remove(@PathVariable String taskId) {
        LambdaQueryWrapper<DailyTask> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DailyTask::getDtId, taskId);
        DailyTask task = dailyTaskMapper.selectOne(wrapper);

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

        // 使用 MyBatis Plus 的删除方法，会自动处理 @TableLogic 标记的字段
        dailyTaskMapper.deleteById(task.getId());

        return success("删除成功");
    }

    /**
     * 批量删除任务（逻辑删除）
     */
    @PreAuthorize("@ss.hasPermi('exam:daily:task:admin:remove') or @ss.hasRole('test') or @ss.hasRole('zhijianke')")
    @Log(title = "批量删除每日任务", businessType = BusinessType.DELETE)
    @DeleteMapping("/batch/{taskIds}")
    public AjaxResult removeBatch(@PathVariable String[] taskIds) {
        for (String taskId : taskIds) {
            LambdaQueryWrapper<DailyTask> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(DailyTask::getDtId, taskId);
            DailyTask task = dailyTaskMapper.selectOne(wrapper);

            if (task != null) {
                // 使用 MyBatis Plus 的删除方法，会自动处理 @TableLogic 标记的字段
                dailyTaskMapper.deleteById(task.getId());
            }
        }

        return success("批量删除成功");
    }

    /**
     * 获取任务状态列表
     * 用于前端下拉框等场景
     */
    @GetMapping("/status/list")
    public AjaxResult getStatusList() {
        List<Map<String, String>> statusList = Arrays.stream(DailyTaskStatusEnum.values())
                .map(status -> {
                    Map<String, String> item = new HashMap<>();
                    item.put("code", status.getCode());
                    item.put("name", status.getCnName());
                    return item;
                })
                .collect(Collectors.toList());
        return AjaxResult.success(statusList);
    }

    /**
     * 应用查询条件（工具方法）
     */
    private void applyQueryConditions(LambdaQueryWrapper<DailyTask> wrapper, DailyTaskAdminQueryDTO queryDTO) {
        if (queryDTO.getUserId() != null) {
            wrapper.eq(DailyTask::getDtUserId, queryDTO.getUserId());
        }
        if (StringUtils.isNotBlank(queryDTO.getUserName())) {
            wrapper.like(DailyTask::getDtUserName, queryDTO.getUserName());
        }
        if (queryDTO.getDeptId() != null) {
            wrapper.eq(DailyTask::getDtDeptId, queryDTO.getDeptId());
        }
        if (StringUtils.isNotBlank(queryDTO.getDeptName())) {
            wrapper.like(DailyTask::getDtDeptName, queryDTO.getDeptName());
        }
        if (StringUtils.isNotBlank(queryDTO.getRole())) {
            wrapper.like(DailyTask::getDtRole, queryDTO.getRole());
        }
        if (queryDTO.getBusinessDateStart() != null) {
            wrapper.ge(DailyTask::getDtBusinessDate, queryDTO.getBusinessDateStart());
        }
        if (queryDTO.getBusinessDateEnd() != null) {
            wrapper.le(DailyTask::getDtBusinessDate, queryDTO.getBusinessDateEnd());
        }
        if (queryDTO.getCreateTimeStart() != null) {
            wrapper.ge(DailyTask::getCreateTime, queryDTO.getCreateTimeStart());
        }
        if (queryDTO.getCreateTimeEnd() != null) {
            wrapper.le(DailyTask::getCreateTime, queryDTO.getCreateTimeEnd());
        }
        if (StringUtils.isNotBlank(queryDTO.getConfigId())) {
            wrapper.eq(DailyTask::getDtConfigId, queryDTO.getConfigId());
        }
        wrapper.eq(DailyTask::getDelStatus, 0);
    }
}
