package yem.base.common.module.iscb.form;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import kd.bos.form.IFormView;
import kd.bos.form.control.CodeEdit;
import kd.bos.form.plugin.AbstractFormPlugin;
import yem.base.common.utils.YEM;

import java.math.BigDecimal;
import java.util.EventObject;
import java.util.LinkedHashMap;

/**
 * 接口日志
 *
 * @author longh
 * @description 表单插件
 * @date 2023年9月7日
 */
public class ApiLogFormPlugin extends AbstractFormPlugin {

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

    private void initData() {
        IFormView view = this.getView();
        String yem_source_data = (String) this.getModel().getValue("yem_source_data_tag");
        String yem_target_data = (String) this.getModel().getValue("yem_target_data_tag");
        CodeEdit yem_sourceedit = view.getControl("yem_sourceedit");
        CodeEdit yem_targetedit = view.getControl("yem_targetedit");
        yem_sourceedit.setText(getPrettyTag(yem_source_data));
        yem_targetedit.setText(getPrettyTag(yem_target_data));
    }

    private String getPrettyTag(String encryptData) {
        String str;
        Object obj = null;
        try {
            if (encryptData != null) {
                if (encryptData.startsWith("{")) {
                    obj = JSONObject.parseObject(encryptData, LinkedHashMap.class, new Feature[]{Feature.OrderedField});
                } else if (encryptData.startsWith("[")) {
                    obj = JSONObject.parseArray(encryptData);
                }
            }
        } catch (Exception e) {

        } finally {
            if (obj != null) {
                str = JSON.toJSONString(obj, new SerializerFeature[]{SerializerFeature.PrettyFormat, SerializerFeature.WriteMapNullValue});
            } else {
                str = s(encryptData);
            }
        }
        return subStringAndConcatTip(str);
    }

    private String subStringAndConcatTip(String param) {
        if (YEM.isNotEmpty(param) && param.length() > 102400) {
            param = param.substring(0, 102400);
            StringBuilder sb = new StringBuilder();
            // 请下载日志用文本编辑器查看
            sb.append(param).append("\n\n\n\n请注意：因内容太长，后续部分被自动截断，请联系管理员去后台查看...");
            return sb.toString();
        }
        return param;
    }

    private String s(Object o) {
        if (o == null) {
            return null;
        } else if (o instanceof BigDecimal) {
            return ((BigDecimal) o).toPlainString();
        } else {
            String s = o.toString();
            if (s == null) {
                return null;
            } else {
                s = s.trim();
                return s.length() == 0 ? null : s;
            }
        }
    }

}
