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

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sundot.airport.common.core.domain.entity.SysDept;
import com.sundot.airport.common.exception.ServiceException;
import com.sundot.airport.common.utils.DateUtils;
import com.sundot.airport.system.service.ISysDeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sundot.airport.blocked.mapper.BlockedBootPersonnelTenureMapper;
import com.sundot.airport.blocked.domain.BlockedBootPersonnelTenure;
import com.sundot.airport.blocked.service.IBlockedBootPersonnelTenureService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 开机人员年限分布Service业务层处理
 *
 * @author ruoyi
 * @date 2026-04-16
 */
@Service
public class BlockedBootPersonnelTenureServiceImpl extends ServiceImpl<BlockedBootPersonnelTenureMapper, BlockedBootPersonnelTenure> implements IBlockedBootPersonnelTenureService {
    @Autowired
    private BlockedBootPersonnelTenureMapper blockedBootPersonnelTenureMapper;
    @Autowired
    private ISysDeptService sysDeptService;

    /**
     * 查询开机人员年限分布
     *
     * @param id 开机人员年限分布主键
     * @return 开机人员年限分布
     */
    @Override
    public BlockedBootPersonnelTenure selectBlockedBootPersonnelTenureById(Long id) {
        return blockedBootPersonnelTenureMapper.selectBlockedBootPersonnelTenureById(id);
    }

    /**
     * 查询开机人员年限分布列表
     *
     * @param blockedBootPersonnelTenure 开机人员年限分布
     * @return 开机人员年限分布
     */
    @Override
    public List<BlockedBootPersonnelTenure> selectBlockedBootPersonnelTenureList(BlockedBootPersonnelTenure blockedBootPersonnelTenure) {
        return blockedBootPersonnelTenureMapper.selectBlockedBootPersonnelTenureList(blockedBootPersonnelTenure);
    }

    /**
     * 新增开机人员年限分布
     *
     * @param blockedBootPersonnelTenure 开机人员年限分布
     * @return 结果
     */
    @Override
    public int insertBlockedBootPersonnelTenure(BlockedBootPersonnelTenure blockedBootPersonnelTenure) {
        blockedBootPersonnelTenure.setCreateTime(DateUtils.getNowDate());
        LambdaQueryWrapper<BlockedBootPersonnelTenure> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BlockedBootPersonnelTenure::getBrigadeId, blockedBootPersonnelTenure.getBrigadeId());
        BlockedBootPersonnelTenure existingRate = blockedBootPersonnelTenureMapper.selectOne(queryWrapper);
        if (ObjUtil.isNotNull(existingRate)) {
            blockedBootPersonnelTenure.setId(existingRate.getId());
            return blockedBootPersonnelTenureMapper.updateBlockedBootPersonnelTenure(blockedBootPersonnelTenure);
        } else {
            return blockedBootPersonnelTenureMapper.insertBlockedBootPersonnelTenure(blockedBootPersonnelTenure);
        }
    }

    /**
     * 修改开机人员年限分布
     *
     * @param blockedBootPersonnelTenure 开机人员年限分布
     * @return 结果
     */
    @Override
    public int updateBlockedBootPersonnelTenure(BlockedBootPersonnelTenure blockedBootPersonnelTenure) {
        blockedBootPersonnelTenure.setUpdateTime(DateUtils.getNowDate());
        return blockedBootPersonnelTenureMapper.updateBlockedBootPersonnelTenure(blockedBootPersonnelTenure);
    }

    /**
     * 批量删除开机人员年限分布
     *
     * @param ids 需要删除的开机人员年限分布主键
     * @return 结果
     */
    @Override
    public int deleteBlockedBootPersonnelTenureByIds(Long[] ids) {
        return blockedBootPersonnelTenureMapper.deleteBlockedBootPersonnelTenureByIds(ids);
    }

    /**
     * 删除开机人员年限分布信息
     *
     * @param id 开机人员年限分布主键
     * @return 结果
     */
    @Override
    public int deleteBlockedBootPersonnelTenureById(Long id) {
        return blockedBootPersonnelTenureMapper.deleteBlockedBootPersonnelTenureById(id);
    }

    /**
     * 导入开机人员年限分布列表
     *
     * @param list            数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String importData(List<BlockedBootPersonnelTenure> list, boolean isUpdateSupport) {
        if (CollUtil.isEmpty(list)) {
            throw new ServiceException("导入开机人员年限分布数据不能为空！");
        }

        List<SysDept> deptListAll = sysDeptService.selectDeptInfoAll(new SysDept());
        Map<String, Long> deptMap = deptListAll.stream().collect(Collectors.toMap(SysDept::getDeptName, SysDept::getDeptId, (oldValue, newValue) -> newValue));

        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();

        for (BlockedBootPersonnelTenure data : list) {
            // 根据名称填充ID字段
            fillIdsByName(data, deptMap);
            try {
                if (ObjUtil.isNull(data.getBrigadeId()) || ObjUtil.isNull(data.getBrigadeName())) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、业务大队【" + data.getBrigadeName() + "】业务大队不能为空");
                    continue;
                }

                // 查询是否已存在（根据【日期+当班大队+班次】唯一）
                BlockedBootPersonnelTenure queryParam = new BlockedBootPersonnelTenure();
                queryParam.setBrigadeId(data.getBrigadeId());
                List<BlockedBootPersonnelTenure> existingList = blockedBootPersonnelTenureMapper.selectBlockedBootPersonnelTenureList(queryParam);

                if (CollUtil.isEmpty(existingList)) {
                    // 新增
                    data.setCreateTime(DateUtils.getNowDate());
                    blockedBootPersonnelTenureMapper.insertBlockedBootPersonnelTenure(data);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、业务大队【" + data.getBrigadeName() + "】导入成功");
                } else if (isUpdateSupport) {
                    // 更新
                    BlockedBootPersonnelTenure old = existingList.get(0);
                    data.setId(old.getId());
                    data.setUpdateTime(DateUtils.getNowDate());
                    blockedBootPersonnelTenureMapper.updateBlockedBootPersonnelTenure(data);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、业务大队【" + data.getBrigadeName() + "】更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、业务大队【" + data.getBrigadeName() + "】已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、业务大队【" + data.getBrigadeName() + "】导入失败：";
                failureMsg.append(msg + e.getMessage());
            }
        }

        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new ServiceException(failureMsg.toString());
        } else {
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    /**
     * 根据名称填充ID字段
     *
     * @param data 速率数据
     */
    private void fillIdsByName(BlockedBootPersonnelTenure data, Map<String, Long> deptMap) {
        // 业务大队
        if (ObjUtil.isNotNull(data.getBrigadeName())) {
            data.setBrigadeId(deptMap.get(data.getBrigadeName()));
        }
    }
}
