package com.ruoyi.web.controller.system;

import java.util.Date;
import java.util.List;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RequestParam;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.DutyConfig;
import com.ruoyi.system.service.IDutyConfigService;
import com.ruoyi.system.service.ISysUserService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.core.domain.entity.SysUser;

/**
 * 值班配置Controller
 *
 * @author ruoyi
 * @date 2024-12-19
 */
@Controller
@RequestMapping("/system/dutyConfig")
public class DutyConfigController extends BaseController
{
    private String prefix = "system/dutyConfig";

    @Autowired
    private IDutyConfigService dutyConfigService;

    @Autowired
    private ISysUserService userService;

    @RequiresPermissions("system:dutyConfig:view")
    @GetMapping()
    public String dutyConfig()
    {
        return prefix + "/dutyConfig";
    }

    /**
     * 查询值班配置列表
     */
    @RequiresPermissions("system:dutyConfig:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(DutyConfig dutyConfig)
    {
        startPage();
        List<DutyConfig> list = dutyConfigService.selectDutyConfigList(dutyConfig);
        return getDataTable(list);
    }

    /**
     * 导出值班配置列表
     */
    @RequiresPermissions("system:dutyConfig:export")
    @Log(title = "值班配置", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(DutyConfig dutyConfig)
    {
        List<DutyConfig> list = dutyConfigService.selectDutyConfigList(dutyConfig);
        ExcelUtil<DutyConfig> util = new ExcelUtil<DutyConfig>(DutyConfig.class);
        return util.exportExcel(list, "值班配置数据");
    }

    /**
     * 新增值班配置
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        // 获取所有可用用户
        SysUser user = new SysUser();
        user.setStatus("0"); // 正常状态
        List<SysUser> users = userService.selectUserList(user);
        mmap.put("users", users);
        return prefix + "/add";
    }

    /**
     * 新增保存值班配置
     */
    @RequiresPermissions("system:dutyConfig:add")
    @Log(title = "值班配置", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(DutyConfig dutyConfig, @RequestParam("dutyUserIds") String dutyUserIds)
    {
        // 验证时间范围
        if (dutyConfig.getStartTime() == null || dutyConfig.getEndTime() == null) {
            return error("开始时间和结束时间不能为空");
        }
        
        if (dutyConfig.getStartTime().compareTo(dutyConfig.getEndTime()) >= 0) {
            return error("开始时间必须早于结束时间");
        }
        
        // 检查时间段是否冲突
        if (dutyConfigService.checkTimeConflict(dutyConfig.getStartTime(), dutyConfig.getEndTime(), null)) {
            return error("该时间段与现有配置冲突，请重新选择时间");
        }
        
        // 验证值班用户
        if (dutyUserIds == null || dutyUserIds.trim().isEmpty()) {
            return error("值班用户不能为空");
        }
        
        dutyConfig.setCreateBy(getLoginName());
        // Service层会处理dutyUserIds参数
        return toAjax(dutyConfigService.insertDutyConfig(dutyConfig, dutyUserIds));
    }

    /**
     * 修改值班配置
     */
    @GetMapping("/edit/{id}")
    public String edit(@PathVariable("id") Long id, ModelMap mmap)
    {
        DutyConfig dutyConfig = dutyConfigService.selectDutyConfigById(id);
        mmap.put("dutyConfig", dutyConfig);
        
        // 获取所有可用用户
        SysUser user = new SysUser();
        user.setStatus("0"); // 正常状态
        List<SysUser> users = userService.selectUserList(user);
        mmap.put("users", users);
        
        return prefix + "/edit";
    }

    /**
     * 修改保存值班配置
     */
    @RequiresPermissions("system:dutyConfig:edit")
    @Log(title = "值班配置", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(DutyConfig dutyConfig, @RequestParam("dutyUserIds") String dutyUserIds)
    {
        // 验证时间范围
        if (dutyConfig.getStartTime() == null || dutyConfig.getEndTime() == null) {
            return error("开始时间和结束时间不能为空");
        }
        
        if (dutyConfig.getStartTime().compareTo(dutyConfig.getEndTime()) >= 0) {
            return error("开始时间必须早于结束时间");
        }
        
        // 检查时间段是否冲突（排除自己）
        if (dutyConfigService.checkTimeConflict(dutyConfig.getStartTime(), dutyConfig.getEndTime(), dutyConfig.getId())) {
            return error("该时间段与现有配置冲突，请重新选择时间");
        }
        
        // 验证值班用户
        if (dutyUserIds == null || dutyUserIds.trim().isEmpty()) {
            return error("值班用户不能为空");
        }
        
        dutyConfig.setUpdateBy(getLoginName());
        // Service层会处理dutyUserIds参数
        return toAjax(dutyConfigService.updateDutyConfig(dutyConfig, dutyUserIds));
    }

    /**
     * 删除值班配置
     */
    @RequiresPermissions("system:dutyConfig:remove")
    @Log(title = "值班配置", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(dutyConfigService.deleteDutyConfigByIds(ids));
    }

    /**
     * 修改值班配置状态
     */
    @RequiresPermissions("system:dutyConfig:edit")
    @Log(title = "值班配置", businessType = BusinessType.UPDATE)
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(DutyConfig dutyConfig)
    {
        dutyConfig.setUpdateBy(getLoginName());
        return toAjax(dutyConfigService.changeStatus(dutyConfig));
    }

    /**
     * 获取可用用户列表
     */
    @GetMapping("/getAvailableUsers")
    @ResponseBody
    public AjaxResult getAvailableUsers()
    {
        SysUser user = new SysUser();
        user.setStatus("0"); // 正常状态
        List<SysUser> users = userService.selectUserList(user);
        return AjaxResult.success(users);
    }

    /**
     * 获取当前值班用户
     */
    @GetMapping("/getCurrentDutyUser")
    @ResponseBody
    public AjaxResult getCurrentDutyUser()
    {
        Long dutyUserId = dutyConfigService.getNextDutyUserId();
        if (dutyUserId != null) {
            SysUser user = userService.selectUserById(dutyUserId);
            return AjaxResult.success(user);
        }
        return AjaxResult.error("当前没有值班配置");
    }

    /**
     * 查看值班配置详情
     */
    @RequiresPermissions("system:dutyConfig:view")
    @GetMapping("/detail/{id}")
    public String detail(@PathVariable("id") Long id, ModelMap mmap)
    {
        DutyConfig dutyConfig = dutyConfigService.selectDutyConfigById(id);
        
        // 设置是否在当前时间范围内
        if (dutyConfig != null) {
            Date now = new Date();
            if ("1".equals(dutyConfig.getStatus()) && 
                dutyConfig.getStartTime() != null && dutyConfig.getEndTime() != null) {
                dutyConfig.setIsActive(now.compareTo(dutyConfig.getStartTime()) >= 0 && 
                                     now.compareTo(dutyConfig.getEndTime()) <= 0);
            } else {
                dutyConfig.setIsActive(false);
            }
        }
        
        mmap.put("dutyConfig", dutyConfig);
        return prefix + "/detail";
    }
}