package nckd.jxccl.opmc.pm.plugin.form.result;

import kd.bos.dataentity.OperateOption;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.utils.StringUtils;
import kd.bos.entity.operate.OperateOptionConst;
import kd.bos.entity.operate.result.IOperateInfo;
import kd.bos.entity.operate.result.OperateErrorInfo;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.entity.report.ReportQueryParam;
import kd.bos.entity.validate.ErrorLevel;
import kd.bos.form.FormShowParameter;
import kd.bos.form.MessageBoxOptions;
import kd.bos.form.ShowType;
import kd.bos.form.events.AfterDoOperationEventArgs;
import kd.bos.form.events.PreOpenFormEventArgs;
import kd.bos.report.ReportList;
import kd.bos.report.ReportShowParameter;
import kd.bos.report.plugin.AbstractReportFormPlugin;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import kd.sdk.plugin.Plugin;
import nckd.jxccl.base.common.constant.FormConstant;
import nckd.jxccl.base.common.exception.ValidationException;
import nckd.jxccl.base.common.utils.StrFormatter;
import nckd.jxccl.base.entity.helper.EntityHelper;
import nckd.jxccl.opmc.pm.common.PerfManagerFormConstant;

import java.util.ArrayList;
import java.util.List;
import java.util.StringJoiner;
import java.util.stream.Stream;

/**
* 年度绩效结果明细-插件
* 实体标识：nckd_annualperfdetail
* @author W.Y.C
* @date 2025/11/15 21:51
* @version 1.0
*/
public class AnnualPerfDetailFormPlugin extends AbstractReportFormPlugin implements Plugin {

    @Override
    public void preOpenForm(PreOpenFormEventArgs e) {
        // 1. 获取表单显示参数对象
        FormShowParameter showParameter = (FormShowParameter) e.getSource();
        // 2. 设置页面标题
        showParameter.setCaption("年度绩效结果明细");
        super.preOpenForm(e);
    }

    @Override
    public void beforeQuery(ReportQueryParam queryParam) {
        ReportList reportList = this.getControl("reportlistap");
        reportList.setSelectedAll(true);
    }


    @Override
    public void afterDoOperation(AfterDoOperationEventArgs e) {
        if(e.getOperationResult() != null && e.getOperationResult().isSuccess()) {
            String operateKey = e.getOperateKey();
            if ("deemedresult".equals(operateKey)) {
                FormShowParameter showParameter = new FormShowParameter();
                showParameter.setFormId("nckd_updateresult");
                showParameter.getOpenStyle().setShowType(ShowType.Modal);
                this.getView().showForm(showParameter);
            }else if (Stream.of(PerfManagerFormConstant.ARCHIVE_OP, PerfManagerFormConstant.UNARCHIVE_OP)
                    .anyMatch(op -> op.equalsIgnoreCase(operateKey))) {
                //获取报表选中的数据
                ReportList reportList = this.getView().getControl("reportlistap");
                int[] selectedRows = reportList.getEntryState().getSelectedRows();
                if(selectedRows != null && selectedRows.length > 0){
                    List<DynamicObject> saveData = new ArrayList<>(selectedRows.length);
                    for (int rowIndex : selectedRows) {
                        // 获取指定行的数据
                        DynamicObject rowData = reportList.getReportModel().getRowData(rowIndex);
                        DynamicObject person = rowData.getDynamicObject(FormConstant.NCKD_PERSON);
                        DynamicObject dynamicObject = EntityHelper.newEntity(PerfManagerFormConstant.PERFMANAGER_ENTITYID);
                        dynamicObject.set(FormConstant.NCKD_PERSON, person);
                        saveData.add(dynamicObject);
                    }
                    OperateOption operateOption = OperateOption.create();
                    operateOption.setVariableValue("operateKey", operateKey);
                    operateOption.setVariableValue(OperateOptionConst.IGNOREWARN, true+"");
                    OperationResult result = OperationServiceHelper.executeOperate(
                            "archiveorunarchive",
                            "nckd_annualperfdetail",
                            saveData.toArray(new DynamicObject[0]),
                            operateOption
                    );
                    if (!result.isSuccess()) {
                        StringJoiner error = new StringJoiner(StrFormatter.LINE_SEPARATOR);
                        StringJoiner warningError = new StringJoiner(StrFormatter.LINE_SEPARATOR);
                        for (IOperateInfo operateInfo : result.getAllErrorOrValidateInfo()) {
                            OperateErrorInfo operateErrorInfo = (OperateErrorInfo)operateInfo;
                            if(operateErrorInfo.getLevel()  == ErrorLevel.FatalError || operateErrorInfo.getLevel() == ErrorLevel.Error){
                                error.add(operateErrorInfo.getMessage());
                            }else{
                                warningError.add(operateErrorInfo.getMessage());
                            }
                        }
                        if(StringUtils.isNotEmpty(result.getMessage())){
                            error.add(result.getMessage());
                        }
                        if(error.length() > 0){
                            error.add(warningError.toString());
                            throw new ValidationException(error.toString());
                        } else if(warningError.length() > 0){
                            this.getView().showTipNotification(warningError.toString());
                        }else{
                            throw new ValidationException(result.getMessage());
                        }
                    }else{
                        //刷新列表
                        this.getView().invokeOperation(FormConstant.REFRESH_OP);
                        this.getView().showConfirm("提示",result.getMessage(), MessageBoxOptions.OK,null,null,null,null);
                    }
                }
            }else if("printlist".equalsIgnoreCase(operateKey)){

                ReportShowParameter reportShowParameter = new ReportShowParameter();
                reportShowParameter.setFormId("nckd_printlistrpt");
                reportShowParameter.getOpenStyle().setShowType(ShowType.MainNewTabPage);
                this.getView().showForm(reportShowParameter);
            }
        }
    }
}