package nckd.jxccl.swc.hsas.formplugin.web.outdata.basedata;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.dataentity.utils.StringUtils;
import kd.bos.entity.datamodel.AbstractFormDataModel;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.TableValueSetter;
import kd.bos.entity.datamodel.events.PropertyChangedArgs;
import kd.bos.form.CloseCallBack;
import kd.bos.form.FormShowParameter;
import kd.bos.form.MessageBoxResult;
import kd.bos.form.ShowType;
import kd.bos.form.control.EntryGrid;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.events.ClosedCallBackEvent;
import kd.bos.form.events.MessageBoxClosedEvent;
import kd.bos.form.operate.FormOperate;
import kd.bos.form.plugin.AbstractFormPlugin;
import kd.bos.orm.util.CollectionUtils;
import kd.sdk.plugin.Plugin;
import nckd.jxccl.sit.hcsi.formplugin.web.tp.enums.SinsurPresetItemEnum;
import nckd.jxccl.swc.hsas.common.OutImpPresetItem;
import nckd.jxccl.swc.hsas.formplugin.web.outdata.helper.OutImpTemplateHelper;

import java.util.*;

/**
 * Tyx 2025-12-08
 * 外单位数据导入模板 【nckd_outimptpl】
 */
public class OutImpTemplateEdit extends AbstractFormPlugin implements Plugin {

    private static String ENTRYKEY = "nckd_outimptplentry";

    public OutImpTemplateEdit() {

    }

    @Override
    public void afterCreateNewData(EventObject e) {
        super.afterCreateNewData(e);
        // 添加预置数据：
        createPresetItemData();
    }

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

    @Override
    public void beforeDoOperation(BeforeDoOperationEventArgs args) {
        super.beforeDoOperation(args);
        FormOperate formOperate = (FormOperate)args.getSource();
        String opKey = formOperate.getOperateKey();
        int[] selectRowIndexs = ((EntryGrid)this.getControl(ENTRYKEY)).getSelectRows();
        int[] rowIndexs;
        switch (opKey) {
            case "donothing_addmaprelation":
                this.openAddMatchRelationPage();
                break;
            case "donothing_deleteentry":
                if (selectRowIndexs.length == 0) {
                    this.getView().showTipNotification(ResManager.loadKDString("请选择要执行的数据。", "MigrationTemplateEdit_4", "swc-hsas-formplugin", new Object[0]));
                } else {
                    rowIndexs = this.getChangeableRowIndexs(selectRowIndexs);
                    if (rowIndexs.length < selectRowIndexs.length) {
                        this.getView().showTipNotification(ResManager.loadKDString("预置字段不可删除。", "MigrationTemplateEdit_0", "swc-hsas-formplugin", new Object[0]));
                    }

                    this.deleteEntry(rowIndexs);
                }
                break;
            case "donothing_moveup":
                if (selectRowIndexs.length == 0) {
                    this.getView().showTipNotification(ResManager.loadKDString("请选中一行再进行操作。", "MigrationTemplateEdit_3", "swc-hsas-formplugin", new Object[0]));
                } else {
                    //rowIndexs = this.getChangeableRowIndexs(selectRowIndexs);
                    this.moveUpEntry(selectRowIndexs);
                }
                break;
            case "donothing_movedown":
                if (selectRowIndexs.length == 0) {
                    this.getView().showTipNotification(ResManager.loadKDString("请选中一行再进行操作。", "MigrationTemplateEdit_3", "swc-hsas-formplugin", new Object[0]));
                } else {
                    //rowIndexs = this.getChangeableRowIndexs(selectRowIndexs);
                    this.moveDownEntry(selectRowIndexs);
                }
                break;
            case "save":
                ((FormOperate)args.getSource()).getOption().setVariableValue("save", Boolean.TRUE.toString());
                break;
            case "submit":
                ((FormOperate)args.getSource()).getOption().setVariableValue("save", Boolean.TRUE.toString());
                ((FormOperate)args.getSource()).getOption().setVariableValue("isList", Boolean.FALSE.toString());
        }
    }

    @Override
    public void propertyChanged(PropertyChangedArgs e) {
        super.propertyChanged(e);
        switch (e.getProperty().getName()) {
            case "org":
                this.clearUnPresetItemData();
                this.createPresetItemData();
                this.getView().updateView(ENTRYKEY);
                break;
        }
    }

    @Override
    public void closedCallBack(ClosedCallBackEvent evt) {
        super.closedCallBack(evt);
        switch (evt.getActionId()) {
            case "donothing_addmaprelation":
                this.addMatchRelationCloseEvent((DynamicObjectCollection)evt.getReturnData());
            default:
        }
    }

    public void confirmCallBack(MessageBoxClosedEvent messageBoxClosedEvent) {
        super.confirmCallBack(messageBoxClosedEvent);
        switch (messageBoxClosedEvent.getCallBackId()) {
            case "write_task_type_change":
                if (MessageBoxResult.Yes.equals(messageBoxClosedEvent.getResult())) {
                    this.getPageCache().remove("write_task_type_change");
                    this.changePresetItemData();
                } else {
                    this.getModel().setValue("writetasktype", this.getPageCache().get("write_task_type_change_old"));
                }
                this.getPageCache().remove("write_task_type_change_old");
            default:
        }
    }

    private void clearUnPresetItemData() {
        int row = this.getModel().getEntryEntity(ENTRYKEY).getRowCount();
        int[] allRowIndex = new int[row];
        for(int index = 0; index < row; allRowIndex[index] = index++) {

        }
        this.deleteEntry(allRowIndex);
    }

    private TableValueSetter createTableValueSetter() {
        TableValueSetter setter = new TableValueSetter(new String[0]);
        setter.addField("nckd_matchcolumn", new Object[0]);
        setter.addField("nckd_itemtype", new Object[0]);
        setter.addField("nckd_itemid", new Object[0]);
        setter.addField("nckd_salaryitem", new Object[0]);
        setter.addField("nckd_bizitem", new Object[0]);
        setter.addField("nckd_supportitem", new Object[0]);
        setter.addField("nckd_fetchitem", new Object[0]);
        setter.addField("nckd_itemnumber", new Object[0]);
        setter.addField("nckd_itemname", new Object[0]);
        setter.addField("nckd_datatype", new Object[0]);
        setter.addField("nckd_comment", new Object[0]);
        setter.addField("nckd_uniquecode", new Object[0]);
        setter.addField("nckd_ispreset", new Object[0]);
        return setter;
    }

    private int[] getChangeableRowIndexs(int[] selectRowIndexs) {
        int presetDataSize = this.getPresetDataSize();
        List<Integer> selectRowIndexList = new ArrayList(selectRowIndexs.length);
        int[] var4 = selectRowIndexs;
        int var5 = selectRowIndexs.length;

        for(int var6 = 0; var6 < var5; ++var6) {
            int index = var4[var6];
            if (index >= presetDataSize) {
                selectRowIndexList.add(index);
            }
        }

        selectRowIndexs = new int[selectRowIndexList.size()];

        for(int index = 0; index < selectRowIndexList.size(); ++index) {
            selectRowIndexs[index] = (Integer)selectRowIndexList.get(index);
        }

        return selectRowIndexs;
    }

    private void deleteEntry(int[] rowIndexs) {
        if (rowIndexs.length != 0) {
            this.getModel().deleteEntryRows(ENTRYKEY, rowIndexs);
        }
    }

    private void moveUpEntry(int[] rowIndexs) {
        if (rowIndexs.length != 0) {
            int presetDataSize = this.getPresetDataSize();
            if (rowIndexs[0] == presetDataSize) {
                int continueIndex;
                for(continueIndex = 0; continueIndex + 1 < rowIndexs.length && rowIndexs[continueIndex + 1] == rowIndexs[continueIndex] + 1; ++continueIndex) {
                }

                List<Integer> filterIndexList = new ArrayList(rowIndexs.length);

                int index;
                for(index = continueIndex + 1; index < rowIndexs.length; ++index) {
                    filterIndexList.add(rowIndexs[index]);
                }

                rowIndexs = new int[filterIndexList.size()];

                for(index = 0; index < filterIndexList.size(); ++index) {
                    rowIndexs[index] = (Integer)filterIndexList.get(index);
                }
            }

            if (rowIndexs.length != 0) {
                this.getModel().moveEntryRowsUp(ENTRYKEY, rowIndexs);
            }
        }
    }

    private void moveDownEntry(int[] rowIndexs) {
        if (rowIndexs.length != 0) {
            this.getModel().moveEntryRowsDown(ENTRYKEY, rowIndexs);
        }
    }

    private void openAddMatchRelationPage() {
        if (this.getModel().getValue("org") == null) {
            this.getView().showTipNotification(ResManager.loadKDString("请先选择算发薪管理组织后，再添加映射关系。", "MigrationTemplateEdit_1", "swc-hsas-formplugin", new Object[0]));
        } else {
            FormShowParameter showParameter = new FormShowParameter();
            showParameter.setFormId("nckd_outitemselect");
            //showParameter.setFormId("hsas_calitemselect");
            showParameter.getOpenStyle().setShowType(ShowType.Modal);
            showParameter.setParentPageId(this.getView().getPageId());
            showParameter.setCaption(ResManager.loadKDString("添加项目", "MigrationTemplateEdit_2", "swc-hsas-formplugin", new Object[0]));
            showParameter.setCloseCallBack(new CloseCallBack(this, "donothing_addmaprelation"));
            this.getView().showForm(showParameter);
        }
    }

    public void addMatchRelationCloseEvent(DynamicObjectCollection itemDatas) {
        if (itemDatas != null && itemDatas.size() != 0) {
            int presetDataSize = this.getPresetDataSize();
            DynamicObjectCollection entryDatas = this.getModel().getEntryEntity(ENTRYKEY);
            Map<Long, Map<String, Object>> existItemDataMap = new HashMap(entryDatas.size() - presetDataSize);
            int[] deleteRowIndex = new int[entryDatas.size() - presetDataSize];

            for(int index = presetDataSize; index < entryDatas.size(); deleteRowIndex[index - presetDataSize] = index++) {
                DynamicObject entryData = (DynamicObject)entryDatas.get(index);
                Map<String, Object> existItemData = new HashMap(2);
                existItemData.put("nckd_matchcolumn", entryData.getString("nckd_matchcolumn"));
                existItemData.put("nckd_comment", entryData.getString("nckd_comment"));
                existItemDataMap.put(entryData.getLong("nckd_itemid"), existItemData);
            }

            if (deleteRowIndex.length != 0) {
                this.getModel().deleteEntryRows(ENTRYKEY, deleteRowIndex);
            }

            Map<String, Map<String, Object>> itemParamMap = OutImpTemplateHelper.analyzeItemDatas(itemDatas, existItemDataMap);
            AbstractFormDataModel model = (AbstractFormDataModel)this.getModel();
            model.beginInit();
            TableValueSetter tableValueSetter = this.createTableValueSetter();
            Iterator it = itemDatas.iterator();

            while(it.hasNext()) {
                DynamicObject dataObj = (DynamicObject)it.next();
                String unicode = dataObj.getString("nckd_itemnumber");
                Map<String, Object> itemParam = (Map)itemParamMap.get(unicode);
                if (itemParam != null) {
                    Map<String, Object> existItemData = (Map)existItemDataMap.get(itemParam.get("id"));
                    String common;
                    String matchColumn;
                    if (existItemData != null) {
                        common = (String)existItemData.get("nckd_comment");
                        matchColumn = (String)existItemData.get("nckd_matchcolumn");
                    } else {
                        common = (String)itemParam.get("nckd_comment");
                        matchColumn = "";
                    }

                    String itemType = (String)itemParam.get("itemType");
                    Long itemId = (Long)itemParam.get("id");
                    if ("1".equals(itemType)) {
                        tableValueSetter.addRow(new Object[]{matchColumn, itemParam.get("itemType"), itemId, itemId, 0L, 0L, 0L, dataObj.get("nckd_itemnumber"), dataObj.get("nckd_itemname"), itemParam.get("dataTypeId"), common, unicode});
                    } else if ("2".equals(itemType)) {
                        tableValueSetter.addRow(new Object[]{matchColumn, itemParam.get("itemType"), itemId, itemId, 0L, 0L, 0L, dataObj.get("nckd_itemnumber"), dataObj.get("nckd_itemname"), itemParam.get("dataTypeId"), common, unicode});
                    } else if ("4".equals(itemType)) {
                        tableValueSetter.addRow(new Object[]{matchColumn, itemParam.get("itemType"), itemId, 0L, 0L, 0L, itemId, dataObj.get("nckd_itemnumber"), dataObj.get("nckd_itemname"), itemParam.get("dataTypeId"), common, unicode});
                    } else if ("3".equals(itemType)) {
                        tableValueSetter.addRow(new Object[]{matchColumn, itemParam.get("itemType"), itemId, 0L, itemId, 0L, 0L, dataObj.get("nckd_itemnumber"), dataObj.get("nckd_itemname"), itemParam.get("dataTypeId"), common, unicode});
                    }
                }
            }

            model.batchCreateNewEntryRow(ENTRYKEY, tableValueSetter);
            model.endInit();
            this.getView().updateView(ENTRYKEY);
        }
    }

    private void loadMatchRelationInfo() {
        DynamicObjectCollection entryDatas = this.getModel().getEntryEntity(ENTRYKEY);
        int presetDataSize = this.getPresetDataSize();
        if (!CollectionUtils.isEmpty(entryDatas)) {
            Map<String, Map<String, Object>> itemParamMap = OutImpTemplateHelper.analyzeMatchItem(entryDatas);
            IDataModel model = this.getModel();

            int index;
            DynamicObject entry;
            for(index = 0; index < presetDataSize; ++index) {
                entry = (DynamicObject)entryDatas.get(index);
                Long itemId = entry.getLong("nckd_itemid");
                OutImpPresetItem presetItemEnum = OutImpTemplateHelper.getPresetItemEnum(itemId);
                if (presetItemEnum != null) {
                    model.setValue("nckd_itemnumber", '-', index);
                    model.setValue("nckd_itemnumber", presetItemEnum.getItemName(), index);
                    model.setValue("nckd_itemnumber", "", index);
                }
            }

            for(index = presetDataSize; index < entryDatas.size(); ++index) {
                entry = (DynamicObject)entryDatas.get(index);
                String itemType = entry.getString("nckd_itemtype");
                Long itemId = entry.getLong("nckd_itemid");
                Map<String, Object> itemParam = (Map)itemParamMap.get(itemType + '-' + itemId);
                if (itemParam != null) {
                    model.setValue("nckd_itemnumber", itemParam.get("nckd_itemnumber"), index);
                    model.setValue("nckd_itemnumber", itemParam.get("nckd_itemnumber"), index);
                    model.setValue("nckd_itemnumber", itemParam.get("nckd_itemnumber"), index);
                }
            }

            this.getView().updateView(ENTRYKEY);
            this.getModel().setDataChanged(false);
        }
    }

    private int getPresetDataSize() {
        DynamicObjectCollection entryDatas = this.getModel().getEntryEntity(ENTRYKEY);
        int index;
        for(index = 0; index < entryDatas.size(); ++index) {
            DynamicObject entry = (DynamicObject)entryDatas.get(index);
//            if (!StringUtils.equals(entry.getString("nckd_itemtype"), "0")) {
//                break;
//            }
            if(!entry.getBoolean("nckd_ispreset")) {
                break;
            }
        }
        return index;
    }

    private void createPresetItemData() {
        AbstractFormDataModel model = (AbstractFormDataModel) this.getModel();
        TableValueSetter tableValueSetter = this.createTableValueSetter();
        List<OutImpPresetItem> presetItemEnumsList = OutImpTemplateHelper.getPresetItemEnumList();
        if (!CollectionUtils.isEmpty(presetItemEnumsList)) {
            for(OutImpPresetItem presetItemEnum : presetItemEnumsList) {
                tableValueSetter.addRow(new Object[]{presetItemEnum.getMatchColumn(), "2", presetItemEnum.getItemId(), 0L, 0L, 0L, 0L, presetItemEnum.getItemNumber(), presetItemEnum.getItemName(), presetItemEnum.getDataTypeId(), presetItemEnum.getComment(), "", true});
            }
        }
        model.beginInit();
        model.batchCreateNewEntryRow(ENTRYKEY, tableValueSetter);
        model.endInit();
        this.getView().updateView(ENTRYKEY);
    }

    private void changePresetItemData() {
//        DynamicObjectCollection entryDatas = this.getModel().getEntryEntity(ENTRYKEY);
//        Iterator<DynamicObject> iterator = entryDatas.iterator();
//
//        while(iterator.hasNext()) {
//            DynamicObject next = (DynamicObject)iterator.next();
//            if (SWCStringUtils.equals(next.getString("nckd_itemtype"), "0")) {
//                iterator.remove();
//            }
//        }
//
//        List<DynamicObject> entryList = new ArrayList(entryDatas.size());
//        entryList.addAll(entryDatas);
//        this.getModel().deleteEntryData(ENTRYKEY);
//        AbstractFormDataModel model = (AbstractFormDataModel)this.getModel();
//        DynamicObject data = model.getDataEntity();
//        model.beginInit();
//        TableValueSetter tableValueSetter = this.createTableValueSetter();
//        List<PresetItemEnum> presetItemEnumsList = OutImpTemplateHelper.getPresetItemEnumList(data.getString("writetasktype"), data.getBoolean("ismultimeoneperiod"));
//        if (!CollectionUtils.isEmpty(presetItemEnumsList)) {
//            Iterator it = presetItemEnumsList.iterator();
//
//            while(it.hasNext()) {
//                PresetItemEnum presetItemEnum = (PresetItemEnum)it.next();
//                tableValueSetter.addRow(new Object[]{presetItemEnum.getMatchColumn(), "0", presetItemEnum.getItemId(), 0L, 0L, 0L, 0L, '-', presetItemEnum.getItemName(), presetItemEnum.getDataTypeId(), presetItemEnum.getComment().getLocaleString(), ""});
//            }
//
//            it = entryList.iterator();
//
//            while(it.hasNext()) {
//                DynamicObject entryData = (DynamicObject)it.next();
//                tableValueSetter.addRow(new Object[]{
//                        entryData.getString("nckd_matchcolumn"),
//                        entryData.getString("nckd_itemtype"),
//                        entryData.getLong("nckd_itemid"),
//                        entryData.getLong("nckd_salaryitem.id"),
//                        entryData.getLong("nckd_bizitem.id"),
//                        entryData.getLong("nckd_supportitem.id"),
//                        entryData.getLong("nckd_fetchitem.id"),
//                        entryData.getString("nckd_itemnumber"),
//                        entryData.getString("nckd_itemname"),
//                        entryData.getLong("nckd_datatype.id"),
//                        entryData.getString("nckd_comment"),
//                        entryData.getString("nckd_uniquecode")
//                });
//            }
//
//            model.batchCreateNewEntryRow(ENTRYKEY, tableValueSetter);
//            model.endInit();
//            this.getView().updateView(ENTRYKEY);
//        }
    }

}