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

import com.sundot.airport.common.core.domain.BaseLargeScreenQueryParamDto;
import com.sundot.airport.common.core.domain.entity.SysUser;
import com.sundot.airport.item.domain.*;
import com.sundot.airport.item.mapper.ItemLargeScreenMapper;
import com.sundot.airport.item.service.ItemLargeScreenService;
import com.sundot.airport.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 查获大屏Service业务层处理
 *
 * @author ruoyi
 * @date 2025-07-10
 */
@Service
public class ItemLargeScreenServiceImpl implements ItemLargeScreenService {

    @Autowired
    private ItemLargeScreenMapper itemLargeScreenMapper;
    @Autowired
    private ISysUserService sysUserService;

    /**
     * 移交公安情况
     *
     * @param dto 大屏查询参数
     * @return 移交公安情况
     */
    @Override
    public List<ItemLargeScreenInfoDto> police(BaseLargeScreenQueryParamDto dto) {
        return itemLargeScreenMapper.police(dto);
    }

    /**
     * 故意隐匿情况
     *
     * @param dto 大屏查询参数
     * @return 故意隐匿情况
     */
    @Override
    public List<ItemLargeScreenInfoDto> conceal(BaseLargeScreenQueryParamDto dto) {
        return itemLargeScreenMapper.conceal(dto);
    }

    /**
     * 查获类别分布
     *
     * @param dto 大屏查询参数
     * @return 查获类别分布
     */
    @Override
    public List<ItemLargeScreenCommonDto> category(BaseLargeScreenQueryParamDto dto) {
        BigDecimal totalSum = itemLargeScreenMapper.getTotalSum(dto);
        if (totalSum.compareTo(BigDecimal.ZERO) == 0) {
            return Collections.emptyList();
        }
        List<ItemLargeScreenCommonDto> result = itemLargeScreenMapper.category(dto);
        result.forEach(item -> item.setScale(item.getTotal().multiply(new BigDecimal("100")).divide(totalSum, 2, BigDecimal.ROUND_HALF_UP)));
        return result;
    }

    /**
     * 查获岗位分布
     *
     * @param dto 大屏查询参数
     * @return 查获岗位分布
     */
    @Override
    public List<ItemLargeScreenCommonDto> post(BaseLargeScreenQueryParamDto dto) {
        BigDecimal totalSum = itemLargeScreenMapper.getTotalSum(dto);
        if (totalSum.compareTo(BigDecimal.ZERO) == 0) {
            return Collections.emptyList();
        }
        List<ItemLargeScreenCommonDto> result = itemLargeScreenMapper.post(dto);
        result.forEach(item -> item.setScale(item.getTotal().multiply(new BigDecimal("100")).divide(totalSum, 2, BigDecimal.ROUND_HALF_UP)));
        return result;
    }

    /**
     * 查获总数量+移交公安数量+故意隐匿数量
     *
     * @param dto 大屏查询参数
     * @return 查获总数量+移交公安数量+故意隐匿数量
     */
    @Override
    public ItemLargeScreenTotalSomeDto getTotalSome(BaseLargeScreenQueryParamDto dto) {
        if (dto.getSpecifiedDate() == null) {
            dto.setSpecifiedDate(Date.from(LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant()));
        }
        ItemLargeScreenTotalSomeDto result = itemLargeScreenMapper.getTotalSome(dto);

        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dto.getSpecifiedDate());
        calendar.add(Calendar.DAY_OF_MONTH, -1);
        Date previousDate = calendar.getTime();
        dto.setSpecifiedDate(previousDate);
        ItemLargeScreenTotalSomeDto before = itemLargeScreenMapper.getTotalSome(dto);
        result.setTotalBefore(before.getTotal());
        result.setPoliceTotalBefore(before.getPoliceTotal());
        result.setConcealTotalBefore(before.getConcealTotal());
        return result;
    }

    /**
     * app端查获总数量+移交公安数量+故意隐匿数量
     *
     * @param dto 大屏查询参数
     * @return
     */
    @Override
    public ItemLargeScreenTotalSomeDto getAppTotalSome(BaseLargeScreenQueryParamDto dto) {
        return itemLargeScreenMapper.getTotalSome(dto);
    }

    /**
     * 查获排名
     *
     * @param dto  大屏查询参数
     * @param type 类型:1=按科室;2=按班组;3=按个人;4=按大队
     * @return 查获排名
     */
    @Override
    public List<ItemLargeScreenCommonDto> rank(BaseLargeScreenQueryParamDto dto, int type) {
        BigDecimal totalSum = itemLargeScreenMapper.getTotalSum(dto);
        if (totalSum.compareTo(BigDecimal.ZERO) == 0) {
            return Collections.emptyList();
        }
        List<ItemLargeScreenCommonDto> result;
        switch (type) {
            case 1:
                result = itemLargeScreenMapper.rankByDepartment(dto);
                break;
            case 2:
                result = itemLargeScreenMapper.rankByTeam(dto);
                break;
            case 3:
                result = itemLargeScreenMapper.rankByIndividual(dto);
                for (ItemLargeScreenCommonDto itemLargeScreenCommonDto : result) {
                    if (Objects.nonNull(itemLargeScreenCommonDto)) {
                        SysUser sysUser = sysUserService.selectUserById(itemLargeScreenCommonDto.getId());
                        if (Objects.nonNull(sysUser)) {
                            itemLargeScreenCommonDto.setName(sysUser.getNickName());
                        }
                    }
                }
                break;
            case 4:
                result = itemLargeScreenMapper.rankByBrigade(dto);
                break;
            default:
                return Collections.emptyList();
        }
        result.forEach(item -> item.setScale(item.getTotal().multiply(new BigDecimal("100")).divide(totalSum, 2, BigDecimal.ROUND_HALF_UP)));
        return result;
    }

    /**
     * 查获时段分布
     *
     * @param dto 大屏查询参数
     * @return 查获时段分布
     */
    @Override
    public List<ItemLargeScreenTimeSpanDto> timeSpan(BaseLargeScreenQueryParamDto dto) {
        if (dto.getSpecifiedDate() == null) {
            dto.setSpecifiedDate(Date.from(LocalDate.now().atStartOfDay(ZoneId.systemDefault()).toInstant()));
        }
        return itemLargeScreenMapper.timeSpan(dto);
    }

    /**
     * app端 查获时段分布
     *
     * @param dto 大屏查询参数
     * @return 查获时段分布
     */
    @Override
    public List<ItemLargeScreenTimeSpanDto> appTimeSpan(BaseLargeScreenQueryParamDto dto) {
        return itemLargeScreenMapper.timeSpan(dto);
    }


    /**
     * 查获位置分布
     *
     * @param dto 大屏查询参数
     * @return 查获位置分布
     */
    @Override
    public List<ItemLargeScreenPositionDto> position(BaseLargeScreenQueryParamDto dto) {
        List<ItemLargeScreenPositionDto> positions = itemLargeScreenMapper.position(dto);
        if (!positions.isEmpty()) {
            positions.forEach(p -> {
                if (p.getCheckPositionNameOne() != null && p.getCheckPositionNameOne().contains("/")) {
                    String[] arr = p.getCheckPositionNameOne().split("/", 2);
                    p.setCheckPositionNameOne(arr[0]);
                    p.setCheckPositionNameTwo(arr[1]);
                }
            });


            // 3. 分组并追加汇总
            List<ItemLargeScreenPositionDto> result = new ArrayList<>();
            Map<String, List<ItemLargeScreenPositionDto>> grouped =
                    positions.stream().collect(Collectors.groupingBy(ItemLargeScreenPositionDto::getCheckPositionNameOne));

            grouped.forEach((groupName, groupList) -> {
                // 3.1 先加入组内原始数据
                result.addAll(groupList);

                // 3.2 计算组内 BigDecimal 总和
                BigDecimal sum = groupList.stream()
                        .map(ItemLargeScreenPositionDto::getTotal)
                        .filter(Objects::nonNull)
                        .reduce(BigDecimal.ZERO, BigDecimal::add);

                // 3.3 构造汇总记录
                ItemLargeScreenPositionDto summary = new ItemLargeScreenPositionDto();
                summary.setCheckPositionCodeOne("TOTAL"); // 可自定义
                summary.setCheckPositionNameOne(groupName);
                summary.setCheckPositionCodeTwo("无");
                summary.setCheckPositionNameTwo("无");
                summary.setTotal(sum);

                result.add(summary);
            });
            // 按拆分后的 checkPositionNameOne 升序
            result.sort(
                    Comparator.comparing(ItemLargeScreenPositionDto::getCheckPositionNameOne,
                            Comparator.nullsFirst(String::compareTo))
            );

            return result;
        }
        return positions;
    }

    /**
     * app端 查获位置分布
     *
     * @param dto
     * @return
     */
    @Override
    public List<ItemLargeScreenPositionAppDto> appPosition(BaseLargeScreenQueryParamDto dto) {
        return itemLargeScreenMapper.appPosition(dto);
    }

    /**
     * 查获通道分布
     *
     * @param dto 大屏查询参数
     * @return 查获通道分布
     */
    @Override
    public List<ItemLargeScreenChannelDto> channel(BaseLargeScreenQueryParamDto dto) {
        return itemLargeScreenMapper.channel(dto);
    }

}
