package com.bonus.material.cityScreen.service;

import com.bonus.common.core.exception.ServiceException;
import com.bonus.material.cityScreen.DTO.CityScreenDTO;
import com.bonus.material.cityScreen.VO.*;
import com.bonus.material.cityScreen.entity.DeviceInfoEntity;
import com.bonus.material.cityScreen.mapper.CityScreenMapper;
import com.bonus.material.equipment.domain.DeptConfigRateSummary;
import com.bonus.material.equipment.service.ISysDeptService;
import org.apache.commons.lang3.ObjectUtils;
import org.hibernate.validator.internal.util.StringHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author：tqzhang
 * @Date：2025/9/14 - 15:47
 */
@Service
public class CityScreenServiceImpl implements CityScreenService {
    private static final Logger logger = LoggerFactory.getLogger(CityScreenServiceImpl.class);
    @Resource
    private CityScreenMapper cityScreenMapper;
    @Resource
    private ISysDeptService sysDeptService;

    /**
     * 基础头部数据
     *
     * @param dto 入参
     * @return List<BasicTitleData>
     */
    @Override
    public BasicTitleVO getBasicHead(CityScreenDTO dto) {
        try {
            if (StringHelper.isNullOrEmptyString(dto.getCompanyId())) {
                throw new ServiceException("公司不能为空");
            }
            String companyId = dto.getCompanyId();
            //根据公司ID查询设备总数、总价值
            BasicTitleVO titleVO = cityScreenMapper.getDeviceData(dto);
            if (titleVO == null) {
                throw new ServiceException("未查询到相关数据");
            }
            // 获取装备转换率
            DeptConfigRateSummary user = new DeptConfigRateSummary();
            List<DeptConfigRateSummary> list = sysDeptService.selectDeptConfigRatePivot(user);
            list.forEach(item -> {
                String deptId = String.valueOf(item.getCompanyId());
                if (deptId != null && deptId.equals(companyId)) {
                    titleVO.setAllocationRate(StringHelper.isNullOrEmptyString(String.valueOf(item.getConfigRate())) ? "0" : String.valueOf(item.getConfigRate()));
                }
            });
            if (ObjectUtils.isEmpty(titleVO.getAllocationRate()) || "null".equals(titleVO.getAllocationRate())) {
                titleVO.setAllocationRate("0");
            }
            //查询今日出入库设备数
            BasicTitleVO todayTitleVO = cityScreenMapper.getTodayDeviceEnterOutNum(dto);
            if (todayTitleVO != null) {
                titleVO.setEnterNum(todayTitleVO.getEnterNum());
                titleVO.setOutNum(todayTitleVO.getOutNum());
            }
            return titleVO;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new ServiceException("获取数据失败");
        }
    }

    /**
     * 装备数量价值
     *
     * @param dto 入参
     * @return List<EquipmentQuantityVO>
     */
    @Override
    public List<EquipmentQuantityVO> equipmentQuantityValue(CityScreenDTO dto) {
        try {
            List<EquipmentQuantityVO> list = new ArrayList<>();
            List<Integer> typeIds = cityScreenMapper.selectTypeIdList();
            for (int typeId : typeIds) {
                EquipmentQuantityVO vo = new EquipmentQuantityVO();
                dto.setTypeId(typeId + 1);
                dto.setYear(1);
                EquipmentQuantityVO fiveVO = cityScreenMapper.equipmentQuantityValue(dto);
                dto.setYear(2);
                EquipmentQuantityVO fiveToTenVO = cityScreenMapper.equipmentQuantityValue(dto);
                dto.setYear(3);
                EquipmentQuantityVO aboveTenVO = cityScreenMapper.equipmentQuantityValue(dto);
                vo.setDeviceQuantity(fiveVO.getDeviceQuantity() + fiveToTenVO.getDeviceQuantity() + aboveTenVO.getDeviceQuantity());
                vo.setTotalValue(fiveVO.getTotalValue().add(fiveToTenVO.getTotalValue()).add(aboveTenVO.getTotalValue()));
                vo.setDeviceType(String.valueOf(typeId));
                vo.setFiveYearCount(fiveVO.getDeviceQuantity());
                vo.setFiveToTenYearCount(fiveToTenVO.getDeviceQuantity());
                vo.setAboveTenYearCount(aboveTenVO.getDeviceQuantity());
                vo.setFiveYearRatio(vo.getTotalValue().compareTo(BigDecimal.ZERO) == 0 ? "0" : String.format("%.1f", (fiveVO.getTotalValue().divide(vo.getTotalValue(), 1, BigDecimal.ROUND_HALF_UP)).multiply(BigDecimal.valueOf(100))));
                vo.setFiveToTenYearRatio(vo.getTotalValue().compareTo(BigDecimal.ZERO) == 0 ? "0" : String.format("%.1f", (fiveToTenVO.getTotalValue().divide(vo.getTotalValue(), 1, BigDecimal.ROUND_HALF_UP)).multiply(BigDecimal.valueOf(100))));
                vo.setAboveTenYearRatio(vo.getTotalValue().compareTo(BigDecimal.ZERO) == 0 ? "0" : String.format("%.1f", (aboveTenVO.getTotalValue().divide(vo.getTotalValue(), 1, BigDecimal.ROUND_HALF_UP)).multiply(BigDecimal.valueOf(100))));
                list.add(vo);
            }
            return list;

        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new ServiceException("获取装备数量价值数据失败");
        }
    }

    /**
     * 装备状态
     *
     * @param dto 入参
     * @return List<EchartsVO>
     */
    @Override
    public List<EchartsVO> equipmentStatus(CityScreenDTO dto) {
        try {
            dto.setStatus(9);
            List<DeviceInfoEntity> list = cityScreenMapper.getDeviceInfo(dto);
            List<EchartsVO> resultList = new ArrayList<>();
            List<DeviceInfoEntity> usingList = list.stream().filter(item -> !StringHelper.isNullOrEmptyString(item.getStatus()) && item.getStatus().equals("1")).collect(Collectors.toList());
            List<DeviceInfoEntity> inTheLibraryList = list.stream().filter(item -> !StringHelper.isNullOrEmptyString(item.getStatus()) && (item.getStatus().equals("2") || item.getStatus().equals("3"))).collect(Collectors.toList());
            List<DeviceInfoEntity> repairAgainList = list.stream().filter(item -> !StringHelper.isNullOrEmptyString(item.getStatus()) && item.getStatus().equals("5")).collect(Collectors.toList());
            List<DeviceInfoEntity> sharingList = list.stream().filter(item -> !StringHelper.isNullOrEmptyString(item.getStatus()) && item.getStatus().equals("3")).collect(Collectors.toList());

            double totalSize = usingList.size() + inTheLibraryList.size() + repairAgainList.size();
            resultList.add(new EchartsVO("在用", usingList.size(), totalSize == 0 ? "0.00" : String.format("%.2f", (usingList.size() / totalSize) * 100)));
            resultList.add(new EchartsVO("在库", inTheLibraryList.size(), totalSize == 0 ? "0.00" : String.format("%.2f", (inTheLibraryList.size() / totalSize) * 100)));
            resultList.add(new EchartsVO("在修", repairAgainList.size(), totalSize == 0 ? "0.00" : String.format("%.2f", (repairAgainList.size() / totalSize) * 100)));
            resultList.add(new EchartsVO("共享", sharingList.size(), "0.00"));
            return resultList;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new ServiceException("获取装备状态数据失败");
        }
    }

    /**
     * 维修报警
     *
     * @param dto 入参
     * @return List<AlarmVO>
     */
    @Override
    public List<AlarmVO> maintenanceAlarm(CityScreenDTO dto) {
        try {
            return cityScreenMapper.maintenanceAlarm(dto);
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new ServiceException("获取维修报警数据失败");
        }
    }

    /**
     * 退役报警
     *
     * @param dto 入参
     * @return List<AlarmVO>
     */
    @Override
    public List<AlarmVO> retirementAlarm(CityScreenDTO dto) {
        try {
            return cityScreenMapper.retirementAlarm(dto);
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new ServiceException("获取退役报警数据失败");
        }
    }

    /**
     * 装备在役率
     *
     * @param dto 入参
     * @return List<EchartsVO>
     */
    @Override
    public List<EchartsVO> equipmentInServiceRate(CityScreenDTO dto) {
        try {
            dto.setStatus(9);
            List<DeviceInfoEntity> list = cityScreenMapper.getDeviceInfo(dto);
            List<EchartsVO> resultList = new ArrayList<>();
            //每种设备数量
            List<DeviceInfoEntity> powerList = list.stream().filter(item -> !StringHelper.isNullOrEmptyString(item.getTypeId()) && item.getTypeId().equals("1")).collect(Collectors.toList());
            List<DeviceInfoEntity> lineList = list.stream().filter(item -> !StringHelper.isNullOrEmptyString(item.getTypeId()) && item.getTypeId().equals("2")).collect(Collectors.toList());
            List<DeviceInfoEntity> cableList = list.stream().filter(item -> !StringHelper.isNullOrEmptyString(item.getTypeId()) && item.getTypeId().equals("3")).collect(Collectors.toList());

            int powerNum = calculateInUseCount(powerList);
            int lineNum = calculateInUseCount(lineList);
            int cableNum = calculateInUseCount(cableList);

            double totalSize = powerList.size() + lineList.size() + cableList.size();
            double useSize = powerNum + lineNum + cableNum;
            System.out.println("totalSize:" + totalSize + ",useSize:" + useSize);
            resultList.add(new EchartsVO("变电装备在用率", powerNum, calculatePercentage(powerNum, powerList.size())));
            resultList.add(new EchartsVO("线路装备在用率", lineNum, calculatePercentage(lineNum, lineList.size())));
            resultList.add(new EchartsVO("电缆装备在用率", cableNum, calculatePercentage(cableNum, cableList.size())));
            resultList.add(new EchartsVO("总体在用率", (int) useSize, calculatePercentage(useSize / 3, totalSize / 3)));
            return resultList;
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new ServiceException("获取装备在役率数据失败");
        }
    }

    private int calculateInUseCount(List<DeviceInfoEntity> list) {
        return (int) list.stream()
                .filter(item -> item.getStatus().equals("2") || item.getStatus().equals("3"))
                .count();
    }

    private String calculatePercentage(double part, double total) {
        return total == 0 ? "0.00" : String.format("%.2f", (part / total) * 100);
    }

    /**
     * 装备周转率
     *
     * @param dto 入参
     * @return List<EquipmentTurnoverRateVO>
     */
    @Override
    public List<EquipmentTurnoverRateVO> equipmentTurnoverRate(CityScreenDTO dto) {
        try {
            return cityScreenMapper.equipmentTurnoverRate(dto);
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            throw new ServiceException("获取装备周转率数据失败");
        }
    }

    /**
     * 工程在用装备情况
     *
     * @param dto 入参
     * @return List<EquipmentTurnoverRateVO>
     */
    @Override
    public List<EquipmentUseVO> equipmentInUseInTheProject(CityScreenDTO dto) {
        try {
            return cityScreenMapper.equipmentInUseInTheProject(dto);
        } catch (Exception e) {
            logger.error(e.getMessage());
            throw new ServiceException("获取工程在用装备情况数据失败");
        }
    }

    @Override
    public List<ProVO> proList(CityScreenDTO dto) {
        List<ProVO> list = cityScreenMapper.proList(dto);
        return list;
        //根据county进行分组  取每组下面useNum最大的那组数据 组成新的集合
//        return list.stream().collect(Collectors.groupingBy(ProVO::getCounty)).values().stream()
//                .map(list1 -> list1.stream().max(Comparator.comparing(ProVO::getUseNum))
//                        .orElse(null)).collect(Collectors.toList());
    }
}
