package cd.casic.ci.process.process.service.dataAnalysis.Impl;

import cd.casic.ci.process.dto.resp.dataAnalysis.DataAnalysisResp;
import cd.casic.ci.process.process.dao.history.PipPipelineHisInstanceDao;
import cd.casic.ci.process.process.dao.vulInfo.VulInfoDao;
import cd.casic.ci.process.process.dataObject.volumnInfo.VulInfo;
import cd.casic.ci.process.process.service.dataAnalysis.DataAnalysisService;
import cd.casic.framework.datapermission.core.dal.AdminUserMapper;
import cd.casic.module.machine.dal.dataobject.MachineInfoDO;
import cd.casic.module.machine.dal.mysql.MachineInfoMapper;
import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: Paul
 * @create: 2025-07-29 16:17
 */
@Service
public class DataAnalysisServiceImpl implements DataAnalysisService {

    @Resource
    private AdminUserMapper userMapper;

    @Resource
    private VulInfoDao vulInfoDao;

    @Resource
    private PipPipelineHisInstanceDao pipelineHisInstanceDao;

    @Resource
    private MachineInfoMapper machineInfoMapper;

        private static final Map<String, String> provinceCapitalMap = new HashMap<>();
        static {
            provinceCapitalMap.put("河北省", "石家庄市");
            provinceCapitalMap.put("山西", "太原");
            provinceCapitalMap.put("辽宁", "沈阳");
            provinceCapitalMap.put("吉林", "长春");
            provinceCapitalMap.put("黑龙江", "哈尔滨");
            provinceCapitalMap.put("江苏省", "南京市");
            provinceCapitalMap.put("浙江", "杭州");
            provinceCapitalMap.put("安徽", "合肥");
            provinceCapitalMap.put("福建", "福州");
            provinceCapitalMap.put("江西", "南昌");
            provinceCapitalMap.put("山东", "济南");
            provinceCapitalMap.put("河南", "郑州");
            provinceCapitalMap.put("湖北省", "武汉市");
            provinceCapitalMap.put("湖南省", "长沙市");
            provinceCapitalMap.put("广东省", "广州市");
            provinceCapitalMap.put("海南", "海口");
            provinceCapitalMap.put("四川省", "成都市");
            provinceCapitalMap.put("贵州", "贵阳");
            provinceCapitalMap.put("云南", "昆明");
            provinceCapitalMap.put("陕西", "西安");
            provinceCapitalMap.put("甘肃", "兰州");
            provinceCapitalMap.put("青海", "西宁");
        }

    @Override
    public String getUseUserSUM(String city) {
        return userMapper.selectCount().toString();
    }

    @Override
    public String getTaskSUM(String city) {
        return pipelineHisInstanceDao.selectCount().toString();
    }

    @Override
    public String getVulSUM(String city) {
        return vulInfoDao.selectCount(new QueryWrapper<VulInfo>().lambda().eq(Objects.nonNull(city),VulInfo::getCity,city)).toString();
    }

    public String getPerilousVulSUM(String city){
        return vulInfoDao.selectCount(new LambdaQueryWrapper<VulInfo>().eq(Objects.nonNull(city),VulInfo::getCity,city).eq(VulInfo::getSeverity,2)).toString();
    }

    @Override
    public DataAnalysisResp getUserAndTaskDataCount(String city) {
        return DataAnalysisResp.builder().scanVulSUM("101125698234").useUserSUM(getUseUserSUM(city))
                .taskSUM(getTaskSUM(city)).vulSUM(getVulSUM(city)).perilousVulSUM(getPerilousVulSUM(city)).build();
    }

    @Override
    public List<DataAnalysisResp.HoopVulCount> getHoopVulCountList() {
        Integer integer = Integer.decode(getVulSUM(null));
        if (integer == 0) {
            return null;
        }
        QueryWrapper<VulInfo> wrapper = new QueryWrapper<>();
        wrapper.select("city", "COUNT(*) as value")
                .groupBy("city");
        List<Map<String, Object>> listMaps = vulInfoDao.selectMaps(wrapper);
        List<DataAnalysisResp.HoopVulCount> rest = new ArrayList<>();
        listMaps.forEach(map -> {
            DataAnalysisResp.HoopVulCount hoopVulCount = BeanUtil.mapToBean(map, DataAnalysisResp.HoopVulCount.class, false);
            String format = new DecimalFormat("0.00%").format(hoopVulCount.getValue().divide(new BigDecimal(integer), 4, RoundingMode.HALF_UP));
            hoopVulCount.setCount(format);
            rest.add(hoopVulCount);
        });
        return rest;
    }

    @Override
    public List<DataAnalysisResp.ResourceDistCount> getResourceDistCountList(String city) {
        List<MachineInfoDO> machineInfoDOS = machineInfoMapper.selectList();
        List<DataAnalysisResp.ResourceDistCount> distCountList = machineInfoDOS.stream().map(obj -> {
            DataAnalysisResp.ResourceDistCount distCount = new DataAnalysisResp.ResourceDistCount();
            BeanUtil.copyProperties(obj, distCount);
            return distCount;
        }).collect(Collectors.toList());
        if (Objects.nonNull(city)) {
            String srt = Optional.ofNullable(provinceCapitalMap.get(city)).orElse(city);
            return distCountList.stream().filter(a -> srt.equals(a.getCountry())).toList();
        }
        return distCountList;
    }

    @Override
    public List<VulInfo> getVulMonitorCountList(String city) {
        if (Objects.nonNull(city)) {
            city = Optional.ofNullable(provinceCapitalMap.get(city)).orElse(city);
        }
        LambdaQueryWrapper<VulInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Objects.nonNull(city),VulInfo::getCity,city).orderByDesc(VulInfo::getCreateTime).last("LIMIT 10");
        return vulInfoDao.selectList(wrapper);
    }

    @Override
    public List<Map<String,DataAnalysisResp>> userAndTaskCountList(String city) {
        DataAnalysisResp data = getUserAndTaskDataCount(city);
        List<Map<String, DataAnalysisResp>> res = new ArrayList<>();
        Map<String, DataAnalysisResp> respMap = new HashMap<>();
        List<VulInfo> list = vulInfoDao.selectList();
        Map<String, Long> map = list.stream().collect(Collectors.groupingBy(VulInfo::getCity, Collectors.counting()));
        Map<String, Long> perilous = list.stream().filter(obj -> obj.getSeverity().equals(2)).collect(Collectors.groupingBy(VulInfo::getCity, Collectors.counting()));

        map.entrySet().forEach(p->{
            String key = p.getKey();
            Long perilousVulSUM = perilous.get(key);
            DataAnalysisResp analysisResp = DataAnalysisResp.builder().scanVulSUM(data.getScanVulSUM()).useUserSUM(data.getUseUserSUM()).taskSUM(data.getTaskSUM())
                    .vulSUM(p.getValue().toString()).perilousVulSUM(perilousVulSUM == null ? "0" : perilousVulSUM.toString()).build();
            respMap.put(key, analysisResp);
        });
        res.add(respMap);
        return res;
    }
}
