package com.ruoyi.system.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.system.mapper.DutyConfigMapper;
import com.ruoyi.system.mapper.DutyUserMapper;
import com.ruoyi.system.mapper.DutyAssignCounterMapper;
import com.ruoyi.system.domain.DutyConfig;
import com.ruoyi.system.domain.DutyUser;
import com.ruoyi.system.domain.DutyAssignCounter;
import com.ruoyi.system.service.IDutyConfigService;

import com.ruoyi.common.core.text.Convert;

/**
 * 值班配置Service业务层处理
 *
 * @author ruoyi
 * @date 2024-01-15
 */
@Service
public class DutyConfigServiceImpl implements IDutyConfigService
{
    @Autowired
    private DutyConfigMapper dutyConfigMapper;

    @Autowired
    private DutyUserMapper dutyUserMapper;

    @Autowired
    private DutyAssignCounterMapper dutyAssignCounterMapper;

    /**
     * 查询值班配置
     *
     * @param id 值班配置主键
     * @return 值班配置
     */
    @Override
    public DutyConfig selectDutyConfigById(Long id)
    {
        DutyConfig dutyConfig = dutyConfigMapper.selectDutyConfigById(id);
        if (dutyConfig != null) {
            // 设置值班用户名称
            List<DutyUser> dutyUsers = dutyConfig.getDutyUsers();
            if (dutyUsers != null && !dutyUsers.isEmpty()) {
                String userNames = dutyUsers.stream()
                    .map(DutyUser::getUserName)
                    .collect(Collectors.joining(","));
                dutyConfig.setDutyUserNames(userNames);
            }
        }
        return dutyConfig;
    }

    /**
     * 查询值班配置列表
     *
     * @param dutyConfig 值班配置
     * @return 值班配置
     */
    @Override
    public List<DutyConfig> selectDutyConfigList(DutyConfig dutyConfig)
    {
        List<DutyConfig> list = dutyConfigMapper.selectDutyConfigList(dutyConfig);
        // 为每个配置设置用户名称和是否激活状态
        Date now = new Date();
        for (DutyConfig config : list) {
            // 设置值班用户名称
            List<DutyUser> dutyUsers = config.getDutyUsers();
            if (dutyUsers != null && !dutyUsers.isEmpty()) {
                String userNames = dutyUsers.stream()
                    .map(DutyUser::getUserName)
                    .collect(Collectors.joining(","));
                config.setDutyUserNames(userNames);
            }
            
            // 设置是否在当前时间范围内
            if ("1".equals(config.getStatus()) && 
                config.getStartTime() != null && config.getEndTime() != null) {
                config.setIsActive(now.compareTo(config.getStartTime()) >= 0 && 
                                 now.compareTo(config.getEndTime()) <= 0);
            } else {
                config.setIsActive(false);
            }
        }
        return list;
    }

    /**
     * 根据当前时间获取下一个值班用户ID（轮询分配）
     *
     * @return 值班用户ID，如果没有匹配的配置则返回null
     */
    @Override
    @Transactional
    public Long getNextDutyUserId()
    {
        Date currentTime = new Date();
        DutyConfig activeDutyConfig = dutyConfigMapper.selectActiveDutyConfig(currentTime);
        
        if (activeDutyConfig == null) {
            return null;
        }
        
        // 获取值班用户列表（按排序顺序）
        List<DutyUser> dutyUsers = dutyUserMapper.selectDutyUsersByConfigIdOrderBySort(activeDutyConfig.getId());
        if (dutyUsers == null || dutyUsers.isEmpty()) {
            return null;
        }
        
        // 如果只有一个用户，直接返回
        if (dutyUsers.size() == 1) {
            updateAssignCounter(activeDutyConfig.getId(), dutyUsers.get(0).getUserId());
            return dutyUsers.get(0).getUserId();
        }
        
        // 查询分配计数器
        DutyAssignCounter counter = dutyAssignCounterMapper.selectDutyAssignCounterByConfigId(activeDutyConfig.getId());
        
        Long nextUserId = null;
        
        if (counter == null) {
            // 第一次分配，返回第一个用户
            nextUserId = dutyUsers.get(0).getUserId();
            
            // 创建计数器
            counter = new DutyAssignCounter();
            counter.setConfigId(activeDutyConfig.getId());
            counter.setLastAssignedUserId(nextUserId);
            counter.setAssignCount(1);
            counter.setUpdateTime(currentTime);
            dutyAssignCounterMapper.insertDutyAssignCounter(counter);
        } else {
            // 轮询：找到上次分配用户的下一个用户
            Long lastUserId = counter.getLastAssignedUserId();
            int lastIndex = -1;
            
            // 找到上次分配用户的索引
            for (int i = 0; i < dutyUsers.size(); i++) {
                if (dutyUsers.get(i).getUserId().equals(lastUserId)) {
                    lastIndex = i;
                    break;
                }
            }
            
            // 计算下一个用户的索引（循环轮询）
            int nextIndex = (lastIndex + 1) % dutyUsers.size();
            nextUserId = dutyUsers.get(nextIndex).getUserId();
            
            // 更新计数器
            Integer assignCount = counter.getAssignCount() == null ? 1 : counter.getAssignCount() + 1;
            dutyAssignCounterMapper.updateAssignCounter(activeDutyConfig.getId(), nextUserId, assignCount);
        }
        
        return nextUserId;
    }
    
    /**
     * 更新分配计数器（内部方法）
     */
    private void updateAssignCounter(Long configId, Long userId) {
        DutyAssignCounter counter = dutyAssignCounterMapper.selectDutyAssignCounterByConfigId(configId);
        if (counter == null) {
            counter = new DutyAssignCounter();
            counter.setConfigId(configId);
            counter.setLastAssignedUserId(userId);
            counter.setAssignCount(1);
            counter.setUpdateTime(new Date());
            dutyAssignCounterMapper.insertDutyAssignCounter(counter);
        } else {
            Integer assignCount = counter.getAssignCount() == null ? 1 : counter.getAssignCount() + 1;
            dutyAssignCounterMapper.updateAssignCounter(configId, userId, assignCount);
        }
    }

    /**
     * 根据当前时间查询有效的值班配置
     *
     * @param currentTime 当前时间
     * @return 值班配置
     */
    @Override
    public DutyConfig selectActiveDutyConfig(Date currentTime)
    {
        return dutyConfigMapper.selectActiveDutyConfig(currentTime);
    }

    /**
     * 新增值班配置
     *
     * @param dutyConfig 值班配置
     * @param dutyUserIds 值班用户ID字符串（逗号分隔）
     * @return 结果
     */
    @Override
    @Transactional
    public int insertDutyConfig(DutyConfig dutyConfig, String dutyUserIds)
    {
        // 创建时间由数据库 sysdate() 自动设置，无需手动设置
        int result = dutyConfigMapper.insertDutyConfig(dutyConfig);
        
        // 处理值班用户关联
        if (result > 0 && dutyUserIds != null && !dutyUserIds.trim().isEmpty()) {
            String[] userIdArray = dutyUserIds.split(",");
            List<DutyUser> dutyUsers = new ArrayList<>();
            for (int i = 0; i < userIdArray.length; i++) {
                DutyUser dutyUser = new DutyUser();
                dutyUser.setConfigId(dutyConfig.getId());
                dutyUser.setUserId(Long.parseLong(userIdArray[i].trim()));
                dutyUser.setSortOrder(i + 1);
                dutyUser.setCreateTime(DateUtils.getNowDate());
                dutyUsers.add(dutyUser);
            }
            dutyUserMapper.insertDutyUserBatch(dutyUsers);
        }
        
        return result;
    }

    /**
     * 修改值班配置
     *
     * @param dutyConfig 值班配置
     * @param dutyUserIds 值班用户ID字符串（逗号分隔）
     * @return 结果
     */
    @Override
    @Transactional
    public int updateDutyConfig(DutyConfig dutyConfig, String dutyUserIds)
    {
        dutyConfig.setUpdateTime(DateUtils.getNowDate());
        int result = dutyConfigMapper.updateDutyConfig(dutyConfig);
        
        // 先删除原有的值班用户关联
        dutyUserMapper.deleteDutyUserByConfigId(dutyConfig.getId());
        
        // 重新添加值班用户关联
        if (result > 0 && dutyUserIds != null && !dutyUserIds.trim().isEmpty()) {
            String[] userIdArray = dutyUserIds.split(",");
            List<DutyUser> dutyUsers = new ArrayList<>();
            for (int i = 0; i < userIdArray.length; i++) {
                DutyUser dutyUser = new DutyUser();
                dutyUser.setConfigId(dutyConfig.getId());
                dutyUser.setUserId(Long.parseLong(userIdArray[i].trim()));
                dutyUser.setSortOrder(i + 1);
                dutyUser.setCreateTime(DateUtils.getNowDate());
                dutyUsers.add(dutyUser);
            }
            dutyUserMapper.insertDutyUserBatch(dutyUsers);
        }
        
        return result;
    }

    /**
     * 批量删除值班配置
     *
     * @param ids 需要删除的值班配置主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteDutyConfigByIds(String ids)
    {
        String[] configIds = Convert.toStrArray(ids);
        // 删除值班用户关联关系
        for (String configId : configIds) {
            dutyUserMapper.deleteDutyUserByConfigId(Long.parseLong(configId));
        }
        return dutyConfigMapper.deleteDutyConfigByIds(configIds);
    }

    /**
     * 删除值班配置信息
     *
     * @param id 值班配置主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteDutyConfigById(Long id)
    {
        // 删除值班用户关联关系
        dutyUserMapper.deleteDutyUserByConfigId(id);
        return dutyConfigMapper.deleteDutyConfigById(id);
    }

    /**
     * 检查时间段是否冲突
     *
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @param excludeId 排除的配置ID（用于编辑时排除自己）
     * @return 是否冲突
     */
    @Override
    public boolean checkTimeConflict(Date startTime, Date endTime, Long excludeId)
    {
        int count = dutyConfigMapper.checkTimeConflict(startTime, endTime, excludeId);
        return count > 0;
    }

    /**
     * 修改值班配置状态
     *
     * @param dutyConfig 值班配置
     * @return 结果
     */
    @Override
    public int changeStatus(DutyConfig dutyConfig)
    {
        dutyConfig.setUpdateTime(DateUtils.getNowDate());
        return dutyConfigMapper.updateDutyConfig(dutyConfig);
    }
}