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.core.domain.entity.SysDictData;
import com.sundot.airport.common.enums.ShiftEnum;
import com.sundot.airport.common.exception.ServiceException;
import com.sundot.airport.common.utils.DateUtils;
import com.sundot.airport.system.service.ISysDeptService;
import com.sundot.airport.system.service.ISysDictDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sundot.airport.blocked.mapper.BlockedRateMapper;
import com.sundot.airport.blocked.domain.BlockedRate;
import com.sundot.airport.blocked.service.IBlockedRateService;
import org.springframework.transaction.annotation.Transactional;

/**
 * 速率Service业务层处理
 *
 * @author ruoyi
 * @date 2026-04-13
 */
@Service
public class BlockedRateServiceImpl extends ServiceImpl<BlockedRateMapper, BlockedRate> implements IBlockedRateService {
    @Autowired
    private BlockedRateMapper blockedRateMapper;
    @Autowired
    private ISysDeptService sysDeptService;
    @Autowired
    private ISysDictDataService sysDictDataService;

    /**
     * 查询速率
     *
     * @param id 速率主键
     * @return 速率
     */
    @Override
    public BlockedRate selectBlockedRateById(Long id) {
        return blockedRateMapper.selectBlockedRateById(id);
    }

    /**
     * 查询速率列表
     *
     * @param blockedRate 速率
     * @return 速率
     */
    @Override
    public List<BlockedRate> selectBlockedRateList(BlockedRate blockedRate) {
        return blockedRateMapper.selectBlockedRateList(blockedRate);
    }

    /**
     * 新增速率
     *
     * @param blockedRate 速率
     * @return 结果
     */
    @Override
    public int insertBlockedRate(BlockedRate blockedRate) {
        LambdaQueryWrapper<BlockedRate> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(BlockedRate::getStatDate, blockedRate.getStatDate())
                .eq(BlockedRate::getDutyBrigadeId, blockedRate.getDutyBrigadeId())
                .eq(BlockedRate::getShift, blockedRate.getShift());
        BlockedRate existingRate = blockedRateMapper.selectOne(queryWrapper);
        if (ObjUtil.isNotNull(existingRate)) {
            blockedRate.setUpdateTime(DateUtils.getNowDate());
            blockedRate.setId(existingRate.getId());
            return blockedRateMapper.updateBlockedRate(blockedRate);
        } else {
            blockedRate.setCreateTime(DateUtils.getNowDate());
            return blockedRateMapper.insertBlockedRate(blockedRate);
        }
    }

    /**
     * 修改速率
     *
     * @param blockedRate 速率
     * @return 结果
     */
    @Override
    public int updateBlockedRate(BlockedRate blockedRate) {
        blockedRate.setUpdateTime(DateUtils.getNowDate());
        return blockedRateMapper.updateBlockedRate(blockedRate);
    }

    /**
     * 批量删除速率
     *
     * @param ids 需要删除的速率主键
     * @return 结果
     */
    @Override
    public int deleteBlockedRateByIds(Long[] ids) {
        return blockedRateMapper.deleteBlockedRateByIds(ids);
    }

    /**
     * 删除速率信息
     *
     * @param id 速率主键
     * @return 结果
     */
    @Override
    public int deleteBlockedRateById(Long id) {
        return blockedRateMapper.deleteBlockedRateById(id);
    }

    /**
     * 导入速率数据
     *
     * @param list            数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String importData(List<BlockedRate> 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));

        SysDictData shiftQuery = new SysDictData();
        shiftQuery.setDictType("shift");
        List<SysDictData> shiftList = sysDictDataService.selectDictDataList(shiftQuery);
        Map<String, String> shiftMap = shiftList.stream().collect(Collectors.toMap(SysDictData::getDictLabel, SysDictData::getDictValue));

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

        for (BlockedRate data : list) {
            // 根据名称填充ID字段
            fillIdsByName(data, deptMap, shiftMap);
            try {
                if (ObjUtil.isNull(data.getStatDate())) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、日期【" + data.getStatDate() + "】、当班大队【" + data.getDutyBrigadeName() + "】、班次【" + data.getShiftDesc() + "】日期不能为空");
                    continue;
                }
                if (ObjUtil.isNull(data.getDutyBrigadeId()) || ObjUtil.isNull(data.getDutyBrigadeName())) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、日期【" + data.getStatDate() + "】、当班大队【" + data.getDutyBrigadeName() + "】、班次【" + data.getShiftDesc() + "】当班大队不能为空");
                    continue;
                }
                if (ObjUtil.isNull(data.getShift())) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、日期【" + data.getStatDate() + "】、当班大队【" + data.getDutyBrigadeName() + "】、班次【" + data.getShiftDesc() + "】班次不能为空");
                    continue;
                }

                // 查询是否已存在（根据【日期+当班大队+班次】唯一）
                BlockedRate queryParam = new BlockedRate();
                queryParam.setStatDate(data.getStatDate());
                queryParam.setDutyBrigadeId(data.getDutyBrigadeId());
                queryParam.setShift(data.getShift());
                List<BlockedRate> existingList = blockedRateMapper.selectBlockedRateList(queryParam);

                if (CollUtil.isEmpty(existingList)) {
                    // 新增
                    data.setCreateTime(DateUtils.getNowDate());
                    blockedRateMapper.insertBlockedRate(data);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、日期【" + data.getStatDate() + "】、当班大队【" + data.getDutyBrigadeName() + "】、班次【" + data.getShiftDesc() + "】导入成功");
                } else if (isUpdateSupport) {
                    // 更新
                    BlockedRate old = existingList.get(0);
                    data.setId(old.getId());
                    data.setUpdateTime(DateUtils.getNowDate());
                    blockedRateMapper.updateBlockedRate(data);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、日期【" + data.getStatDate() + "】、当班大队【" + data.getDutyBrigadeName() + "】、班次【" + data.getShiftDesc() + "】更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、日期【" + data.getStatDate() + "】、当班大队【" + data.getDutyBrigadeName() + "】、班次【" + data.getShiftDesc() + "】已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、日期【" + data.getStatDate() + "】、当班大队【" + data.getDutyBrigadeName() + "】、班次【" + data.getShiftDesc() + "】导入失败：";
                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(BlockedRate data, Map<String, Long> deptMap, Map<String, String> shiftMap) {
        // 当班大队
        if (ObjUtil.isNotNull(data.getDutyBrigadeName())) {
            data.setDutyBrigadeId(deptMap.get(data.getDutyBrigadeName()));
        }

        // 班次
        if (ObjUtil.isNotNull(data.getShiftDesc())) {
            data.setShift(shiftMap.get(data.getShiftDesc()));
        }
    }
}
