package nckd.jxccl.opmc.pm.helper;

import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.org.OrgUnitServiceHelper;
import kd.bos.servicehelper.user.UserServiceHelper;
import nckd.jxccl.base.common.utils.DateUtil;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.stream.Collectors;

/**
 * @ClassName: KpiImportUtils
 * @Description: 绩效导入工具类
 * @Author: PJJ
 * @Date: 2026/1/14 下午2:36
 * @Version: 1.0
 */
public class KpiImportUtils {
    /**
     * 查询去年绩效考核不合格员工
     * @return
     */
    public static List<DynamicObject> yearUnqualifiedUser() {
        //获取去年第一天
        LocalDateTime localDateTime = DateUtil.minusYears(DateUtil.now(), 1);
        localDateTime = DateUtil.beginOfYear(localDateTime);
        //去年年度绩效不合格员工
        QFilter qFilter = new QFilter("nckd_perfmanagerentry.nckd_appraisalresult.number", QCP.in, new String[]{"04", "10"});
        qFilter.and("nckd_perfmanagerentry.nckd_appraisalyear", QCP.equals, localDateTime);
        //查询考核周期获取年度绩效考核结果为 不合格 人员
        DynamicObjectCollection user = QueryServiceHelper.query("nckd_perfmanager", "nckd_person.id", qFilter.toArray());
        List<Long> userIds = user.stream().map(i -> i.getLong("nckd_person.id")).collect(Collectors.toList());
        QFilter userqFilter = new QFilter("employee", QCP.in, userIds);
        userqFilter.and("posstatus.poststatecls.number", QCP.equals, "1010_S");
        //最新任职经历
        DynamicObject[] empposorgrel = BusinessDataServiceHelper.load("hrpi_empposorgrel", "employee.empnumber", userqFilter.toArray());
        List<String> userNumber = Arrays.stream(empposorgrel).map(i -> i.getString("employee.empnumber")).collect(Collectors.toList());
        DynamicObject[] bos_ser = BusinessDataServiceHelper.load("bos_user", "id,number,name,entryentity.dpt,entryentity.ispartjob", new QFilter[]{new QFilter("number", QCP.in, userNumber)});
        return Arrays.asList(bos_ser);
    }

    public static List<DynamicObject> monthUnqualifiedUser() {
        //查询月度考核不合格员工
        QFilter qFilter = new QFilter("status", QCP.equals, "C");
        qFilter.and("enable", QCP.equals, "1");
        qFilter.and("nckd_entryentity.nckd_examine_dimension.number", QCP.equals, "JT-00011");
        qFilter.and("nckd_entryentity.nckd_result", QCP.in, new String[]{"视同不合格", "不合格"});
        //绩效导入结果
        DynamicObject[] result = BusinessDataServiceHelper.load("nckd_examinproject_result", "nckd_user,nckd_importplan", qFilter.toArray());
        Map<Long, List<Integer>> userId_month = Arrays.stream(result)
                .collect(Collectors.groupingBy(i -> i.getLong("nckd_user.id"),
                        Collectors.mapping(obj -> obj.getInt("nckd_month"), Collectors.toList())));
        ArrayList<Long> objects = new ArrayList<>();
        //过滤连续三个月考核不合格员工
        for (Long userId : userId_month.keySet()) {
            List<Integer> integers = userId_month.get(userId);
            //校验连续三月
            boolean check = check(integers);
            if (check) {
                objects.add(userId);
            }
        }
        DynamicObject[] bos_ser = BusinessDataServiceHelper.load("bos_user", "id,number,name,entryentity.dpt,entryentity.ispartjob", new QFilter[]{new QFilter("id", QCP.in, objects)});
        return Arrays.asList(bos_ser);
    }

    private static boolean check(List<Integer> months) {
        if (months == null || months.size() < 3) {
            return false;
        }

        // 1. 去重并排序
        Set<Integer> uniqueMonths = new TreeSet<>(months);
        List<Integer> sortedMonths = new ArrayList<>(uniqueMonths);

        // 2. 检查连续三个月
        for (int i = 0; i <= sortedMonths.size() - 3; i++) {
            int month1 = sortedMonths.get(i);
            int month2 = sortedMonths.get(i + 1);
            int month3 = sortedMonths.get(i + 2);

            // 检查是否连续
            if (month2 == month1 + 1 && month3 == month2 + 1) {
                return true;
            }
        }

        return false;
    }

    public static List<DynamicObject> querEmpposorgre(LocalDateTime date) {
        long orgId = RequestContext.get().getOrgId();
        List<Long> subOrgIds = OrgUnitServiceHelper.getAllSubordinateOrgs(1L, Collections.singletonList(orgId), true);
        QFilter qFilter = new QFilter("adminorg", QCP.in, subOrgIds);
        qFilter.and("isprimary", QCP.equals, true);
        qFilter.and("posstatus.number", QCP.equals, "1010_S");
        qFilter.and("startdate", QCP.less_equals, date);
        qFilter.and("enddate", QCP.large_equals, date);
        DynamicObject[] load = BusinessDataServiceHelper.load("hrpi_empposorgrel", "employee,adminorg,position", qFilter.toArray());
        return Arrays.asList(load);
    }


}
