package nckd.jxccl.swc.hcdm.opplugin.annualincome;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.PreparePropertysEventArgs;
import kd.bos.entity.plugin.args.AfterOperationArgs;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.sdk.plugin.Plugin;
import nckd.jxccl.swc.hcdm.business.annualincome.AnnualIncomeService;
import nckd.jxccl.swc.utils.SwcUtils;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Tyx 2025-12-12
 * 本单位发薪收入确认更新插件
 */
public class SalAnnualIncomeUpdatePlugin extends AbstractOperationServicePlugIn implements Plugin {

    @Override
    public void onPreparePropertys(PreparePropertysEventArgs e) {
        super.onPreparePropertys(e);
        e.getFieldKeys().addAll(this.billEntityType.getAllFields().keySet());
    }

    @Override
    public void afterExecuteOperationTransaction(AfterOperationArgs e) {
        super.afterExecuteOperationTransaction(e);
        DynamicObject[] bills = e.getDataEntities();
        for(DynamicObject bill : bills) {
            // 获取薪资核算组
            DynamicObjectCollection groupDyns = bill.getDynamicObjectCollection("nckd_mulpayrollgrp");
            List<Long> groupIds = groupDyns.stream().map(group -> group.getLong("fbasedataid.id")).collect(Collectors.toList());

            Date startDate = bill.getDate("nckd_calyear");
            // 获取年度最后一天
            Date endDate = SwcUtils.getLastDayOfYear(startDate);
            AnnualIncomeService service = new AnnualIncomeService(groupIds, startDate, endDate);
            DynamicObjectCollection resultCols = service.querySalaryDetailBySql();
            doDealData(bill, resultCols);
        }
        SaveServiceHelper.save(bills);
    }

    private void doDealData(DynamicObject bill, DynamicObjectCollection resultCols) {
        // 根据groupId + '_' +  emloyeeId提取
        Map<String, DynamicObject> resultMap = resultCols.stream()
                .collect(Collectors.toMap(
                        obj -> obj.getLong("groupId") + "_" + obj.getLong("employeeId"), // 构造唯一键
                        obj -> obj  // 保留原始对象
                ));
        Set<String> allKeySet = resultMap.keySet();
        DynamicObjectCollection entryCols = bill.getDynamicObjectCollection("nckd_entryentity");
        Map<String, DynamicObject> currentMap = entryCols.stream()
                .collect(Collectors.toMap(
                        obj -> obj.getLong("nckd_payrollgrp.id") + "_" + obj.getLong("nckd_employee.id"), // 构造唯一键
                        obj -> obj  // 保留原始对象
                ));
        Set<String> currentKeySet = currentMap.keySet();


        Set<String> updateKeySet = allKeySet.stream()
                .filter(currentKeySet::contains)
                .collect(Collectors.toSet());
        Set<String> addnewSet = allKeySet.stream()
                .filter(key -> !currentKeySet.contains(key))
                .collect(Collectors.toSet());

        for (DynamicObject entry : entryCols) {
            // 如果当前分录推送状态不为【社保未拉取】则继续
            if(!entry.getString("nckd_pushstatus").equals("0")) {
                continue;
            }
            // 当前分录的emplyeeId + groupId
            Long groupId = entry.getLong("nckd_payrollgrp.id");
            Long employeeId = entry.getLong("nckd_employee.id");
            String key = groupId + "_" + employeeId;

            // 根据唯一键获取，如果不存在则新增一行记录
            if(updateKeySet.contains(key)) {
                doUpdateEntry(entry,resultMap.get(key));
            }
        }

        //处理新增分录
        for (String key : addnewSet) {
            doAddnewEntry(entryCols.addNew(),resultMap.get(key));
        }

    }

    /**
     * 更新分录数据
     * 更新字段：证件号，月份，年度工资收入
     * @param entry
     * @param result
     */
    private void doUpdateEntry(DynamicObject entry, DynamicObject result) {
        entry.set("nckd_idcardno", result.getString("idCardNo"));
        entry.set("nckd_month", result.getInt("monthCount"));
        entry.set("nckd_totalsalary", result.getBigDecimal("amount"));
    }

    private void doAddnewEntry(DynamicObject entry, DynamicObject result) {
        entry.set("nckd_payrollgrp", result.getLong("groupId"));
        entry.set("nckd_employee", result.getLong("employeeId"));
        entry.set("nckd_idcardno", result.getString("idCardNo"));
        entry.set("nckd_month", result.getInt("monthCount"));
        entry.set("nckd_totalsalary", result.getBigDecimal("amount"));
        entry.set("nckd_pushstatus", "0");

    }
}