package com.sunxung.factoring.service.irrCalculate.impl;

import com.sunxung.factoring.component.util.DateUtil;
import com.sunxung.factoring.component.util.IrrUtil;
import com.sunxung.factoring.component.util.PercentageUtil;
import com.sunxung.factoring.entity.irrCalculate.vo.IRRCalculateVo;
import com.sunxung.factoring.entity.irrCalculate.vo.IRRCalculateVoList;
import com.sunxung.factoring.service.irrCalculate.IRRCalculateService;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class IRRCalculateServiceImpl implements IRRCalculateService {
    @Override
    public String irrCalculate(IRRCalculateVoList voList) {
        String irrStr = "0%";
        if (voList!=null&&null != voList.getList() && voList.getList().size() > 0) {
            List<BigDecimal> netCash = new ArrayList<BigDecimal>();
            Map<Date, BigDecimal> map = new HashMap<>();
            // 根据日期分组：
            Map<Date, List<IRRCalculateVo>> map1 = voList.getList().stream()
                    .filter((t) -> t.getDate() != null)
                    .collect(Collectors.groupingBy(IRRCalculateVo::getDate));
            // 计算同一日期下的现金流量总和
            map1.forEach((x, y) -> {
                BigDecimal total = new BigDecimal(0);
                for (IRRCalculateVo vo : y) {
                    if (null != vo.getFinalCashFlow()) {
                        total = total.add(vo.getFinalCashFlow());
                    }
                }
                map.put(x, total);
            });
            // 对map进行排序
            Map<Date, BigDecimal> result = map.entrySet().stream().sorted(Map.Entry.comparingByKey())
                    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue,
                            LinkedHashMap::new));
            // 获取最大日期和最小的日期
            Date firstDate = null;
            Date endDate = null;
            for (Map.Entry<Date, BigDecimal> entry : result.entrySet()) {
                if (null != entry.getKey()) {
                    firstDate = entry.getKey();
                    break;
                }
            }
            for (Map.Entry<Date, BigDecimal> entry : result.entrySet()) {
                if (null != entry.getKey()) {
                    endDate = entry.getKey();
                }
            }
            // 把两个日期之间的所有日期的金额设置为0，放到Map中
            Map<Date, BigDecimal> allMap = new LinkedHashMap<>();
            if (null != firstDate && null != endDate) {
                List<Date> dates = DateUtil.getBetweenDates(DateUtil.formateYMD(firstDate),
                        DateUtil.formateYMD(endDate));
                for (Date date : dates) {
                    allMap.put(date, new BigDecimal("0"));
                }
            }
            for (Map.Entry<Date, BigDecimal> entry : allMap.entrySet()) {
                BigDecimal amount = result.get(entry.getKey());
                if (amount == null) {
                    amount = entry.getValue();
                }
                netCash.add(amount);
            }
            double irr = new IrrUtil(netCash, 1).calculateIrr();
            if (Double.isNaN(irr)) {
                // throw new ValidatorException(CodeUtil.FAIL, "现金流量不符合IRR的计算公式");
            }
            if (!Double.isNaN(irr) && !Double.isInfinite(irr)) {
                irr = new BigDecimal(irr).setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();// 保留四位小数
                irrStr = PercentageUtil.convertPercentage(irr);
                if (irrStr.length() >= 6) {
                    char a = irrStr.charAt(5);
                    if (a == '.') {
                        irrStr = irrStr.substring(0, 8) + "%";
                    }
                }
            }
        }
        return irrStr;
    }
}
