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

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.coderule.CodeRuleServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;
import kd.sdk.plugin.Plugin;
import nckd.jxccl.swc.constants.SwcConstant;
import nckd.jxccl.swc.hcdm.business.annualincome.AnnualIncomeService;
import nckd.jxccl.swc.utils.SwcUtils;

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

/**
 * 动态表单插件
 */
public class IncomeBatchAddnewEdit extends AbstractFormPlugin implements Plugin {


    @Override
    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);
        //年份默认当前日期的上年-01-01
    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs afterDoOperationEventArgs) {
        super.afterDoOperation(afterDoOperationEventArgs);
        String key = afterDoOperationEventArgs.getOperateKey();
        switch(key) {
            case "donothing_batchaddnew":
                doBatchAddnew();
        }
    }


    /**
     * 批量生成年收入数据：
     * 1、窗口中如果选择了核算组则按选择的核算组生成数据，没选择的话生成全部核算组的数据
     * 2、如果按照年份+核算组已有数据，则不生成并提示
     * 3、
     */
    private void doBatchAddnew() {
        String msg;
        DynamicObject dyn = this.getModel().getDataEntity();
        // 获取当前窗口选择的年份 实际值是yyyy-01-01
        Date startDate = dyn.getDate("nckd_year");
        DynamicObjectCollection cols = queryData();
        if(cols.size() == 0) {
            msg = "所有核算组都已生成，请勿重复生成！";
            this.getView().returnDataToParent(msg);
            this.getView().close();
            return;
        }
        // 根据groupId提取出来
        Map<Long, List<DynamicObject>> groupMap = cols.stream().collect(Collectors.groupingBy(obj -> obj.getLong("groupId")));

        Set<Long> keySet = groupMap.keySet();
        DynamicObjectCollection billCols = new DynamicObjectCollection();
        for(Long groupId : keySet) {
            DynamicObject bill = SwcConstant.SALANNUALINCOMEBILL_ENTITY.generateEmptyDynamicObject();
            // 2025-12-12 表头薪资核算组改为了多选
            DynamicObjectCollection mulpayRollGrp = bill.getDynamicObjectCollection("nckd_mulpayrollgrp");
            DynamicObject payRollGrp = new DynamicObject(mulpayRollGrp.getDynamicObjectType());
            payRollGrp.set("fbasedataid", groupId);
            mulpayRollGrp.add(payRollGrp);
            bill.set("nckd_mulpayrollgrp", mulpayRollGrp);

            bill.set("nckd_calyear", startDate);
            bill.set("billstatus", "A");
            DynamicObjectCollection entryCols = bill.getDynamicObjectCollection("nckd_entryentity");
            for(DynamicObject obj : groupMap.get(groupId)) {
                DynamicObject entry = entryCols.addNew();

                entry.set("nckd_payrollgrp", obj.getLong("groupId"));
                entry.set("nckd_employee", obj.getLong("employeeId"));
                entry.set("nckd_idcardno", obj.getString("idCardNo"));
                entry.set("nckd_month", obj.getInt("monthCount"));
                entry.set("nckd_totalsalary", obj.getBigDecimal("amount"));
                entry.set("nckd_pushstatus", "0");
                bill.set("org", obj.getLong("orgId"));
            }

            bill.set("billno", CodeRuleServiceHelper.getNumber(SwcConstant.SALANNUALINCOMEBILL_ENTITY.getEntityName(), bill, bill.getString("org")));
            billCols.add(bill);
        }
        Object[] a = SwcConstant.SALANNUALINCOMEBILL_ENTITY.save(billCols);
        msg = String.format("共生成%d条薪资核算组数据", a.length);
        this.getView().returnDataToParent(msg);
        this.getView().close();
    }


    /**
     * 查询数据，包含字段：
     *
     * @return
     */
    public DynamicObjectCollection queryData() {
        DynamicObject dyn = this.getModel().getDataEntity();
        // 获取当前窗口选择的年份 实际值是yyyy-01-01
        Date startDate = dyn.getDate("nckd_year");
        // 获取薪资核算组Ids
        List<Long> groupIds = getPayRollGroupIds(startDate);
        // 获取年度最后一天
        Date endDate = SwcUtils.getLastDayOfYear(startDate);

        AnnualIncomeService service = new AnnualIncomeService(groupIds, startDate, endDate);
        DynamicObjectCollection cols = service.querySalaryDetailBySql();
        return cols;
    }

    public List<Long> getPayRollGroupIds (Date startDate) {
        List<Long> groupIds = new ArrayList<Long>();
        IDataModel model = this.getModel();

        // 查出现在已经生成了多少薪资核算组的数据
        List<Long> excludeGroupIds = SwcUtils.getExcludePayRollGroupIds(startDate);

        DynamicObjectCollection payRollGrpCols = (DynamicObjectCollection)model.getValue("nckd_mulpayrollgrp");
        if(payRollGrpCols.size() == 0) {
            groupIds = SwcUtils.getAllPayRollGrpIds();
        }
        else {
            groupIds = payRollGrpCols.stream().map(obj -> obj.getDynamicObject("fbasedataid").getLong("id")).collect(Collectors.toList());
        }
        // 排除已经生成了数据的核算组
        groupIds.removeAll(excludeGroupIds);
        return groupIds;
    }


}