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

import nckd.jxccl.base.common.utils.DateTimeUtils;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.dataentity.utils.ObjectUtils;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.ListSelectedRowCollection;
import kd.bos.form.CloseCallBack;
import kd.bos.form.ShowFormHelper;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.events.ClosedCallBackEvent;
import kd.bos.form.operate.FormOperate;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.list.ListFilterParameter;
import kd.bos.list.ListShowParameter;
import kd.bos.orm.query.QCP;
import kd.bos.orm.query.QFilter;
import kd.hr.hbp.business.servicehelper.HRBaseServiceHelper;
import kd.sdk.plugin.Plugin;
import nckd.jxccl.base.swc.helper.SWCHelper;
import nckd.jxccl.swc.constants.SwcConstant;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Tyx 2025-10-29
 * 单位代发单表单插件
 */
public class AgencyBillEdit extends AbstractFormPlugin implements Plugin {

    private static final String CALLBACK_CLOSE_ADD_ADJFILE = "CALLBACK_CLOSE_ADD_ADJFILE";
    private static final HRBaseServiceHelper SALARYFILE_HELPER = new HRBaseServiceHelper("hsas_salaryfile");

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        this.addItemClickListeners("nckd_advcontoolbarap");
    }

    @Override
    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);
    }

    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
    }

    @Override
    public void beforeBindData(EventObject e) {
        super.beforeBindData(e);
        if("calPerson".equals(this.getView().getFormShowParameter().getCustomParam("source"))) {
            dealDataByCalPerson();
        }
    }

    /**
     * 从薪资明细-转代发按钮跳转过来之后的处理
     */
    public void dealDataByCalPerson() {
        IDataModel model = this.getModel();
        DynamicObject billDyn = model.getDataEntity(true);
        DynamicObjectCollection entryCols = billDyn.getDynamicObjectCollection("nckd_entryentity");
        Map<String, Object> customParams = this.getView().getFormShowParameter().getCustomParams();
        // 组织
        model.setValue("org", customParams.get("org"));
        // 归属年月
        String startDateStr = customParams.get("startDate").toString().substring(0, 10);
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        LocalDate localDate = LocalDate.parse(startDateStr, formatter);
        Date date = Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
        // 赋值薪资核算组
        model.setValue("nckd_payrollgroup",customParams.get("payrollgroup"));
        List calPersonIds = (List) customParams.get("calPersonIds");
        // 获取核算人员相关信息
        QFilter filter = new QFilter("id", "in", calPersonIds);
        String selectFields = "id, employee.id, empposorgrelsndet.adminorg.id";
        DynamicObject[] calPersonDyns = SwcConstant.CALPERSON_HELPER.load(selectFields, new QFilter[]{filter});
        Map<Long, DynamicObject> calPersonMap = Arrays.stream(calPersonDyns).collect(Collectors.toMap((dyx) -> {
            return dyx.getLong("id");
        }, (dyx) -> {
            return dyx;
        }, (key1, key2) -> {
            return key2;
        }));


        // 获取核算列表信息
        filter = new QFilter("calpersonid", "in", calPersonIds);
        filter.and("hsas_caltableentry.salaryitem.number", QCP.equals, "JT_283");
        selectFields = "calpersonid,hsas_caltableentry.calamountvalue";
        DynamicObjectCollection calTableDyns = SwcConstant.CALTABLE_ENTITY.queryOriginalCollection(selectFields, new QFilter[]{filter});
        Map<Long, DynamicObject> calTableMap = calTableDyns.stream().collect(Collectors.toMap((dyx) -> {
            return dyx.getLong("calpersonid");
        }, (dyx) -> {
            return dyx;
        }, (key1, key2) -> {
            return key2;
        }));

        // 获取到人员主任职
        List<Long> employeeId = Arrays.stream(calPersonDyns).map(dyx -> dyx.getLong("employee.id")).collect(Collectors.toList());
        DynamicObject[] empposorgrelDyns = SWCHelper.queryEmpPosOrgRelDyns(employeeId);
        Map<Long, DynamicObject> empposorgrelMap = Arrays.stream(empposorgrelDyns).collect(Collectors.toMap((dyx) -> {
            return dyx.getLong("employee.id");
        }, (dyx) -> {
            return dyx;
        }, (key1, key2) -> {
            return key2;
        }));

        // 获取到人员证件信息
        DynamicObject[] percreDyns = SWCHelper.queryPercreDyns(employeeId);
        Map<Long, DynamicObject> percreMap = Arrays.stream(percreDyns).collect(Collectors.toMap((dyx) -> {
            return dyx.getLong("employee.id");
        }, (dyx) -> {
            return dyx;
        }, (key1, key2) -> {
            return key2;
        }));

        for (Object calPerson : calPersonIds) {
            DynamicObject row = entryCols.addNew();
            Long calPersonId = Long.valueOf(calPerson.toString());
            row.set("nckd_employee", calPersonMap.get(calPersonId).getDynamicObject("employee"));
            row.set("nckd_eorg", empposorgrelMap.get(row.getLong("nckd_employee.id")).getDynamicObject("adminorg.belongcompany"));
            row.set("nckd_adminorg", calPersonMap.get(calPersonId).getDynamicObject("empposorgrelsndet.adminorg"));
            //row.set("nckd_payrollgrp", model.getValue("nckd_payrollgroup"));
            row.set("nckd_belongdate", date);
            row.set("nckd_idcardno", percreMap.get(row.getLong("nckd_employee.id")).getString("number"));
            if(calTableMap.keySet().contains(calPersonId)) {
                row.set("nckd_amount", calTableMap.get(calPersonId).getBigDecimal("hsas_caltableentry.calamountvalue"));
            }
            else {
                row.set("nckd_amount", BigDecimal.ZERO);
            }
        }
    }

    /**
     * 根据核算名单ID获取相关信息
     * @param calPersonIds
     * @return
     */
    public DynamicObjectCollection getCalTableByCalPersonId(List calPersonIds) {
        QFilter filter = new QFilter("calpersonid", "in", calPersonIds);
        String selectFields = "employee.id, empposorgrelsndet.adminorg.id";
        return SwcConstant.CALPERSON_HELPER.queryOriginalCollection(selectFields, new QFilter[]{filter});
    }

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs args) {
        super.beforeDoOperation(args);
        FormOperate formOperate = (FormOperate)args.getSource();
        String key = formOperate.getOperateKey();
        switch (key) {
            case "add_adjfile":
                beforeAddAdjFileVerify(args);
                break;
        }
    }

    /**
     * 添加代发人员前校验
     * 必须选择完薪资核算组和组织
     */
    private void beforeAddAdjFileVerify(BeforeDoOperationEventArgs args) {
        DynamicObject dyn = this.getModel().getDataEntity();
        DynamicObject org = dyn.getDynamicObject("org");
        DynamicObject parRollGroup = dyn.getDynamicObject("nckd_payrollgroup");

        if(ObjectUtils.isEmpty(org)) {
            args.setCancel(true);
            this.getView().showTipNotification("请先选择组织！");
        }

        if(ObjectUtils.isEmpty(parRollGroup)) {
            args.setCancel(true);
            this.getView().showTipNotification("请先选择薪资核算组！");
        }

    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs afterDoOperationEventArgs) {
        super.afterDoOperation(afterDoOperationEventArgs);
        FormOperate source = (FormOperate)afterDoOperationEventArgs.getSource();
        switch (source.getOperateKey()) {
            case "add_adjfile":
                this.showAdjFileF7(afterDoOperationEventArgs);
        }
    }

    private void showAdjFileF7(AfterDoOperationEventArgs args) {
        ListShowParameter formShowParameter = ShowFormHelper.createShowListForm("hsas_salaryfilef7", true);
        ListFilterParameter listFilterParameter = formShowParameter.getListFilterParameter();
        formShowParameter.setMultiSelect(true);
        List<QFilter> qFilters = listFilterParameter.getQFilters();
        qFilters.add(new QFilter("iscurrentversion", QCP.equals, "1"));

        Date effectiveDate = new Date();
        long orgId = this.getModel().getDataEntity().getLong("org.id");
        long payRollGrpId = this.getModel().getDataEntity().getLong("nckd_payrollgroup.id");
        qFilters.add(new QFilter("org.id", QCP.equals, orgId));
        qFilters.add(new QFilter("payrollgroup.id", QCP.equals, payRollGrpId));
        if (effectiveDate != null) {
            formShowParameter.setCustomParam("effectiveDate", DateTimeUtils.format(effectiveDate, "yyyy-MM-dd"));
        }

        formShowParameter.setListFilterParameter(listFilterParameter);
        formShowParameter.setCloseCallBack(new CloseCallBack(this, "CALLBACK_CLOSE_ADD_ADJFILE"));
        formShowParameter.setCaption(ResManager.loadKDString("请添加代发人员", "ApplyBillEdit_1", "swc-hcdm-formplugin", new Object[0]));
//        Long billId = (Long)this.getModel().getDataEntity().getPkValue();
//        formShowParameter.setCustomParam("billid", String.valueOf(billId));
//        formShowParameter.setCustomParam("addPersonFlag", Boolean.TRUE.toString());
//        formShowParameter.setCustomParam("isHistoryPage", Boolean.TRUE.toString());
//        formShowParameter.setCustomParam("hisPage", "versionListPage");
//        formShowParameter.setCustomParam("option", "hisversioninfo");
        this.getView().showForm(formShowParameter);
    }

    @Override
    public void closedCallBack(ClosedCallBackEvent closedCallBackEvent) {
        super.closedCallBack(closedCallBackEvent);
        String actionId = closedCallBackEvent.getActionId();
        Object returnData = closedCallBackEvent.getReturnData();
        if (CALLBACK_CLOSE_ADD_ADJFILE.equals(actionId) && returnData != null) {
            this.onCloseCallbackAddAdjFile(closedCallBackEvent);
        }
    }

    private void onCloseCallbackAddAdjFile(ClosedCallBackEvent args) {
        IDataModel model = this.getModel();
        ListSelectedRowCollection selectedRows = (ListSelectedRowCollection) args.getReturnData();
        Object[] primaryKeyObjs = selectedRows.getPrimaryKeyValues();
        List<Long> ids = Arrays.stream(primaryKeyObjs).map(obj -> (Long)obj).collect(Collectors.toList());
        QFilter filter = new QFilter("id", QCP.in, ids);
        String selectFields = "employee.id, employee.name, employee.empnumber, empposorgrel.adminorg.id";
        DynamicObject[] adjFiles = SALARYFILE_HELPER.load(selectFields, new QFilter[]{filter});

        // employeeId
        List<Long> employeeIds = Arrays.stream(adjFiles).map(obj -> obj.getLong("employee.id")).collect(Collectors.toList());
        DynamicObject[] percreDyns = SWCHelper.queryPercreDyns(employeeIds);
        Map<Long, DynamicObject> percreMap = Arrays.stream(percreDyns).collect(Collectors.toMap((dyx) -> {
            return dyx.getLong("employee.id");
        }, (dyx) -> {
            return dyx;
        }, (key1, key2) -> {
            return key2;
        }));


        DynamicObjectCollection entryCols = model.getDataEntity(true).getDynamicObjectCollection("nckd_entryentity");
        model.beginInit();
        for (DynamicObject adjFile : adjFiles) {
            DynamicObject entry = entryCols.addNew();
            entry.set("nckd_employee", adjFile.getDynamicObject("employee"));
            entry.set("nckd_adminorg", adjFile.getDynamicObject("empposorgrel.adminorg"));

            Long employeeId = adjFile.getLong("employee.id");
            if(percreMap.containsKey(employeeId)) {
                entry.set("nckd_idcardno", percreMap.get(employeeId).getString("number"));
            }

        }
        model.endInit();
        this.getView().updateView("nckd_entryentity");
    }
}