package com.engine.salary.report.entity.bo;

import com.engine.salary.util.SalaryDateUtil;
import com.google.common.collect.Sets;
import org.apache.commons.collections4.CollectionUtils;

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

/**
 * 薪酬统计员工明细
 */
public class SalaryStatisticsEmployeeBO {

    /**
     * 年月参数处理，注意：薪资所属月居然是用字符串存储的，无法通过sql between处理
     *
     * @param year
     * @param salaryMonth
     * @return
     */
    public static Set<String> getSalaryMonths(Integer year, List<Date> salaryMonth) {
        Set<String> salaryMonths = Sets.newHashSet();
        // 年份参数
        if (Objects.nonNull(year)) {
            List<String> months = Arrays.asList("01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12");
            for (int i = 0; i < months.size(); i++) {
                salaryMonths.add(year + "-" + months.get(i));
            }
        }
        // 薪资所属月参数，如果已经有年的就取交集
        if (CollectionUtils.isNotEmpty(salaryMonth)) {
            salaryMonth = (salaryMonth.size() > 2 ? salaryMonth.subList(0, 1) : salaryMonth);
            if (salaryMonth.size() == 2) {
                if (salaryMonth.get(0).after(salaryMonth.get(1))) {
                    salaryMonths.clear();
                    salaryMonths.add("2000-01");
                } else {
                    Date startYearMonth = salaryMonth.get(0);
                    Date endYearMonth = salaryMonth.get(1);
                    Set<String> yearMonths = Sets.newHashSet();
                    while (!startYearMonth.after(endYearMonth)) {
                        yearMonths.add(SalaryDateUtil.getFormatYearMonth(startYearMonth));
                        startYearMonth = SalaryDateUtil.plusMonths(startYearMonth, 1);
                    }
                    if (CollectionUtils.isNotEmpty(salaryMonths)) {
                        Set<String> finalSalaryMonths = salaryMonths;
                        salaryMonths = yearMonths.stream().filter(finalSalaryMonths::contains).collect(Collectors.toSet());
                        salaryMonths = CollectionUtils.isEmpty(salaryMonths) ? Sets.newHashSet("2000-01") : salaryMonths;
                    } else {
                        salaryMonths = yearMonths;
                    }
                }
            } else {
                String singMonth = SalaryDateUtil.getFormatYearMonth(salaryMonth.get(0));
                salaryMonths.add(CollectionUtils.isNotEmpty(salaryMonths) ? (salaryMonths.contains(singMonth) ? singMonth : "2000-01") : singMonth);
            }
        }

        return salaryMonths;
    }
}
