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

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.DailyTaskConfig;
import com.sundot.airport.exam.dto.DailyTaskConfigDTO;
import com.sundot.airport.exam.dto.DailyTaskConfigQueryDTO;
import com.sundot.airport.exam.service.IDailyTaskConfigService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

/**
 * <b>功能名：</b>DailyTaskConfigController<br>
 * <b>说明：</b> 每日答题任务配置Controller <br>
 * <b>著作权：</b> Copyright (C) 2025 SUNDOT CORPORATION<br>
 * <b>修改履历：
 *
 * @author Simon Lin
 */
@RestController
@RequestMapping("/exam/daily/config")
public class DailyTaskConfigController extends BaseController {

    @Autowired
    private IDailyTaskConfigService dailyTaskConfigService;

    /**
     * 查询每日答题任务配置列表
     */
    @PreAuthorize("@ss.hasPermi('exam:daily:config:list')")
    @PostMapping("/list")
    public TableDataInfo list(@RequestBody DailyTaskConfigQueryDTO queryDTO) {
        return dailyTaskConfigService.selectConfigList(queryDTO);
    }

    /**
     * 获取每日答题任务配置详细信息
     */
    @PreAuthorize("@ss.hasPermi('exam:daily:config:query')")
    @GetMapping("/{dtcId}")
    public AjaxResult getInfo(@PathVariable("dtcId") String dtcId) {
        return success(dailyTaskConfigService.selectConfigById(dtcId));
    }

    /**
     * 新增每日答题任务配置
     */
    @PreAuthorize("@ss.hasPermi('exam:daily:config:add')")
    @Log(title = "每日答题任务配置", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Validated @RequestBody DailyTaskConfigDTO dto) {
        return toAjax(dailyTaskConfigService.insertConfig(dto));
    }

    /**
     * 修改每日答题任务配置
     */
    @PreAuthorize("@ss.hasPermi('exam:daily:config:edit')")
    @Log(title = "每日答题任务配置", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Validated @RequestBody DailyTaskConfigDTO dto) {
        return toAjax(dailyTaskConfigService.updateConfig(dto));
    }

    /**
     * 删除每日答题任务配置
     */
    @PreAuthorize("@ss.hasPermi('exam:daily:config:remove')")
    @Log(title = "每日答题任务配置", businessType = BusinessType.DELETE)
    @DeleteMapping("/{dtcIds}")
    public AjaxResult remove(@PathVariable String[] dtcIds) {
        return toAjax(dailyTaskConfigService.deleteConfigByIds(dtcIds));
    }

    /**
     * 启用/停用每日答题任务配置
     */
    @PreAuthorize("@ss.hasPermi('exam:daily:config:edit')")
    @Log(title = "每日答题任务配置", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public AjaxResult changeStatus(@RequestParam("dtcId") String dtcId,
                                    @RequestParam("enableStatus") Boolean enableStatus) {
        return toAjax(dailyTaskConfigService.updateConfigStatus(dtcId, enableStatus));
    }

    /**
     * 根据当前用户获取有效配置
     * 遍历用户的所有角色，收集所有匹配的有效配置，并选择最新的配置
     */
    @GetMapping("/effective")
    public AjaxResult getEffectiveConfig() {
        // 获取当前用户的角色ID列表和部门
        Long deptId = getDeptId();

        // 获取用户的所有角色ID
        java.util.List<Long> roleIds = getLoginUser().getUser().getRoles().stream()
                .map(role -> role.getRoleId())
                .collect(java.util.stream.Collectors.toList());

        if (roleIds.isEmpty()) {
            return AjaxResult.error("用户未分配角色");
        }

        // 收集所有角色匹配的有效配置
        java.util.List<DailyTaskConfig> matchedConfigs = new java.util.ArrayList<>();
        for (Long roleId : roleIds) {
            DailyTaskConfig config = dailyTaskConfigService.getEffectiveConfig(roleId, deptId);
            if (config != null) {
                matchedConfigs.add(config);
            }
        }

        if (matchedConfigs.isEmpty()) {
            return AjaxResult.error("未找到适用的答题配置");
        }

        // 选择最新的配置（根据创建时间降序排序，取第一个）
        DailyTaskConfig latestConfig = matchedConfigs.stream()
                .sorted((c1, c2) -> c2.getCreateTime().compareTo(c1.getCreateTime()))
                .findFirst()
                .orElse(null);

        return success(latestConfig);
    }

    /**
     * 获取默认配置（第一条配置）
     * 用于单配置管理页面
     */
    @GetMapping("/default")
    public AjaxResult getDefaultConfig() {
        DailyTaskConfig config = dailyTaskConfigService.getDefaultConfig();
        if (config == null) {
            return AjaxResult.error("暂无配置数据");
        }
        return success(config);
    }
}
