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

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
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.BlockedLuggageStatisticsDailyMapper;
import com.sundot.airport.blocked.domain.BlockedLuggageStatisticsDaily;
import com.sundot.airport.blocked.service.IBlockedLuggageStatisticsDailyService;
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 BlockedLuggageStatisticsDailyServiceImpl implements IBlockedLuggageStatisticsDailyService {
    @Autowired
    private BlockedLuggageStatisticsDailyMapper blockedLuggageStatisticsDailyMapper;

    @Autowired
    private ISysDeptService sysDeptService;

    /**
     * 查询每日行李过检查堵统计
     *
     * @param id 每日行李过检查堵统计主键
     * @return 每日行李过检查堵统计
     */
    @Override
    public BlockedLuggageStatisticsDaily selectBlockedLuggageStatisticsDailyById(Long id) {
        return blockedLuggageStatisticsDailyMapper.selectBlockedLuggageStatisticsDailyById(id);
    }

    /**
     * 查询每日行李过检查堵统计列表
     *
     * @param blockedLuggageStatisticsDaily 每日行李过检查堵统计
     * @return 每日行李过检查堵统计
     */
    @Override
    public List<BlockedLuggageStatisticsDaily> selectBlockedLuggageStatisticsDailyList(BlockedLuggageStatisticsDaily blockedLuggageStatisticsDaily) {
        return blockedLuggageStatisticsDailyMapper.selectBlockedLuggageStatisticsDailyList(blockedLuggageStatisticsDaily);
    }

    /**
     * 新增每日行李过检查堵统计
     *
     * @param blockedLuggageStatisticsDaily 每日行李过检查堵统计
     * @return 结果
     */
    @Override
    @Transactional
    public int insertBlockedLuggageStatisticsDaily(BlockedLuggageStatisticsDaily blockedLuggageStatisticsDaily) {
        // 根据大队名称填充ID
        fillBrigadeIdByName(blockedLuggageStatisticsDaily);
        calculateAndSetFields(blockedLuggageStatisticsDaily);
        return blockedLuggageStatisticsDailyMapper.insertBlockedLuggageStatisticsDaily(blockedLuggageStatisticsDaily);
    }

    /**
     * 修改每日行李过检查堵统计
     *
     * @param blockedLuggageStatisticsDaily 每日行李过检查堵统计
     * @return 结果
     */
    @Override
    @Transactional
    public int updateBlockedLuggageStatisticsDaily(BlockedLuggageStatisticsDaily blockedLuggageStatisticsDaily) {
        // 根据大队名称填充ID
        fillBrigadeIdByName(blockedLuggageStatisticsDaily);
        calculateAndSetFields(blockedLuggageStatisticsDaily);
        return blockedLuggageStatisticsDailyMapper.updateBlockedLuggageStatisticsDaily(blockedLuggageStatisticsDaily);
    }

    /**
     * 批量删除每日行李过检查堵统计
     *
     * @param ids 需要删除的每日行李过检查堵统计主键
     * @return 结果
     */
    @Override
    public int deleteBlockedLuggageStatisticsDailyByIds(Long[] ids) {
        return blockedLuggageStatisticsDailyMapper.deleteBlockedLuggageStatisticsDailyByIds(ids);
    }

    /**
     * 删除每日行李过检查堵统计信息
     *
     * @param id 每日行李过检查堵统计主键
     * @return 结果
     */
    @Override
    public int deleteBlockedLuggageStatisticsDailyById(Long id) {
        return blockedLuggageStatisticsDailyMapper.deleteBlockedLuggageStatisticsDailyById(id);
    }

    /**
     * 导入每日行李过检查堵统计数据
     *
     * @param list 数据列表
     * @param isUpdateSupport 是否更新支持，如果已存在，则进行更新数据
     * @return 结果
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public String importData(List<BlockedLuggageStatisticsDaily> 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 (BlockedLuggageStatisticsDaily data : list) {
            try {
                fillBrigadeIdByName(data);
                // 数据校验
                if (ObjUtil.isNull(data.getStatDate())) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、统计日期【" + data.getStatDate() + "】、班次类型【" + data.getShiftType() + "】、当班大队【" + data.getBrigadeName() + "】统计日期不能为空");
                    continue;
                }
                if (ObjUtil.isNull(data.getShiftType())) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、统计日期【" + data.getStatDate() + "】、班次类型【" + data.getShiftType() + "】、当班大队【" + data.getBrigadeName() + "】班次类型不能为空");
                    continue;
                }
                if (ObjUtil.isNull(data.getBrigadeId()) || ObjUtil.isNull(data.getBrigadeName())) {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、统计日期【" + data.getStatDate() + "】、班次类型【" + data.getShiftType() + "】、当班大队【" + data.getBrigadeName() + "】当班大队不能为空");
                    continue;
                }

                // 查询是否已存在（根据日期+班次+大队ID唯一索引）
                BlockedLuggageStatisticsDaily queryParam = new BlockedLuggageStatisticsDaily();
                queryParam.setStatDate(data.getStatDate());
                queryParam.setShiftType(data.getShiftType());
                queryParam.setBrigadeId(data.getBrigadeId());
                List<BlockedLuggageStatisticsDaily> existingList = blockedLuggageStatisticsDailyMapper.selectBlockedLuggageStatisticsDailyList(queryParam);

                if (CollUtil.isEmpty(existingList)) {
                    // 新增
                    data.setCreateTime(DateUtils.getNowDate());
                    calculateAndSetFields(data);
                    blockedLuggageStatisticsDailyMapper.insertBlockedLuggageStatisticsDaily(data);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、统计日期【" + data.getStatDate() + "】、班次类型【" + data.getShiftType() + "】、当班大队【" + data.getBrigadeName() + "】导入成功");
                } else if (isUpdateSupport) {
                    // 更新
                    BlockedLuggageStatisticsDaily old = existingList.get(0);
                    data.setId(old.getId());
                    data.setUpdateTime(DateUtils.getNowDate());
                    calculateAndSetFields(data);
                    blockedLuggageStatisticsDailyMapper.updateBlockedLuggageStatisticsDaily(data);
                    successNum++;
                    successMsg.append("<br/>" + successNum + "、统计日期【" + data.getStatDate() + "】、班次类型【" + data.getShiftType() + "】、当班大队【" + data.getBrigadeName() + "】更新成功");
                } else {
                    failureNum++;
                    failureMsg.append("<br/>" + failureNum + "、统计日期【" + data.getStatDate() + "】、班次类型【" + data.getShiftType() + "】、当班大队【" + data.getBrigadeName() + "】已存在");
                }
            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、统计日期【" + data.getStatDate() + "】、班次类型【" + data.getShiftType() + "】、当班大队【" + 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();
    }

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

        // 计算过检行李合计
        Integer totalLuggage = (data.getT1TravelLuggageCount() != null ? data.getT1TravelLuggageCount() : 0)
                + (data.getT1WalkLuggageCount() != null ? data.getT1WalkLuggageCount() : 0)
                + (data.getT2TravelLuggageCount() != null ? data.getT2TravelLuggageCount() : 0)
                + (data.getT2WalkLuggageCount() != null ? data.getT2WalkLuggageCount() : 0);
        data.setTotalLuggageCount(totalLuggage);

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

        // 当日查堵件数等于查堵合计件数
        data.setDailyBlockedCount(totalBlocked);

        // 计算万分率
        data.setT1TravelBlockRate(calculateBlockRate(data.getT1TravelBlockedCount(), data.getT1TravelLuggageCount()));
        data.setT2TravelBlockRate(calculateBlockRate(data.getT2TravelBlockedCount(), data.getT2TravelLuggageCount()));
        data.setT1WalkBlockRate(calculateBlockRate(data.getT1WalkBlockedCount(), data.getT1WalkLuggageCount()));
        data.setT2WalkBlockRate(calculateBlockRate(data.getT2WalkBlockedCount(), data.getT2WalkLuggageCount()));
        
        // 计算旅检万分查堵率：(T1旅检查堵件数+T2旅检查堵件数)/(T1旅检过检行李数+T2旅检过检行李数)*10000
        Integer travelBlockedCount = (data.getT1TravelBlockedCount() != null ? data.getT1TravelBlockedCount() : 0)
                + (data.getT2TravelBlockedCount() != null ? data.getT2TravelBlockedCount() : 0);
        Integer travelLuggageCount = (data.getT1TravelLuggageCount() != null ? data.getT1TravelLuggageCount() : 0)
                + (data.getT2TravelLuggageCount() != null ? data.getT2TravelLuggageCount() : 0);
        data.setTravelInspectionBlockRate(calculateBlockRate(travelBlockedCount, travelLuggageCount));
        
        // 计算行检万分查堵率：(T1行检查堵件数+T2行检查堵件数)/(T1行检过检行李数+T2行检过检行李数)*10000
        Integer walkBlockedCount = (data.getT1WalkBlockedCount() != null ? data.getT1WalkBlockedCount() : 0)
                + (data.getT2WalkBlockedCount() != null ? data.getT2WalkBlockedCount() : 0);
        Integer walkLuggageCount = (data.getT1WalkLuggageCount() != null ? data.getT1WalkLuggageCount() : 0)
                + (data.getT2WalkLuggageCount() != null ? data.getT2WalkLuggageCount() : 0);
        data.setWalkInspectionBlockRate(calculateBlockRate(walkBlockedCount, walkLuggageCount));
        
        data.setTotalBlockRate(calculateBlockRate(totalBlocked, totalLuggage));
        data.setDailyBlockRate(calculateBlockRate(totalBlocked, totalLuggage));

        // 计算AI相关合计
        Integer aiReviewTotal = (data.getT1ReviewImageTotal() != null ? data.getT1ReviewImageTotal() : 0)
                + (data.getT2ReviewImageTotal() != null ? data.getT2ReviewImageTotal() : 0);
        data.setAiReviewImageTotal(aiReviewTotal);

        Integer aiMarkTotal = (data.getT1AiMarkTotal() != null ? data.getT1AiMarkTotal() : 0)
                + (data.getT2AiMarkTotal() != null ? data.getT2AiMarkTotal() : 0);
        data.setAiMarkTotal(aiMarkTotal);

        Integer aiErrorTotal = (data.getT1AiErrorTotal() != null ? data.getT1AiErrorTotal() : 0)
                + (data.getT2AiErrorTotal() != null ? data.getT2AiErrorTotal() : 0);
        data.setAiErrorImageTotal(aiErrorTotal);

        Integer aiMissTotal = (data.getT1AiMissTotal() != null ? data.getT1AiMissTotal() : 0)
                + (data.getT2AiMissTotal() != null ? data.getT2AiMissTotal() : 0);
        data.setAiMissImageTotal(aiMissTotal);
    }

    /**
     * 初始化默认值
     *
     * @param data 统计数据
     */
    private void initDefaultValues(BlockedLuggageStatisticsDaily data) {
        if (data.getT1TravelLuggageCount() == null) data.setT1TravelLuggageCount(0);
        if (data.getT1WalkLuggageCount() == null) data.setT1WalkLuggageCount(0);
        if (data.getT2TravelLuggageCount() == null) data.setT2TravelLuggageCount(0);
        if (data.getT2WalkLuggageCount() == null) data.setT2WalkLuggageCount(0);
        if (data.getT1TravelBlockedCount() == null) data.setT1TravelBlockedCount(0);
        if (data.getT2TravelBlockedCount() == null) data.setT2TravelBlockedCount(0);
        if (data.getT1WalkBlockedCount() == null) data.setT1WalkBlockedCount(0);
        if (data.getT2WalkBlockedCount() == null) data.setT2WalkBlockedCount(0);
        if (data.getT1ReviewImageTotal() == null) data.setT1ReviewImageTotal(0);
        if (data.getT1AiMarkTotal() == null) data.setT1AiMarkTotal(0);
        if (data.getT1AiErrorTotal() == null) data.setT1AiErrorTotal(0);
        if (data.getT1AiMissTotal() == null) data.setT1AiMissTotal(0);
        if (data.getT2ReviewImageTotal() == null) data.setT2ReviewImageTotal(0);
        if (data.getT2AiMarkTotal() == null) data.setT2AiMarkTotal(0);
        if (data.getT2AiErrorTotal() == null) data.setT2AiErrorTotal(0);
        if (data.getT2AiMissTotal() == null) data.setT2AiMissTotal(0);
        if (data.getOtherVipCount() == null) data.setOtherVipCount(0);
    }

    /**
     * 计算万分率（查堵件数/过检行李数*10000）
     *
     * @param blockedCount 查堵件数
     * @param luggageCount 过检行李数
     * @return 万分率（保留2位小数）
     */
    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), 2, RoundingMode.HALF_UP);
    }

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

        BlockedLuggageStatisticsDaily queryParam = new BlockedLuggageStatisticsDaily();
        queryParam.setStatDate(blockedLuggageStatisticsDaily.getStatDate());
        queryParam.setShiftType(blockedLuggageStatisticsDaily.getShiftType());
        queryParam.setBrigadeId(blockedLuggageStatisticsDaily.getBrigadeId());
        List<BlockedLuggageStatisticsDaily> existingList = blockedLuggageStatisticsDailyMapper.selectBlockedLuggageStatisticsDailyList(queryParam);

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

    /**
     * 新增或更新每日行李过检查堵统计（如果数据重复则覆盖更新）
     *
     * @param blockedLuggageStatisticsDaily 每日行李过检查堵统计
     * @return 结果
     */
    @Override
    @Transactional
    public int insertOrUpdate(BlockedLuggageStatisticsDaily blockedLuggageStatisticsDaily) {
        // 检查是否重复
        BlockedLuggageStatisticsDaily existing = checkDuplicate(blockedLuggageStatisticsDaily);
        // 根据大队名称填充ID
        fillBrigadeIdByName(blockedLuggageStatisticsDaily);
        if (existing != null) {
            // 数据已存在，执行更新（覆盖）
            blockedLuggageStatisticsDaily.setId(existing.getId());
            blockedLuggageStatisticsDaily.setUpdateBy(blockedLuggageStatisticsDaily.getUpdateBy() != null
                    ? blockedLuggageStatisticsDaily.getUpdateBy() : blockedLuggageStatisticsDaily.getCreateBy());
            calculateAndSetFields(blockedLuggageStatisticsDaily);
            return blockedLuggageStatisticsDailyMapper.updateBlockedLuggageStatisticsDaily(blockedLuggageStatisticsDaily);
        } else {
            // 数据不存在，执行新增
            calculateAndSetFields(blockedLuggageStatisticsDaily);
            return blockedLuggageStatisticsDailyMapper.insertBlockedLuggageStatisticsDaily(blockedLuggageStatisticsDaily);
        }
    }

    /**
     * 根据大队名称填充大队ID
     *
     * @param data 统计数据
     */
    private void fillBrigadeIdByName(BlockedLuggageStatisticsDaily 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());
            }
        }
    }
}
