package nckd.jxccl.swc.onlineperf.common;

import com.alibaba.fastjson.JSONObject;
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.QueryServiceHelper;
import kd.sdk.swc.hscs.common.api.ICustomFetchDataService;
import nckd.jxccl.base.common.constant.FormConstant;
import nckd.jxccl.base.common.utils.DateUtil;
import nckd.jxccl.base.common.utils.QueryFieldBuilder;
import nckd.jxccl.swc.constants.SwcConstant;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 在线即时考核薪酬函数
 *
 * @author W.Y.C
 * @version 1.0
 * @date 2025/12/17 14:37
 */
public class OnlinePerfFetchDataService implements ICustomFetchDataService {

    @Override
    public Map<Long, Map<String, Object>> fetchDataCalPerson(List<Long> calPersonIdList, Map<Long, Map<String, Object>> paramsMap, Map<String, Object> extParamMap) {
        QueryFieldBuilder queryFieldBuilder = QueryFieldBuilder.create()
                .add(FormConstant.ID_KEY)
                .add("empnumber")
                .add("name")
                .add("org")
                .addGroup(new String[]{"caltask"}, "calcount", "payrolldate")
                .addGroup(new String[]{"caltask", "calrule"}, FormConstant.ID_KEY)
                .addGroup(new String[]{FormConstant.EMPLOYEE_KEY}, FormConstant.ID_KEY);
        QFilter qFilter = new QFilter("id", "in", calPersonIdList);
        DynamicObject[] load = SwcConstant.CALPERSON_HELPER.load(queryFieldBuilder.buildSelect(), new QFilter[]{qFilter});

        Map<Long, Map<String, Object>> resultMap = new HashMap<Long, Map<String, Object>>();
        if(load != null && load.length > 0) {
            Map<Long, Long> employeeToCalPersonMap = Arrays.stream(load)
                    .collect(Collectors.toMap(
                            obj -> obj.getLong(String.join(".", FormConstant.EMPLOYEE_KEY, FormConstant.ID_KEY)),
                            obj -> obj.getLong(FormConstant.ID_KEY)
                    ));
            long orgId = load[0].getLong(String.join(".", FormConstant.ORG_KEY, FormConstant.ID_KEY));
            DynamicObject calTask = load[0].getDynamicObject("caltask");
            Date date = calTask.getDate("payrolldate");
            int year = DateUtil.getYear(date);
            int month = DateUtil.getMonthValue(date);
            long calRuleId = calTask.getLong(String.join(".", "calrule", FormConstant.ID_KEY));
            int calCount = calTask.getInt("calcount");
            //在线即时考核
            QueryFieldBuilder onlinePerfQueryFieldBuilder = QueryFieldBuilder.create()
                    .add(FormConstant.ID_KEY)
                    .addIdNumberName(OnlinePerfConstant.NCKD_CALRULE)
                    .addIdNumberName(OnlinePerfConstant.NCKD_ADMINORGUNIT)
                    .add(OnlinePerfConstant.NCKD_PERIODYEAR)
                    .add(OnlinePerfConstant.NCKD_PERIODMONTH)
                    .addIdNumberName(OnlinePerfConstant.NCKD_ENTRYENTITY, FormConstant.NCKD_PERSON)
                    .addIdNumberName(OnlinePerfConstant.NCKD_ENTRYENTITY, OnlinePerfConstant.NCKD_SALARYITEM)
                    .add(OnlinePerfConstant.NCKD_ENTRYENTITY, OnlinePerfConstant.NCKD_NMONEY);
            QFilter onlinePerfFilter = new QFilter(OnlinePerfConstant.NCKD_PERIODYEAR, QCP.equals, year)
                    .and(OnlinePerfConstant.NCKD_PERIODMONTH, QCP.equals, month)
                    .and(String.join(".", OnlinePerfConstant.NCKD_ADMINORGUNIT, FormConstant.ID_KEY),QCP.equals, orgId)
                    .and(String.join(".", OnlinePerfConstant.NCKD_CALRULE, FormConstant.ID_KEY),QCP.equals, calRuleId)
                    .and(String.join(".", OnlinePerfConstant.NCKD_ENTRYENTITY, OnlinePerfConstant.NCKD_PERSON),QCP.in, employeeToCalPersonMap.keySet());
            DynamicObjectCollection onlinePerfColl = QueryServiceHelper.query(OnlinePerfConstant.ONLINEPERF_ENTITYID, onlinePerfQueryFieldBuilder.buildSelect(), new QFilter[]{onlinePerfFilter});
            Map<Long, List<DynamicObject>> onlinePerfMap = onlinePerfColl.stream()
                    .collect(Collectors.groupingBy(dynamicObject ->
                            dynamicObject.getLong(String.join(".", OnlinePerfConstant.NCKD_ENTRYENTITY, OnlinePerfConstant.NCKD_PERSON, FormConstant.ID_KEY))
                    ));
            for (Map.Entry<Long, List<DynamicObject>> entrySet : onlinePerfMap.entrySet()) {
                Long key = entrySet.getKey();
                List<DynamicObject> value = entrySet.getValue();
                JSONObject json = new JSONObject();
                for (DynamicObject onlinePerf : value) {
                    if(onlinePerf.getLong(String.join(".", OnlinePerfConstant.NCKD_ENTRYENTITY, OnlinePerfConstant.NCKD_SALARYITEM, FormConstant.ID_KEY))>0){
                        String salaryItemNumber = onlinePerf.getString(String.join(".", OnlinePerfConstant.NCKD_ENTRYENTITY, OnlinePerfConstant.NCKD_SALARYITEM, FormConstant.NUMBER_KEY));
                        BigDecimal money = onlinePerf.getBigDecimal(String.join(".", OnlinePerfConstant.NCKD_ENTRYENTITY, OnlinePerfConstant.NCKD_NMONEY));
                        if(money.compareTo(BigDecimal.ZERO) > 0) {
                            if(calCount == 1) {
                                json.put(salaryItemNumber, money);
                            }else{
                                json.put(salaryItemNumber, BigDecimal.ZERO);
                            }
                        }
                    }
                }
                Map<String, Object> result = new HashMap<String, Object>();
                result.put("resultJson",json.toString());
                resultMap.put(employeeToCalPersonMap.get(key), result);
            }
        }
        return resultMap;
    }

    @Override
    public Map<String, Object> fetchDataCalTask(Long calTaskId, Map<String, Object> paramsMap, Map<String, Object> extParamMap) {
        return null;
    }
}