package cn.stylefeng.workflow.instance.modular.stat.business.factory;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.stylefeng.workflow.instance.modular.stat.business.pojo.ResultXyData;
import cn.stylefeng.workflow.instance.modular.stat.business.pojo.XyData;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

public class CombineResultFactory {

    public static List<ResultXyData> combineResult(Date beginDate, Date endDate, List<XyData> latestData, List<XyData> beforeData, int days) {

        changeBeforeData(beforeData, days);

        List<DateTime> dateTimes = DateUtil.rangeToList(beginDate, endDate, DateField.DAY_OF_YEAR);

        List<String> dateStrList = dateTimes.stream().map(DateUtil::formatDate).collect(Collectors.toList());

        List<ResultXyData> resultXyData = new ArrayList<>();

        for (String dateStr : dateStrList) {
            ResultXyData resultXyDataItem = new ResultXyData();

            resultXyDataItem.setLatestX(dateStr);

            for (XyData latestDatum : latestData) {
                if (latestDatum.getX().equals(dateStr)) {
                    resultXyDataItem.setLatestY(latestDatum.getY());
                    break;
                }
            }
            if (resultXyDataItem.getLatestY() == null) {
                resultXyDataItem.setLatestY(new BigDecimal("0"));
            }

            for (XyData beforeDatum : beforeData) {
                if (beforeDatum.getX().equals(dateStr)) {
                    resultXyDataItem.setBeforeY(beforeDatum.getY());
                    break;
                }
            }
            if (resultXyDataItem.getBeforeY() == null) {
                resultXyDataItem.setBeforeY(new BigDecimal("0"));
            }

            resultXyData.add(resultXyDataItem);
        }

        return resultXyData;
    }

    private static void changeBeforeData(List<XyData> beforeData, int days) {

        for (XyData beforeDatum : beforeData) {
            String x = beforeDatum.getX();
            DateTime xDate = DateUtil.parse(x);
            DateTime offsetDate = xDate.offset(DateField.DAY_OF_YEAR, days);
            beforeDatum.setX(DateUtil.formatDate(offsetDate));
        }
    }

}
