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

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
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 cn.hutool.core.util.StrUtil;
import com.sundot.airport.common.core.domain.entity.SysDictData;
import com.sundot.airport.system.service.ISysDictDataService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.sundot.airport.common.exception.ServiceException;
import com.sundot.airport.common.utils.DateUtils;
import com.sundot.airport.blocked.mapper.BlockedLuggagePieceDailyMapper;
import com.sundot.airport.blocked.domain.BlockedLuggagePieceDaily;
import com.sundot.airport.blocked.service.IBlockedLuggagePieceDailyService;
import com.sundot.airport.common.core.domain.entity.SysDept;
import com.sundot.airport.system.service.ISysDeptService;

/**
 * 每日各时段查堵行李Service业务层处理
 *
 * @author wangxx
 * @date 2026-04-13
 */
@Service
public class BlockedLuggagePieceDailyServiceImpl implements IBlockedLuggagePieceDailyService {
    @Autowired
    private BlockedLuggagePieceDailyMapper blockedLuggagePieceDailyMapper;

    @Autowired
    private ISysDeptService sysDeptService;

    @Autowired
    private ISysDictDataService sysDictDataService;

    /**
     * 查询每日各时段查堵行李
     *
     * @param id 每日各时段查堵行李主键
     * @return 每日各时段查堵行李
     */
    @Override
    public BlockedLuggagePieceDaily selectBlockedLuggagePieceDailyById(Long id) {
        return blockedLuggagePieceDailyMapper.selectBlockedLuggagePieceDailyById(id);
    }

    /**
     * 查询每日各时段查堵行李列表
     *
     * @param blockedLuggagePieceDaily 每日各时段查堵行李
     * @return 每日各时段查堵行李
     */
    @Override
    public List<BlockedLuggagePieceDaily> selectBlockedLuggagePieceDailyList(BlockedLuggagePieceDaily blockedLuggagePieceDaily) {
        return blockedLuggagePieceDailyMapper.selectBlockedLuggagePieceDailyList(blockedLuggagePieceDaily);
    }

    /**
     * 新增每日各时段查堵行李
     *
     * @param blockedLuggagePieceDaily 每日各时段查堵行李
     * @return 结果
     */
    @Override
    @Transactional
    public int insertBlockedLuggagePieceDaily(BlockedLuggagePieceDaily blockedLuggagePieceDaily) {
        // 根据大队名称填充ID
        fillBrigadeIdByName(blockedLuggagePieceDaily);
        calculateAndSetFields(blockedLuggagePieceDaily);
        return blockedLuggagePieceDailyMapper.insertBlockedLuggagePieceDaily(blockedLuggagePieceDaily);
    }

    /**
     * 修改每日各时段查堵行李
     *
     * @param blockedLuggagePieceDaily 每日各时段查堵行李
     * @return 结果
     */
    @Override
    @Transactional
    public int updateBlockedLuggagePieceDaily(BlockedLuggagePieceDaily blockedLuggagePieceDaily) {
        // 根据大队名称填充ID
        fillBrigadeIdByName(blockedLuggagePieceDaily);
        calculateAndSetFields(blockedLuggagePieceDaily);
        return blockedLuggagePieceDailyMapper.updateBlockedLuggagePieceDaily(blockedLuggagePieceDaily);
    }

    /**
     * 批量删除每日各时段查堵行李
     *
     * @param ids 需要删除的每日各时段查堵行李主键
     * @return 结果
     */
    @Override
    public int deleteBlockedLuggagePieceDailyByIds(Long[] ids) {
        return blockedLuggagePieceDailyMapper.deleteBlockedLuggagePieceDailyByIds(ids);
    }

    /**
     * 删除每日各时段查堵行李信息
     *
     * @param id 每日各时段查堵行李主键
     * @return 结果
     */
    @Override
    public int deleteBlockedLuggagePieceDailyById(Long id) {
        return blockedLuggagePieceDailyMapper.deleteBlockedLuggagePieceDailyById(id);
    }

    /**
     * 导入每日各时段查堵行李数据
     *
     * @param list 数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String importData(List<BlockedLuggagePieceDaily> list, boolean isUpdateSupport) {
        if (CollUtil.isEmpty(list)) {
            throw new ServiceException("导入每日各时段查堵行李数据不能为空！");
        }

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

        for (BlockedLuggagePieceDaily data : list) {
            try {
                // 根据大队名称填充ID
                fillBrigadeIdByName(data);

                // 数据校验
                if (ObjUtil.isNull(data.getStatDate())) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、统计日期【" + data.getStatDate() + "】、大队【" + data.getBrigadeName() + "】、时间段【" + data.getTimePeriod() + "】统计日期不能为空");
                    continue;
                }
                if (ObjUtil.isNull(data.getBrigadeId()) || ObjUtil.isNull(data.getBrigadeName())) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、统计日期【" + data.getStatDate() + "】、大队【" + data.getBrigadeName() + "】、时间段【" + data.getTimePeriod() + "】大队不能为空");
                    continue;
                }
                if (StrUtil.isBlank(data.getTimePeriod())) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、统计日期【" + data.getStatDate() + "】、大队【" + data.getBrigadeName() + "】、时间段【" + data.getTimePeriod() + "】时间段不能为空");
                    continue;
                }

                // 查询是否已存在（根据日期+大队ID+时间段唯一）
                BlockedLuggagePieceDaily queryParam = new BlockedLuggagePieceDaily();
                queryParam.setStatDate(data.getStatDate());
                queryParam.setBrigadeId(data.getBrigadeId());
                queryParam.setTimePeriod(data.getTimePeriod());
                List<BlockedLuggagePieceDaily> existingList = blockedLuggagePieceDailyMapper.selectBlockedLuggagePieceDailyList(queryParam);

                if (CollUtil.isEmpty(existingList)) {
                    // 新增
                    data.setCreateTime(DateUtils.getNowDate());
                    calculateAndSetFields(data);
                    blockedLuggagePieceDailyMapper.insertBlockedLuggagePieceDaily(data);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、统计日期【" + data.getStatDate() + "】、大队【" + data.getBrigadeName() + "】、时间段【" + data.getTimePeriod() + "】导入成功");
                } else if (isUpdateSupport) {
                    // 更新
                    BlockedLuggagePieceDaily old = existingList.get(0);
                    data.setId(old.getId());
                    data.setUpdateTime(DateUtils.getNowDate());
                    calculateAndSetFields(data);
                    blockedLuggagePieceDailyMapper.updateBlockedLuggagePieceDaily(data);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、统计日期【" + data.getStatDate() + "】、大队【" + data.getBrigadeName() + "】、时间段【" + data.getTimePeriod() + "】更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、统计日期【" + data.getStatDate() + "】、大队【" + data.getBrigadeName() + "】、时间段【" + data.getTimePeriod() + "】已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、统计日期【" + data.getStatDate() + "】、大队【" + data.getBrigadeName() + "】、时间段【" + data.getTimePeriod() + "】导入失败：";
                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();
    }

    /**
     * 检查数据是否重复
     *
     * @param blockedLuggagePieceDaily 统计数据
     * @return 重复的数据，如果没有重复返回null
     */
    @Override
    public BlockedLuggagePieceDaily checkDuplicate(BlockedLuggagePieceDaily blockedLuggagePieceDaily) {
        if (ObjUtil.isNull(blockedLuggagePieceDaily.getStatDate())
                || ObjUtil.isNull(blockedLuggagePieceDaily.getBrigadeId())
                || ObjUtil.isNull(blockedLuggagePieceDaily.getTimePeriod())) {
            return null;
        }

        BlockedLuggagePieceDaily queryParam = new BlockedLuggagePieceDaily();
        queryParam.setStatDate(blockedLuggagePieceDaily.getStatDate());
        queryParam.setBrigadeId(blockedLuggagePieceDaily.getBrigadeId());
        queryParam.setTimePeriod(blockedLuggagePieceDaily.getTimePeriod());
        List<BlockedLuggagePieceDaily> existingList = blockedLuggagePieceDailyMapper.selectBlockedLuggagePieceDailyList(queryParam);

        if (CollUtil.isNotEmpty(existingList)) {
            return existingList.get(0);
        }
        return null;
    }

    /**
     * 新增或更新每日各时段查堵行李（如果数据重复则覆盖更新）
     *
     * @param blockedLuggagePieceDaily 每日各时段查堵行李
     * @return 结果
     */
    @Override
    @Transactional
    public int insertOrUpdate(BlockedLuggagePieceDaily blockedLuggagePieceDaily) {
        // 检查是否重复
        BlockedLuggagePieceDaily existing = checkDuplicate(blockedLuggagePieceDaily);
        // 根据大队名称填充ID
        fillBrigadeIdByName(blockedLuggagePieceDaily);
        if (existing != null) {
            // 数据已存在，执行更新（覆盖）
            blockedLuggagePieceDaily.setId(existing.getId());
            blockedLuggagePieceDaily.setUpdateBy(blockedLuggagePieceDaily.getUpdateBy() != null
                    ? blockedLuggagePieceDaily.getUpdateBy() : blockedLuggagePieceDaily.getCreateBy());

            calculateAndSetFields(blockedLuggagePieceDaily);
            return blockedLuggagePieceDailyMapper.updateBlockedLuggagePieceDaily(blockedLuggagePieceDaily);
        } else {
            // 数据不存在，执行新增
            calculateAndSetFields(blockedLuggagePieceDaily);
            return blockedLuggagePieceDailyMapper.insertBlockedLuggagePieceDaily(blockedLuggagePieceDaily);
        }
    }

    /**
     * 计算并设置所有计算字段
     *
     * @param data 统计数据
     */
    private void calculateAndSetFields(BlockedLuggagePieceDaily data) {
        // 初始化默认值
        initDefaultValues(data);

        // 计算过检行李数
        Integer totalLuggage = (data.getT1WalkBagCount() != null ? data.getT1WalkBagCount() : 0)
                + (data.getT2WalkBagCount() != null ? data.getT2WalkBagCount() : 0)
                + (data.getT1TravelBagCount() != null ? data.getT1TravelBagCount() : 0)
                + (data.getT2TravelBagCount() != null ? data.getT2TravelBagCount() : 0);
        data.setTotalLuggageCount(totalLuggage);

        // 计算时段查堵件数
        Integer totalBlocked = (data.getT1WalkBlockedCount() != null ? data.getT1WalkBlockedCount() : 0)
                + (data.getT2WalkBlockedCount() != null ? data.getT2WalkBlockedCount() : 0)
                + (data.getT1TravelBlockedCount() != null ? data.getT1TravelBlockedCount() : 0)
                + (data.getT2TravelBlockedCount() != null ? data.getT2TravelBlockedCount() : 0);
        data.setTotalBlockedCount(totalBlocked);

        // 计算查堵万分率
        data.setBlockedRate(calculateBlockRate(totalBlocked, totalLuggage));
    }

    /**
     * 初始化默认值
     *
     * @param data 统计数据
     */
    private void initDefaultValues(BlockedLuggagePieceDaily data) {
        if (data.getT1WalkBagCount() == null) data.setT1WalkBagCount(0);
        if (data.getT1WalkBlockedCount() == null) data.setT1WalkBlockedCount(0);
        if (data.getT2WalkBagCount() == null) data.setT2WalkBagCount(0);
        if (data.getT2WalkBlockedCount() == null) data.setT2WalkBlockedCount(0);
        if (data.getT1TravelBagCount() == null) data.setT1TravelBagCount(0);
        if (data.getT1TravelBlockedCount() == null) data.setT1TravelBlockedCount(0);
        if (data.getT2TravelBagCount() == null) data.setT2TravelBagCount(0);
        if (data.getT2TravelBlockedCount() == null) data.setT2TravelBlockedCount(0);
    }

    /**
     * 计算万分率（查堵件数/过检行李数*10000）
     *
     * @param blockedCount 查堵件数
     * @param luggageCount 过检行李数
     * @return 万分率
     */
    private BigDecimal calculateBlockRate(Integer blockedCount, Integer luggageCount) {
        if (luggageCount == null || luggageCount == 0) {
            return BigDecimal.ZERO;
        }
        if (blockedCount == null) {
            blockedCount = 0;
        }
        return BigDecimal.valueOf(blockedCount)
                .multiply(BigDecimal.valueOf(10000))
                .divide(BigDecimal.valueOf(luggageCount), 4, RoundingMode.HALF_UP);
    }

    /**
     * 根据大队名称填充大队ID
     *
     * @param data 统计数据
     */
    private void fillBrigadeIdByName(BlockedLuggagePieceDaily data) {
        if (ObjUtil.isNull(data.getBrigadeId()) && StrUtil.isNotBlank(data.getBrigadeName())) {
            SysDept deptQuery = new SysDept();
            deptQuery.setDeptName(data.getBrigadeName());
            List<SysDept> deptList = sysDeptService.selectDeptList(deptQuery);
            if (CollUtil.isNotEmpty(deptList)) {
                data.setBrigadeId(deptList.get(0).getDeptId());
            }
        }

        // 时间段 - 通过查堵时间段字典查询
        if (StrUtil.isNotBlank(data.getTimePeriod())) {
            SysDictData query = new SysDictData();
            query.setDictType("blocked_time_period");
            List<SysDictData> sysDictDataList = sysDictDataService.selectDictDataList(query);
            Map<String, String> sysDictDataMap = sysDictDataList.stream().collect(Collectors.toMap(SysDictData::getDictLabel, SysDictData::getDictValue));
            data.setTimePeriod(sysDictDataMap.get(data.getTimePeriod()));
        }
    }
}
