package com.yem.wm.bc.change.from;

import java.util.*;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.yem.wm.bc.change.business.ChangeModelHelper;
import com.yem.wm.bc.change.common.consts.ChangeResumeFormConst;
import com.yem.wm.bc.change.common.consts.ChangeTypeEnum;
import com.yem.wm.bc.change.common.consts.LabelMappingFieldsMap;
import com.yem.wm.bc.common.CommonUtils;
import kd.bos.bill.AbstractBillPlugIn;
import kd.bos.bill.OperationStatus;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.dataentity.metadata.IDataEntityProperty;
import kd.bos.dataentity.metadata.IDataEntityType;
import kd.bos.dataentity.resource.ResManager;
import kd.bos.entity.BillEntityType;
import kd.bos.entity.EntityType;
import kd.bos.entity.MainEntityType;
import kd.bos.entity.datamodel.IDataModel;
import kd.bos.entity.datamodel.RowDataEntity;
import kd.bos.entity.datamodel.events.AfterAddRowEventArgs;
import kd.bos.entity.datamodel.events.BeforeDeleteRowEventArgs;
import kd.bos.entity.property.EntryProp;
import kd.bos.entity.property.SubEntryProp;
import kd.bos.entity.report.CellStyle;
import kd.bos.form.ClientProperties;
import kd.bos.form.FormShowParameter;
import kd.bos.form.ShowType;
import kd.bos.form.cardentry.CardEntry;
import kd.bos.form.control.*;
import kd.bos.form.control.events.BeforeItemClickEvent;
import kd.bos.form.control.events.EntryGridBindDataEvent;
import kd.bos.form.control.events.EntryGridBindDataListener;
import kd.bos.form.control.events.ItemClickEvent;
import kd.bos.form.control.events.RowClickEvent;
import kd.bos.form.control.events.RowClickEventListener;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.BeforeDoOperationEventArgs;
import kd.bos.form.events.PreOpenFormEventArgs;
import kd.bos.form.operate.FormOperate;
import kd.bos.logging.Log;
import kd.bos.logging.LogFactory;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;

/**
 * @author 夜子
 * @ClassName XBillChangePlugin
 * @description: 变更单表单插件
 * @date 2023年08月03日
 * @version: 1.0
 */
public class XBillChangePlugin extends AbstractBillPlugIn implements RowClickEventListener, EntryGridBindDataListener {
    public static Log logger = LogFactory.getLog(XBillChangePlugin.class);

    private final String UpdateBackColor="#ecf6ff";

    public void preOpenForm(PreOpenFormEventArgs e) {
        String billtype;
        DynamicObject changeModel;
        super.preOpenForm(e);
        FormShowParameter formShowPar = e.getFormShowParameter();
        OperationStatus operationStatus = formShowPar.getStatus();
        if (OperationStatus.ADDNEW.getValue() != operationStatus.getValue() && formShowPar.getFormConfig() != null
                && !CommonUtils.isNull((Object) formShowPar.getFormConfig().getEntityTypeId())
                && (changeModel = ChangeModelHelper.getChangeModel4XBill(
                (String) (billtype = formShowPar.getFormConfig().getEntityTypeId()))) == null) {
            e.setCancelMessage(ResManager.loadKDString((String) "当前单据没有启用的变更模型，请联系开发服务人员维护变更模型数据。",
                    (String) "SrcBillBizChangeOpValidator_2", (String) "yem-yc-changemodel",
                    (Object[]) new Object[0]));
            e.setCancel(true);
        }
    }

    protected Map<String, Map<String, String>> getXBillEntryAndOp() {
        Map<String, Map<String, String>> result = new HashMap<>();
        DynamicObject changeModel = ChangeModelHelper
                .getChangeModel4XBill((String) this.getModel().getDataEntityType().getName());
        result = ChangeModelHelper.getXBillEntryAndOp((DynamicObject) changeModel);
        if (result.size() != 0) {
            return result;
        }
        HashMap<String, String> value = new HashMap<String, String>();
        value.put("entity", "billentry");
        value.put("entry_toolbar", "tbmainentry");
        value.put("btn_add", "addrow");
        value.put("btn_delete", "deleterow");
        value.put("btn_modify", "modifyrow");
        value.put("changetype", "billentrychangetype");
        value.put("srcid", "billentrysrcid");
        result.put("entity", value);
        return result;
    }

    @Override
    public void initialize() {
        super.initialize();
        this.setListener();
    }

    @Override
    public void registerListener(EventObject e) {
        super.registerListener(e);
        this.setListener();
    }
    public void setListener(){
        Map<String, Map<String, String>> xBillEntrys = this.getXBillEntryAndOp();
        for (Map.Entry<String, Map<String, String>> entry : xBillEntrys.entrySet()) {
            String entryEntity = entry.getKey();
            Control entryGrid = this.getView().getControl(entryEntity);
            if (!(entryGrid instanceof EntryGrid))
                continue;
            ((EntryGrid) entryGrid).addDataBindListener(this);
            ((EntryGrid) entryGrid).addRowClickListener(this);

            this.addItemClickListeners(entry.getValue().get("entry_toolbar"));
        }
    }

    public void beforeBindData(EventObject e) {
        MainEntityType entityType = this.getModel().getDataEntityType();
        if (entityType instanceof BillEntityType) {
            ((BillEntityType) entityType).setBillNo("changebillno");
        }
    }

    public void afterBindData(EventObject e) {
        this.ViewSetEnable();
        DynamicObject Bill = this.getModel().getDataEntity();
        FormShowParameter showParameter = this.getView().getFormShowParameter();
        Map<String, Object> customParams = showParameter.getCustomParams();
        if(customParams!=null){
            if(customParams.get("InContainer")!=null){
                this.getView().setVisible(false,"titlepanel");
            }
            Object crdheadjson  =  customParams.get("crdheadjson");
            Object crdentryjson =  customParams.get("crdentryjson");

            if(crdheadjson!=null){
                String[] billfields = ChangeModelHelper.getCanLogProperty(Bill.getDynamicObjectType());
                LinkedHashMap<String, Object> xbillJsonMap = JSON.parseObject((String) crdheadjson, new TypeReference<LinkedHashMap<String, Object>>() {});
                if (billfields != null) {
                    for(String billfield :billfields){
                       JSONObject fieljsonObject = (JSONObject) xbillJsonMap.get(billfield);
                       String fielChangeType= (String) fieljsonObject.get("e");
                       Map<String, Object> map = new HashMap<>();
                        if (fielChangeType.equals("*")) {
                            map.put(ClientProperties.BackColor, UpdateBackColor);//设置背景色
                            this.getView().updateControlMetadata(billfield, map);
                            if(billfield.contains("_startdate")||billfield.contains("_enddate")){
                                billfield = billfield.replace("_startdate","");
                                billfield = billfield.replace("_enddate","");
                                this.getView().updateControlMetadata(billfield, map);
                            }
                            SetLabelMappingFieldsColor(Bill.getDynamicObjectType().getName(),billfield);

                        }
                    }
                }
            }
            if(crdentryjson!=null){
                List<EntityType> entryEntities = ChangeModelHelper.getChildEntities(Bill.getDataEntityType());
                LinkedHashMap<String, Object> xbillEntryJsonMap = JSON.parseObject((String) crdentryjson, new TypeReference<LinkedHashMap<String, Object>>() {});
                for(EntityType entryEntitie :entryEntities){
                    JSONArray entryArray= (JSONArray) xbillEntryJsonMap.get(entryEntitie.getName());
                    SetEntryBackColor(Bill, entryEntitie, entryArray,-1);
                }
            }
        }
    }

    public void entryGridBindData(EntryGridBindDataEvent e) {
        List<RowDataEntity> rows = e.getRows();
        if (rows == null || rows.size() == 0) {
            return;
        }
        Map<String, Map<String, String>> xBillEntrys = this.getXBillEntryAndOp();
        if (xBillEntrys == null || xBillEntrys.isEmpty()) {
            return;
        }
        EntryGrid entryGrid = (EntryGrid) e.getSource();
        String entryEntity = entryGrid.getKey();
        if (!xBillEntrys.containsKey(entryEntity)) {
            return;
        }
        Map<String, String> xBillEntry = xBillEntrys.get(entryEntity);
        IDataEntityType dt = this.getModel().getDataEntity().getDataEntityType();
        String[] unEnableEntryPropertys = ChangeModelHelper.getUnEnableProperty((IDataEntityType) dt,
                (String) entryEntity);
        String[] enableEntryProperrtys = ChangeModelHelper.getEnableProperty((IDataEntityType) dt,
                (String) entryEntity);
        for (RowDataEntity row : rows) {
            int index = row.getRowIndex();
            String changeType = (String) this.getModel().getValue(xBillEntry.get("changetype"), index);
            if (ChangeTypeEnum.UPDATE.getValue().equals(changeType)) {
                this.getView().setEnable(Boolean.FALSE, index, unEnableEntryPropertys);
                this.getView().setEnable(Boolean.TRUE, index, enableEntryProperrtys);
                continue;
            }
            if (!ChangeTypeEnum.CANCEL.getValue().equals(changeType))
                continue;
            this.getView().setEnable(Boolean.FALSE, index, unEnableEntryPropertys);
            this.getView().setEnable(Boolean.FALSE, index, enableEntryProperrtys);
        }
    }

    private void SetEntryBackColor(DynamicObject bill, EntityType entryEntitie, JSONArray entryArray,int row) {
        if(entryArray!=null){
            EntryGrid entry = this.getView().getControl(entryEntitie.getName());
            for (int i = 0; i < entryArray.size(); i++) {
                JSONObject jsonObject =  entryArray.getJSONObject(i);
                String lineChangeType= (String) jsonObject.get("f");
                int lineRow= Integer.parseInt((String) jsonObject.get("l")) -1;
                String addNewBackColor = "#d5fbe2";
                String deleteBackColor = "#fef1d0";
                switch (lineChangeType) {
                    case "+":
                        if(entry instanceof CardEntry) {
                            SetCardEntryRowBackColor(addNewBackColor,entryEntitie,lineRow);
                        }else{
                            entry.setRowBackcolor(addNewBackColor, new int[]{lineRow});
                        }
                        break;
                    case "-":
                        if(entry instanceof CardEntry) {
                            SetCardEntryRowBackColor(deleteBackColor,entryEntitie,lineRow);
                        }else{
                            entry.setRowBackcolor(deleteBackColor, new int[]{lineRow});
                        }
                        break;
                    case "*":

                        String[] billfields = ChangeModelHelper.getCanLogProperty(bill.getDynamicObjectType(),entryEntitie.getName());
                        if (billfields != null) {
                            if(entry instanceof CardEntry) {
                                CardEntry cardEntry = this.getView().getControl(entryEntitie.getName());
                                //结果必须正确，否则不生效
                                Map<String, Object> map_textfield = new HashMap<>();
                                Map<String, Object> prop_textfield = new HashMap<>();

                                //背景颜色
                                prop_textfield.put(ClientProperties.BackColor, UpdateBackColor);
                                for(String billfield :billfields){
                                    JSONObject fieljsonObject = (JSONObject) jsonObject.get(billfield);
                                    String fielChangeType= (String) fieljsonObject.get("e");
                                    if (fielChangeType.equals("*")) {
                                        map_textfield.put(billfield, prop_textfield);
                                    }
                                }

                                //此方法只设置一些样式属性，不能圆角半径等属性
                                cardEntry.setCustomProperties(cardEntry.getKey(), lineRow, map_textfield);

                            }else{
                                List<CellStyle> cellStyle = new ArrayList<>();
                                for(String billfield :billfields){
                                    JSONObject fieljsonObject = (JSONObject) jsonObject.get(billfield);
                                    String fielChangeType= (String) fieljsonObject.get("e");
                                    if (fielChangeType.equals("*")) {
                                        CellStyle cs = new CellStyle();
                                        cs.setFieldKey(billfield);
                                        cs.setRow(lineRow);
                                        cs.setBackColor(UpdateBackColor);
                                        cellStyle.add(cs);
                                    }
                                }
                                entry.setCellStyle(cellStyle);
                            }

                        }
                        break;
                }
            }
            List<EntityType> ChildentryEntities = ChangeModelHelper.getChildEntities(entryEntitie);
            for(EntityType ChildentryEntitie :ChildentryEntities){
                if(row==-1){
                    row =0;
                }
                JSONArray ChildentryentryArray=  entryArray.getJSONObject(row).getJSONArray(ChildentryEntitie.getName());
                SetEntryBackColor(bill, ChildentryEntitie, ChildentryentryArray,-1);
            }
        }
    }
    private void SetCardEntryRowBackColor(String BackColor,EntityType  entryEntitie, int lineRow) {
        CardEntry cardEntry = this.getView().getControl(entryEntitie.getName());
        //结果必须正确，否则不生效
        Map<String, Object> map_textfield = new HashMap<>();
        Map<String, Object> prop_textfield = new HashMap<>();
        Map<String, IDataEntityProperty> PropertyMap= entryEntitie.getFields();
        //背景颜色
        prop_textfield.put(ClientProperties.BackColor, BackColor);

        for(String key:PropertyMap.keySet()){
            map_textfield.put(key, prop_textfield);
        }
        //此方法只设置一些样式属性，不能圆角半径等属性
        cardEntry.setCustomProperties(cardEntry.getKey(), lineRow, map_textfield);
    }

    /**
     * @MethodName SetLabelMappingFieldsColor
     * @Author  SC
     * @Description  设置 变更字段的映射标签 颜色
     * @Date 15:40 2023/8/16
     * @Param [billtype, billfield] 单据标识,字段名
     **/
    private void SetLabelMappingFieldsColor(String billtype,String billfield) {
        Map<String, Map<String, String>> filedmap = LabelMappingFieldsMap.Bill_Label_Fields_Map;
        Map<String, String> Label_Fields_Map = new HashMap<>();
        if (filedmap.get(billtype) != null) {
            Label_Fields_Map = filedmap.get(billtype);
        }else{
            Label_Fields_Map = filedmap.get("defaultBill");
        }
        if(Label_Fields_Map.containsKey(billfield)){
            Map<String, Object> map = new HashMap<>();
            //背景颜色
            map.put(ClientProperties.BackColor, UpdateBackColor);
//        //前景颜色
//        map.put(ClientProperties.ForeColor, "#ffffff");
            this.getView().updateControlMetadata(Label_Fields_Map.get(billfield), map);
        }
    }


    public void afterCreateNewData(EventObject e) {
        IDataModel bill = this.getModel();
        long afterCreateNewDataTime = System.currentTimeMillis();
        logger.info(
                "BizChangePerformance----Function(afterCreateNewData)BeginTime:" + new Date(afterCreateNewDataTime));
        for (IDataEntityProperty entityProperty : bill.getDataEntityType().getProperties()) {
            if (entityProperty instanceof SubEntryProp || !(entityProperty instanceof EntryProp))
                continue;
            DynamicObjectCollection entrys = (DynamicObjectCollection) bill.getValue(entityProperty.getName());
            for (DynamicObject entry : entrys) {
                entry.getDataEntityState().setDirty(true);
                entry.getDataEntityState().setBizChanged(true);
                entry.getDataEntityState().setBizChangeFlags(entry.getDataEntityState().getDirtyFlags());
                for (IDataEntityProperty subEntityProperty : entry.getDataEntityType().getProperties()) {
                    if (!(subEntityProperty instanceof SubEntryProp))
                        continue;
                    DynamicObjectCollection subEntrys = entry.getDynamicObjectCollection(subEntityProperty.getName());
                    for (DynamicObject subEntry : subEntrys) {
                        subEntry.getDataEntityState().setDirty(true);
                        subEntry.getDataEntityState().setBizChanged(true);
                        subEntry.getDataEntityState().setBizChangeFlags(subEntry.getDataEntityState().getDirtyFlags());
                    }
                }
            }
        }
        long seteditbegintime = System.currentTimeMillis();
        logger.info(
                "BizChangePerformance----Function(afterCreateNewData)BillEditedSetBegin：" + new Date(seteditbegintime));
        IDataEntityType dt = this.getModel().getDataEntity().getDataEntityType();
        String[] unEnablePropertys = ChangeModelHelper.getUnEnableProperty((IDataEntityType) dt);
        String[] enablePropertys = ChangeModelHelper.getEnableProperty((IDataEntityType) dt);
        if (!CommonUtils.isNull((Object) unEnablePropertys)) {
            this.getView().setEnable(Boolean.FALSE, unEnablePropertys);
        }
        if (!CommonUtils.isNull((Object) enablePropertys)) {
            this.getView().setEnable(Boolean.TRUE, enablePropertys);
        }
        long seteditendtime = System.currentTimeMillis();
        logger.info("BizChangePerformance----Function(afterCreateNewData)BillEditedSetEnd" + new Date(seteditendtime));
        logger.info("BizChangePerformance----Function(afterCreateNewData)BillEditedSetUseTime ："
                + (seteditendtime - seteditbegintime) + " ms");
    }

    public void entryRowClick(RowClickEvent evt) {
        RowClickEventListener.super.entryRowClick(evt);
        IDataEntityType dt = this.getModel().getDataEntity().getDataEntityType();
        int row = evt.getRow();
        if (evt.getSource() instanceof EntryGrid && row != -1) {
            String key = ((EntryGrid) evt.getSource()).getKey();
            Map<String, Map<String, String>> xBillEntrys = this.getXBillEntryAndOp();
            if (!xBillEntrys.containsKey(key)) {
                return;
            }
            Map<String, String> xBillEntry = xBillEntrys.get(key);
            String[] unEnableEntryPropertys = ChangeModelHelper.getUnEnableProperty((IDataEntityType) dt, (String) key);
            String[] enableEntryProperrtys = ChangeModelHelper.getEnableProperty((IDataEntityType) dt, (String) key);
            String changeType = (String) this.getModel().getValue(xBillEntry.get("changetype"), row);
            if (ChangeTypeEnum.UPDATE.getValue().equals(changeType)) {
                this.getView().setEnable(Boolean.FALSE, row, unEnableEntryPropertys);
                this.getView().setEnable(Boolean.TRUE, row, enableEntryProperrtys);
            } else if (ChangeTypeEnum.CANCEL.getValue().equals(changeType)) {
                this.getView().setEnable(Boolean.FALSE, row, unEnableEntryPropertys);
                this.getView().setEnable(Boolean.FALSE, row, enableEntryProperrtys);
            }

            FormShowParameter showParameter = this.getView().getFormShowParameter();
            Map<String, Object> customParams = showParameter.getCustomParams();
            DynamicObject Bill = this.getModel().getDataEntity();
            if(customParams!=null){
                Object crdentryjson =  customParams.get("crdentryjson");

                if(crdentryjson!=null){
                    List<EntityType> entryEntities = ChangeModelHelper.getChildEntities(Bill.getDataEntityType());
                    EntityType entryEntitie = ChangeModelHelper.getChildEntitiesByName(entryEntities,key);
                    LinkedHashMap<String, Object> xbillEntryJsonMap = JSON.parseObject((String) crdentryjson, new TypeReference<LinkedHashMap<String, Object>>() {});
                    JSONArray entryArray= (JSONArray) xbillEntryJsonMap.get(key);
                    SetEntryBackColor(Bill, entryEntitie, entryArray,row);
                }
            }
        }
    }

    public void afterAddRow(AfterAddRowEventArgs evt) {
        RowDataEntity[] rowDataEntitys;
        IDataModel xBill = this.getModel();
        String entryEntity = evt.getEntryProp().getName();
        Map<String, String> xBillEntry = this.getXBillEntryAndOp().get(entryEntity);
        if (xBillEntry == null) {
            return;
        }
        for (RowDataEntity rowDataEntity : rowDataEntitys = evt.getRowDataEntities()) {
            xBill.setValue(xBillEntry.get("changetype"), (Object) ChangeTypeEnum.ADDNEW.getValue(),
                    rowDataEntity.getRowIndex());
        }
        Map<String, Map<String, String>> result = this.getXBillEntryAndOp();
        String changeType = result.get(entryEntity).get("changetype");
        IDataEntityType dt = this.getModel().getDataEntity().getDataEntityType();
        String[] unEnableProperty = ChangeModelHelper.getUnEnableProperty((IDataEntityType) dt, (String) entryEntity);
        String[] enableProperty = ChangeModelHelper.getEnableProperty((IDataEntityType) dt, (String) entryEntity);
        int rowCount = this.getModel().getEntryRowCount(entryEntity);
        for (int i = 0; i < rowCount; ++i) {
            if (!ChangeTypeEnum.UPDATE.getValue().equals(xBill.getValue(changeType, i)))
                continue;
            if (!CommonUtils.isNull((Object) unEnableProperty)) {
                this.getView().setEnable(Boolean.FALSE, i, unEnableProperty);
            }
            if (CommonUtils.isNull((Object) enableProperty))
                continue;
            this.getView().setEnable(Boolean.TRUE, i, enableProperty);
        }
    }

    public void beforeDeleteRow(BeforeDeleteRowEventArgs evt) {
        IDataModel xBill = this.getModel();
        String entryEntity = evt.getEntryProp().getName();
        IDataEntityType dt = this.getModel().getDataEntity().getDataEntityType();
        Map<String, String> xBillEntry = this.getXBillEntryAndOp().get(entryEntity);
        if (xBillEntry == null) {
            return;
        }
        Control entryGrid = this.getView().getControl(entryEntity);
        DynamicObjectCollection  entryEntityCol= xBill.getEntryEntity(entryEntity);
        String[] allEntryProperties = ChangeModelHelper.getProperty4Entry((IDataEntityType) dt, (String) entryEntity);
        int[] RowCol =  evt.getRowIndexs();
        for (int curRow : RowCol) {
            if (!ChangeTypeEnum.UPDATE.getValue().equals(xBill.getValue(xBillEntry.get("changetype"), curRow))
                    && !ChangeTypeEnum.CANCEL.getValue().equals(xBill.getValue(xBillEntry.get("changetype"), curRow)))
                continue;
            if ( entryGrid instanceof TreeEntryGrid){
                 long enID =   entryEntityCol.get(curRow).getLong("id");
                 for(int i = 0 ;i<entryEntityCol.size();i++){
                     long enPID =  entryEntityCol.get(i).getLong("pid");
                     if(enPID ==enID ){
                         boolean next = true;
                         for(int Row : RowCol){
                             if (Row == i) {
                                 next = false;
                                 break;
                             }
                         }
                         if(next){
                             this.getView().showErrorNotification(ResManager.loadKDString("请先删除子行，再删除父行",
                                     "XBillChangeListPlugin_5",  "yem-yc-changemodel",
                                     (Object[]) new Object[0]));
                             evt.setCancel(true);
                             return;
                         }
                     }
                 }
            }
            xBill.setValue(xBillEntry.get("changetype"), (Object) ChangeTypeEnum.CANCEL.getValue(), curRow);
            this.getView().setEnable(Boolean.FALSE, curRow, allEntryProperties);
            evt.setCancel(true);
        }
    }

    public void beforeItemClick(BeforeItemClickEvent evt) {
        super.beforeItemClick(evt);
        String evtItemKey = evt.getItemKey();
        Map<String, Map<String, String>> result = this.getXBillEntryAndOp();
        for (Map.Entry<String, Map<String, String>> entry : result.entrySet()) {
            int[] selectRows;
            if (!evtItemKey.equals(entry.getValue().get("btn_modify"))
                    && !evt.getItemKey().equals(entry.getValue().get("btn_delete")))
                continue;
            String entryEntity = entry.getKey();
            Control entryGrid = this.getView().getControl(entryEntity);
            if (!(entryGrid instanceof EntryGrid)
                    || (selectRows = ((EntryGrid) entryGrid).getSelectRows()).length > 0)
                continue;
            this.getView().showTipNotification(ResManager.loadKDString((String) "请先选择分录行。",
                    (String) "XBillChangePlugin_0", (String) "yem-yc-changemodel", (Object[]) new Object[0]));
            evt.setCancel(true);
        }
    }

    public void itemClick(ItemClickEvent evt) {
        Map<String, Map<String, String>> result = this.getXBillEntryAndOp();
        IDataModel xBill = this.getModel();
        for (Map.Entry<String, Map<String, String>> entry : result.entrySet()) {
            int[] selectRows;
            if (!evt.getItemKey().equals(entry.getValue().get("btn_modify")))
                continue;
            String entryEntity = entry.getKey();
            Control entryGrid = this.getView().getControl(entryEntity);
            if (!(entryGrid instanceof EntryGrid)
                    || (selectRows = ((EntryGrid) entryGrid).getSelectRows()).length <= 0)
                continue;
            boolean nocanmodidataflag = true;
            IDataEntityType dt = this.getModel().getDataEntity().getDataEntityType();
            String[] unEnableProperty = ChangeModelHelper.getUnEnableProperty((IDataEntityType) dt,
                    (String) entryEntity);
            String[] enableProperty = ChangeModelHelper.getEnableProperty((IDataEntityType) dt, (String) entryEntity);
            for (int selectRow : selectRows) {
                if (ChangeTypeEnum.ADDNEW.getValue()
                        .equals(this.getModel().getValue(result.get(entryEntity).get("changetype"), selectRow))
                        || ChangeTypeEnum.UPDATE.getValue()
                        .equals(this.getModel().getValue(result.get(entryEntity).get("changetype"), selectRow)))
                    continue;
                xBill.setValue(result.get(entryEntity).get("changetype"), (Object) ChangeTypeEnum.UPDATE.getValue(),
                        selectRow);
                this.getView().setEnable(Boolean.FALSE, selectRow, unEnableProperty);
                this.getView().setEnable(Boolean.TRUE, selectRow, enableProperty);
                nocanmodidataflag = false;
            }
            if (!nocanmodidataflag)
                continue;
            this.getView().showTipNotification(ResManager.loadKDString((String) "请选择变更方式为“取消”状态的分录行进行修改操作。",
                    (String) "XBillChangePlugin_1", (String) "yem-yc-changemodel", (Object[]) new Object[0]));
            return;
        }
    }

    public void beforeDoOperation(BeforeDoOperationEventArgs args) {
        super.beforeDoOperation(args);
        FormOperate operate = (FormOperate) args.getSource();
        String xBillEntity = this.getModel().getDataEntityType().getName();
        switch (operate.getOperateKey()) {
            case "save" :
            case "submit" :
            case "unsubmit" :
            case "audit" :
            case "unaudit" :
            case "bizvalid" : {
                DynamicObject changeModel = ChangeModelHelper.getChangeModel4XBill((String) xBillEntity);
                if (changeModel == null) {
                    this.getView()
                            .showTipNotification(ResManager.loadKDString((String) "当前单据没有启用的变更模型，请联系开发服务人员维护变更模型数据。",
                                    (String) "SrcBillBizChangeOpValidator_2", (String) "yem-yc-changemodel",
                                    (Object[]) new Object[0]));
                    args.setCancel(true);
                    break;
                }
                FormShowParameter showParameter = this.getView().getFormShowParameter();
                String enableChangeResume = (String) showParameter
                        .getCustomParam(ChangeResumeFormConst.ENABLE_CHANGERESUME);
                if (CommonUtils.isNull((Object) enableChangeResume)
                        && CommonUtils.isNull((Object) (enableChangeResume = this.getPageCache()
                        .get(ChangeResumeFormConst.ENABLE_CHANGERESUME)))) {
                    enableChangeResume = "true";
                    this.getPageCache().put(ChangeResumeFormConst.ENABLE_CHANGERESUME, enableChangeResume);
                }
                operate.getOption().setVariableValue(ChangeResumeFormConst.ENABLE_CHANGERESUME, enableChangeResume);
            }
        }
        Long xBillID = (Long) this.getModel().getValue("id");
        if (xBillID != null && "bizchangeresume".equals(operate.getOperateKey())) {
            QFilter qFilter = new QFilter("xbillid", "=", (Object) xBillID);
            QFilter qFilter2 = new QFilter("currentchangenumber", "!=", (Object) 0);
            DynamicObject changerecord = BusinessDataServiceHelper.loadSingleFromCache((String) "yem_changeresume",
                    (QFilter[]) new QFilter[]{qFilter, qFilter2});
            if (changerecord != null) {
                FormShowParameter changeResume = new FormShowParameter();
                changeResume.setFormId("yem_changeresumeform");
                changeResume.getOpenStyle().setShowType(ShowType.MainNewTabPage);
                changeResume.setStatus(OperationStatus.EDIT);
                changeResume.setCustomParam("srcbillid", changerecord.get("srcbillid"));
                changeResume.setCustomParam("srcbillno", changerecord.get("srcbillno"));
                changeResume.setCustomParam("xbillid", (Object) xBillID);
                this.getView().showForm(changeResume);
            } else {
                this.getView()
                        .showTipNotification(ResManager.loadKDString((String) "没有实际录入变更数据，暂未记录变更履历信息。",
                                (String) "XBillChangeListPlugin_2", (String) "yem-yc-changemodel",
                                (Object[]) new Object[0]));
                args.setCancel(true);
            }
        }
    }

    public void afterDoOperation(AfterDoOperationEventArgs args) {
        DynamicObject changeModel;
        super.afterDoOperation(args);
        FormOperate operate = (FormOperate) args.getSource();
        if ("audit".equalsIgnoreCase(args.getOperateKey()) && args.getOperationResult().isSuccess()
                && (changeModel = ChangeModelHelper.getChangeModel4XBill((String) operate.getEntityId())) != null
                && "auto".equals(changeModel.getString("updatetype"))) {
            this.getView().invokeOperation("bizvalid");
        }
    }

    public void ViewSetEnable(){
        long begintime = System.currentTimeMillis();
        logger.info("BizChangePerformance----Function(afterBindData)EntryEditedSetBegin：" + new Date(begintime));
        IDataEntityType dt = this.getModel().getDataEntity().getDataEntityType();
        String[] unEnablePropertys = ChangeModelHelper.getUnEnableProperty((IDataEntityType) dt);
        String[] enablePropertys = ChangeModelHelper.getEnableProperty((IDataEntityType) dt);
        if (!CommonUtils.isNull((Object) unEnablePropertys)) {
            this.getView().setEnable(Boolean.FALSE, unEnablePropertys);
        }
        if (!CommonUtils.isNull((Object) enablePropertys)) {
            this.getView().setEnable(Boolean.TRUE, enablePropertys);
        }
        Map<String, Map<String, String>> result = this.getXBillEntryAndOp();
        for (Map.Entry<String, Map<String, String>> entry : result.entrySet()) {
            DynamicObject[] dynamicObjects;
            String entryEntity = entry.getKey();
            Map<String, String> xBillEntry = result.get(entryEntity);
            String[] unEnableEntryPropertys = ChangeModelHelper.getUnEnableProperty((IDataEntityType) dt,
                    (String) entryEntity);
            String[] enableEntryProperrtys = ChangeModelHelper.getEnableProperty((IDataEntityType) dt,
                    (String) entryEntity);
            EntryGrid entrygrid = (EntryGrid) this.getControl(entryEntity);
            if (entrygrid == null || entrygrid.getEntryData() == null) {
                continue;
            }
            EntryData entrydata = entrygrid.getEntryData();
            boolean blon = entrygrid.isSplitPage();
            int pageCount = entrydata.getPageCount();
            if (blon) {
                if (pageCount > 0) {
                    int startIdx = entrydata.getStartIndex();
                    int endIdx = entrydata.getEndIndex();
                    for (int i = startIdx; i < endIdx; ++i) {
                        String changeType = (String) this.getModel().getValue(xBillEntry.get("changetype"), i);
                        if (ChangeTypeEnum.UPDATE.getValue().equals(changeType)) {
                            this.getView().setEnable(Boolean.FALSE, i, unEnableEntryPropertys);
                            this.getView().setEnable(Boolean.TRUE, i, enableEntryProperrtys);
                            continue;
                        }
                        if (!ChangeTypeEnum.CANCEL.getValue().equals(changeType))
                            continue;
                        this.getView().setEnable(Boolean.FALSE, i, unEnableEntryPropertys);
                        this.getView().setEnable(Boolean.FALSE, i, enableEntryProperrtys);
                    }
                }
            } else if (entrydata.getDataEntitys() != null && (dynamicObjects = entrydata.getDataEntitys()).length > 0) {
                for (int i = 0; i < dynamicObjects.length; ++i) {
                    String changeType = (String) this.getModel().getValue(xBillEntry.get("changetype"), i);
                    if (ChangeTypeEnum.UPDATE.getValue().equals(changeType)) {
                        this.getView().setEnable(Boolean.FALSE, i, unEnableEntryPropertys);
                        this.getView().setEnable(Boolean.TRUE, i, enableEntryProperrtys);
                        continue;
                    }
                    if (!ChangeTypeEnum.CANCEL.getValue().equals(changeType))
                        continue;
                    this.getView().setEnable(Boolean.FALSE, i, unEnableEntryPropertys);
                    this.getView().setEnable(Boolean.FALSE, i, enableEntryProperrtys);
                }
            }
        }
    }

}