package com.sundot.airport.exam.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sundot.airport.common.core.page.TableDataInfo;
import com.sundot.airport.common.exception.ServiceException;
import com.sundot.airport.common.utils.StringUtils;
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.mapper.DailyTaskConfigMapper;
import com.sundot.airport.exam.service.IDailyTaskConfigService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <b>功能名：</b>DailyTaskConfigServiceImpl<br>
 * <b>说明：</b> 每日答题任务配置Service实现 <br>
 * <b>著作权：</b> Copyright (C) 2025 SUNDOT CORPORATION<br>
 * <b>修改履历：
 *
 * @author Simon Lin
 */
@Service
public class DailyTaskConfigServiceImpl extends ServiceImpl<DailyTaskConfigMapper, DailyTaskConfig>
        implements IDailyTaskConfigService {

    @Override
    public TableDataInfo selectConfigList(DailyTaskConfigQueryDTO queryDTO) {
        // 构建查询条件
        LambdaQueryWrapper<DailyTaskConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DailyTaskConfig::getDelStatus, 0);

        if (StringUtils.isNotEmpty(queryDTO.getDtcName())) {
            wrapper.like(DailyTaskConfig::getDtcName, queryDTO.getDtcName());
        }

        if (StringUtils.isNotEmpty(queryDTO.getRole())) {
            wrapper.like(DailyTaskConfig::getDtcRoles, queryDTO.getRole());
        }

        if (queryDTO.getDtcEnableStatus() != null) {
            wrapper.eq(DailyTaskConfig::getDtcEnableStatus, queryDTO.getDtcEnableStatus());
        }

        if (queryDTO.getStartDate() != null) {
            wrapper.ge(DailyTaskConfig::getDtcStartDate, queryDTO.getStartDate());
        }

        if (queryDTO.getEndDate() != null) {
            wrapper.le(DailyTaskConfig::getDtcEndDate, queryDTO.getEndDate());
        }

        wrapper.orderByDesc(DailyTaskConfig::getCreateTime);

        // 分页查询
        Page<DailyTaskConfig> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());
        IPage<DailyTaskConfig> pageResult = this.page(page, wrapper);

        // 封装返回结果
        TableDataInfo dataInfo = new TableDataInfo();
        dataInfo.setRows(pageResult.getRecords());
        dataInfo.setTotal(pageResult.getTotal());
        return dataInfo;
    }

    @Override
    public DailyTaskConfig selectConfigById(String dtcId) {
        LambdaQueryWrapper<DailyTaskConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DailyTaskConfig::getDtcId, dtcId);
        wrapper.eq(DailyTaskConfig::getDelStatus, 0);
        return this.getOne(wrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertConfig(DailyTaskConfigDTO dto) {
        // 校验日期
        validateDate(dto.getDtcStartDate(), dto.getDtcEndDate());

        // 构建实体
        DailyTaskConfig config = new DailyTaskConfig();
        BeanUtils.copyProperties(dto, config);

        // 生成业务主键
        config.setDtcId("DTC" + IdUtil.getSnowflakeNextIdStr());

        // 转换角色ID和部门ID为逗号分隔的字符串
        config.setDtcRoles(dto.getDtcRoles().stream()
                .map(String::valueOf)
                .collect(Collectors.joining(",")));
        config.setDtcDeptIds(dto.getDtcDeptIds().stream()
                .map(String::valueOf)
                .collect(Collectors.joining(",")));

        config.setDelStatus(0);

        return this.baseMapper.insert(config);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateConfig(DailyTaskConfigDTO dto) {
        if (StringUtils.isEmpty(dto.getDtcId())) {
            throw new ServiceException("配置ID不能为空");
        }

        // 校验配置是否存在
        DailyTaskConfig existConfig = selectConfigById(dto.getDtcId());
        if (existConfig == null) {
            throw new ServiceException("配置不存在");
        }

        // 校验日期
        validateDate(dto.getDtcStartDate(), dto.getDtcEndDate());

        // 构建更新实体
        DailyTaskConfig config = new DailyTaskConfig();
        BeanUtils.copyProperties(dto, config);
        config.setId(existConfig.getId());

        // 转换角色ID和部门ID
        config.setDtcRoles(dto.getDtcRoles().stream()
                .map(String::valueOf)
                .collect(Collectors.joining(",")));
        config.setDtcDeptIds(dto.getDtcDeptIds().stream()
                .map(String::valueOf)
                .collect(Collectors.joining(",")));

        return this.baseMapper.updateById(config);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteConfig(String dtcId) {
        DailyTaskConfig config = selectConfigById(dtcId);
        if (config == null) {
            throw new ServiceException("配置不存在");
        }

        // 逻辑删除
        config.setDelStatus(1);
        return this.baseMapper.updateById(config);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int deleteConfigByIds(String[] dtcIds) {
        int count = 0;
        for (String dtcId : dtcIds) {
            count += deleteConfig(dtcId);
        }
        return count;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public int updateConfigStatus(String dtcId, Boolean enableStatus) {
        DailyTaskConfig config = selectConfigById(dtcId);
        if (config == null) {
            throw new ServiceException("配置不存在");
        }

        config.setDtcEnableStatus(enableStatus);
        return this.baseMapper.updateById(config);
    }

    @Override
    public DailyTaskConfig getEffectiveConfig(Long roleId, Long deptId) {
        Date currentDate = new Date();
        List<DailyTaskConfig> configs = this.baseMapper.findEffectiveConfigByRoleAndDept(
                roleId.toString(), deptId, currentDate);

        return configs.isEmpty() ? null : configs.get(0);
    }

    @Override
    public DailyTaskConfig getDefaultConfig() {
        LambdaQueryWrapper<DailyTaskConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DailyTaskConfig::getDelStatus, 0);
        wrapper.orderByDesc(DailyTaskConfig::getCreateTime);
        wrapper.last("LIMIT 1");
        return this.getOne(wrapper);
    }

    /**
     * 校验日期
     */
    private void validateDate(Date startDate, Date endDate) {
        if (startDate != null && endDate != null) {
            if (startDate.after(endDate)) {
                throw new ServiceException("开始日期不能晚于结束日期");
            }
        }
    }
}
