package nckd.jxccl.base.common.utils;

import kd.bos.dataentity.resource.ResManager;
import kd.bos.dataentity.serialization.DataEntitySerializer;
import kd.bos.dataentity.serialization.DataEntitySerializerOption;
import kd.bos.entity.operate.result.IOperateInfo;
import kd.bos.entity.operate.result.OperateErrorInfo;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.form.FormShowParameter;
import kd.bos.form.IFormView;
import kd.bos.form.IPageCache;
import kd.bos.form.ShowType;
import kd.bos.mvc.SessionManager;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.StringJoiner;

/**
 * 操作执行结果显示工具类
 * 用于生成操作执行结果的表单显示参数，支持显示操作成功和失败的信息
 * 当错误项较多时可以使用表格方式显示，避免信息被截断
 *
 * @author W.Y.C
 * @date 2025/11/28 14:49
 * @version 1.0
 */
public class ShowOperExecuteResult {

    public static FormShowParameter getOperResultForm(String operateName, IFormView formView, OperationResult operationResult) {
        String parentPageId = formView.getFormShowParameter().getPageId();
        IFormView parentView = SessionManager.getCurrent().getViewNoPlugin(parentPageId);
        IPageCache pageCache = (IPageCache) parentView.getService(IPageCache.class);
        return getOperResultForm(operateName, pageCache, operationResult);
    }

    public static FormShowParameter getOperResultForm(String operateName, IFormView formView,IPageCache pageCache, OperationResult operationResult) {
        String parentPageId = formView.getFormShowParameter().getPageId();
        IFormView parentView = SessionManager.getCurrent().getViewNoPlugin(parentPageId);
        return getOperResultForm(operateName, pageCache, operationResult);
    }
    /**
     * 获取操作结果表单显示参数（重载方法1）
     * 
     * @param operateName 操作名称
     * @param pageCache 页面缓存对象
     * @param operationResult 操作结果对象
     * @return 表单显示参数
     */
    public static FormShowParameter getOperResultForm(String operateName,  IPageCache pageCache, OperationResult operationResult) {
        return getOperResultForm(null, operateName, pageCache, operationResult);
    }

    /**
     * 获取操作结果表单显示参数（核心方法）
     * 构造并返回一个包含操作执行结果信息的表单显示参数对象
     * 
     * @param title 自定义标题，如果为空则根据成功/失败数量自动生成标题
     * @param operateName 操作名称
     * @param pageCache 页面缓存对象，用于存储操作结果序列化后的数据
     * @param operationResult 操作结果对象，包含详细的成功/失败信息
     * @return 表单显示参数对象
     */
    public static FormShowParameter getOperResultForm(String title, String operateName,  IPageCache pageCache, OperationResult operationResult) {

        // 收集所有错误或验证信息
        StringJoiner errorMsgJoiner = new StringJoiner(StrFormatter.LINE_SEPARATOR);

        // 构建自定义参数
        Map<String, Object> customParam = new HashMap(2);
        //成功的记录
        Map<String, String> customData = operationResult.getCustomData();
        if(customData != null) {
            //成功的记录
            Map<Object, Object> successMap = new HashMap<>();
            for (Object successPkId : operationResult.getSuccessPkIds()) {
                successMap.put(successPkId, customData.get(successPkId.toString()));
            }

            // 如果有成功记录映射关系，则添加到参数中
            if (!successMap.isEmpty()) {
                // 成功消息
                customParam.put("pkNumbers", successMap);
                for (Map.Entry<Object, Object> objectObjectEntry : successMap.entrySet()) {
                    Object key = objectObjectEntry.getKey();
                    Object value = objectObjectEntry.getValue();
                    String tip = value != null ? ConvertUtil.toStr(value) : ConvertUtil.toStr(key);
                    errorMsgJoiner.add(String.format(ResManager.loadKDString("%s：执行成功。", "ShowOperationResultPlugin_2", "bos-designer-plugin", new Object[0]), tip));
                }
            }
        }

        if(operationResult.getAllErrorOrValidateInfo() != null && !operationResult.getAllErrorOrValidateInfo().isEmpty()){
            Iterator<IOperateInfo> iterator = operationResult.getAllErrorOrValidateInfo().iterator();
            while (iterator.hasNext()) {
                IOperateInfo operateInfo = iterator.next();
                if(operateInfo instanceof OperateErrorInfo){
                    OperateErrorInfo operateErrorInfo = (OperateErrorInfo) operateInfo;
                    int dataEntityIndex = operateErrorInfo.getDataEntityIndex();
                    String prefix = operationResult.getCustomData().get("DataEntityIndex_" + dataEntityIndex);
                    if(StringUtils.isNotBlank(prefix)){
                        operateErrorInfo.setMessage(prefix + operateErrorInfo.getMessage());
                    }
                }
                errorMsgJoiner.add(operateInfo.getMessage());
            }
        }
        String errorMsg = errorMsgJoiner.toString();
        // 如果没有具体的错误详情，则使用操作结果中的通用消息
        if (StringUtils.isBlank(errorMsg)) {
            errorMsg = operationResult.getMessage();
        }

        // 将操作结果序列化后存入页面缓存
        DataEntitySerializerOption option = new DataEntitySerializerOption();
        option.setIncludeComplexProperty(true);
        pageCache.put("operationresult", DataEntitySerializer.serializerToString(operationResult, option));
        

        customParam.put("operateName", operateName);
        
        // 设置标题：如果有自定义标题则使用，否则根据成功/失败数量自动生成
        if (StringUtils.isNotBlank(title)) {
            customParam.put("title", title);
        } else {
            int billCount = operationResult.getBillCount();
            int successCount = operationResult.getSuccessPkIds().size();
            int validError = billCount - successCount;
            customParam.put("title", ResManager.loadKDString("成功数量：%1$s，失败数量：%2$s", "AbstractFormView_8", "bos-form-metadata", new Object[]{successCount, validError}));
        }
        // 添加其他参数
        customParam.put("hasMore", true);
        customParam.put("errorMsg", errorMsg);
        

        
        // 构造表单显示参数对象
        FormShowParameter parameter = new FormShowParameter();
        parameter.setFormId("bos_operationresult"); // 设置表单ID
        parameter.getOpenStyle().setShowType(ShowType.Modal); // 设置显示类型
        parameter.getCustomParams().putAll(customParam); // 添加自定义参数
        parameter.setShowTitle(false); // 不显示默认标题
        
        return parameter;
    }

}