package nckd.jxccl.sit.hcsi.formplugin.web.coordination;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.serialization.SerializationUtils;
import kd.bos.db.DB;
import kd.bos.entity.EntityMetadataCache;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.form.MessageBoxOptions;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.field.FieldEdit;
import kd.bos.form.operate.AbstractOperate;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.org.utils.DynamicObjectUtils;
import kd.bos.orm.query.QFilter;
import kd.hr.hbp.business.servicehelper.HRBaseServiceHelper;
import kd.hr.hbp.common.util.HRStringUtils;
import kd.sdk.plugin.Plugin;

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

/**
 * Tyx 2025-10-27
 * 变动核定单表单插件扩展【nckd_hpdi_empcoordbat_ext】
 */
public class SinSurEmpChgCoordBatchEditPluginEx extends AbstractFormPlugin implements Plugin {

    private static final HRBaseServiceHelper COORDBILL_HELPER = new HRBaseServiceHelper("hpdi_empcoordverifbill3");
    private static final List<String> defaultQueryFields = (List) Stream.of("id", "employeev", "assignment", "coordruleparam").collect(Collectors.toList());
    /**
     * 在标品加载完数据之后，再获取一下核定单分录的数据展示出来
     * @param e
     */
    @Override
    public void afterBindData(EventObject e) {
        super.afterBindData(e);
        List<String> queryFields = this.getQueryFields();
        HRBaseServiceHelper helper = new HRBaseServiceHelper(this.getEntityNumber());
        DynamicObject[] billCols = helper.load(String.join(",", queryFields), new QFilter[]{new QFilter("id", "in", this.getSelectIds())});
        showEntryData(billCols);
    }

    private void showEntryData(DynamicObject[] billCols) {
        Set<String> entryFields = this.getEntryFields();
        // 根据ID提取出来
        Map<Long, DynamicObject> billMap = (Map) Arrays.stream(billCols).collect(Collectors.toMap((dyx) -> {
            return dyx.getLong("id");
        }, (dyx) -> {
            return dyx;
        }, (key1, key2) -> {
            return key2;
        }));
        DynamicObjectCollection entryCols = this.getModel().getEntryEntity("entryentity");
        for(DynamicObject entry : entryCols) {
            Long billId = entry.getLong("id");
            DynamicObject bill = billMap.get(billId);
            DynamicObjectCollection billEntryCols = bill.getDynamicObjectCollection("nckd_entryentity");
            DynamicObjectCollection subEntryCols = entry.getDynamicObjectCollection("nckd_subentryentity");
            subEntryCols.clear();
            for(DynamicObject billEntry : billEntryCols) {
                DynamicObject subEntry = subEntryCols.addNew();
                for(String field : entryFields) {
                    subEntry.set(field, billEntry.get(field));
                }
            }
        }
        this.getView().updateView("nckd_subentryentity");
    }




    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs args) {
        super.beforeDoOperation(args);
        IDataModel model = this.getModel();
        AbstractOperate op = (AbstractOperate)args.getSource();
        String operateKey = op.getOperateKey();
        // 批量设置前校验，查询当前选中的单据体的子单据体是否有数据
        if(HRStringUtils.equals(operateKey, "batchsetting")){
            int row = model.getEntryCurrentRowIndex("entryentity");
            model.setEntryCurrentRowIndex("entryentity", row);
            int rowCount = model.getEntryRowCount("nckd_subentryentity");
            if(rowCount == 0) {
                args.setCancel(true);
                this.getView().showTipNotification("请先维护险种基数！");
            }
        }

    }

    @Override
    public void afterDoOperation(AfterDoOperationEventArgs afterDoOperationEventArgs) {
        super.afterDoOperation(afterDoOperationEventArgs);
        AbstractOperate op = (AbstractOperate)afterDoOperationEventArgs.getSource();
        String operateKey = op.getOperateKey();
        if ((HRStringUtils.equals(operateKey, "save") || HRStringUtils.equals(operateKey, "confirmeffect"))) {
            doSaveSubEntry();
        }
        else if(HRStringUtils.equals(operateKey, "batchsetting")){
            doBatchSetting();
        }
    }

    /**
     * 批量设置其余子分录的险种信息
     */
    public void doBatchSetting() {
        IDataModel model = this.getModel();
        DynamicObject bill = model.getDataEntity(true);
        DynamicObjectCollection entryCols = bill.getDynamicObjectCollection("entryentity");
        // 当前选中行
        int row = model.getEntryCurrentRowIndex("entryentity");
        // 当前选中行的子单据体数据
        DynamicObjectCollection subCols = entryCols.get(row).getDynamicObjectCollection("nckd_subentryentity");

        for(int i = 0; i < entryCols.size(); i++) {
            if(i == row)
                continue;
            // 获取本次要执行覆盖的子单据体
            DynamicObjectCollection otherSubCols = entryCols.get(i).getDynamicObjectCollection("nckd_subentryentity");
            // 清除数据
            otherSubCols.clear();
            // 从subCols copy 过来
            for(DynamicObject subEntry : subCols) {
                DynamicObject otherSubEntry = otherSubCols.addNew();
                DynamicObjectUtils.copy(subEntry, otherSubEntry);
            }
        }
        this.getView().updateView("nckd_subentryentity");
    }

    public void checkSubEntryData() {
        IDataModel model = this.getModel();
        DynamicObject dyn = model.getDataEntity(true);
        DynamicObjectCollection entryCols = dyn.getDynamicObjectCollection("entryentity");
    }

    /**
     * 执行保存，把当前页面的子单据体保存到核定单上；
     */
    public void doSaveSubEntry () {
        DynamicObject bill = this.getModel().getDataEntity(true);
        DynamicObjectCollection entryCols = bill.getDynamicObjectCollection("entryentity");
        DynamicObjectCollection saveCols = new DynamicObjectCollection();
        Set<String> subEntryFields = getEntryFields();
        for (DynamicObject entry : entryCols) {
            // 获取到核定单ID
            Long coordBillId = entry.getLong("id");
            // 获取到核定单Dyn
            DynamicObject coordBill = COORDBILL_HELPER.loadOne(coordBillId);
            // 获取当前页面子单据体的信息
            DynamicObjectCollection subEntryCols = entry.getDynamicObjectCollection("nckd_subentryentity");
            // 保存核定单的分录
            DynamicObjectCollection coordBillEntryCols = coordBill.getDynamicObjectCollection("nckd_entryentity");
            // 清空核定单的分录
            coordBillEntryCols.clear();
            // 根据当前页面子单据体信息->核定单分录数据
            for (DynamicObject subEntry : subEntryCols) {
                DynamicObject billEntry = coordBillEntryCols.addNew();
                for(String field : subEntryFields) {
                    billEntry.set(field, subEntry.get(field));
                }
            }
            saveCols.add(coordBill);
        }
        if(saveCols.size() > 0) {
            COORDBILL_HELPER.save(saveCols);
        }
    }

    /**
     * 获取子单据体字段
     * @return
     */
    public Set<String> getEntryFields() {
        Set<String> subEntryFields = EntityMetadataCache.getDataEntityType("hpdi_empcoordbatchedit3").getAllEntities().get("nckd_subentryentity").getFields().keySet();
        return subEntryFields;
    }

    /**
     * 获取核定单ID
     * @return
     */
    protected List<Long> getSelectIds() {
        String selectIdStr = (String)this.getView().getFormShowParameter().getCustomParam("selectIds");
        return (List<Long>) SerializationUtils.fromJsonStringToList(selectIdStr, Long.class);
    }

    /**
     * 获取实体标识
     * @return
     */
    protected String getEntityNumber() {
        return (String)this.getView().getFormShowParameter().getCustomParam("entityNumber");
    }

    /**
     * 构建查询字段
     * @return
     */
    protected List<String> getQueryFields() {
        EntryGrid entryGrid = (EntryGrid)this.getView().getControl("entryentity");
        List<FieldEdit> entryFields = entryGrid.getFieldEdits();
        Set<String> queryFields = (Set)entryFields.stream().map(FieldEdit::getFieldKey).collect(Collectors.toSet());
        queryFields.remove("adminorg");
        queryFields.remove("position");
        queryFields.addAll(defaultQueryFields);
        Set<String> fields = this.getEntryFields();
        queryFields.addAll(fields.stream().map(field -> "nckd_entryentity." + field).collect(Collectors.toList()));
        return new ArrayList(queryFields);
    }

}