package cn.com.smart.form.helper;

import cn.com.smart.form.bean.entity.TFormScript;
import com.mixsmart.utils.StringUtils;

/**
 * @author 乌草坡 2019-09-10
 * @since 1.0
 */
public class FormHelper {

    /**
     * 脚本回车替换标识
     */
    public static final String SCRIPT_ENTER_REPLACE_FLAG = "##";

    /**
     * 脚本回车标识
     */
    public static final String SCRIPT_ENTER_FLAG = "\n";

    public static final String SCRIPT_ENTER_LINE_FLAG = "\r\n";

    /**
     * 替换脚本内容（主要是替换回车内容）
     * @param content 脚本内容
     * @return 返回替换后的内容
     */
    public static String replaceScriptContent(String content) {
        if(StringUtils.isNotEmpty(content)) {
            content = content.replace(SCRIPT_ENTER_LINE_FLAG, SCRIPT_ENTER_REPLACE_FLAG);
            content = content.replace(SCRIPT_ENTER_FLAG, SCRIPT_ENTER_REPLACE_FLAG);
        }
        return content;
    }

    /**
     * 还原替换的脚本内容
     * @param content 脚本内容
     * @return 返回还原后的内容
     */
    public static String restoreScriptContent(String content) {
        if(StringUtils.isNotEmpty(content)) {
            content = content.replace(SCRIPT_ENTER_REPLACE_FLAG, SCRIPT_ENTER_FLAG);
        }
        return content;
    }

    /**
     * 去掉脚本的注释
     * @param content 脚本内容
     * @return 返回替换后的内容
     */
    public static String removeScriptComments(String content) {
        if(StringUtils.isNotEmpty(content)) {
            content = content.replaceAll("\\/\\*\\*(.*?)\\*\\*\\/", "");
        }
        return content;
    }

    /**
     * 获取所有函数
     * @param formScript
     * @return
     */
    public static String getAllFun(TFormScript formScript) {
        if(null == formScript) {
            return null;
        }
        StringBuilder scriptBuilder = new StringBuilder();
        if(StringUtils.isNotEmpty(formScript.getInitFun())) {
            scriptBuilder.append("function formLoaded(){\n")
                    .append(FormHelper.restoreScriptContent(formScript.getInitFun()))
                    .append("\n }");
        }
        if(StringUtils.isNotEmpty(formScript.getSubmitBeforeFun())) {
            if(scriptBuilder.length() > 0) {
                scriptBuilder.append("\n");
            }
            scriptBuilder.append("function beforeFormSubmit(param){\n")
                    .append(FormHelper.restoreScriptContent(formScript.getSubmitBeforeFun()))
                    .append("\n }");
        }
        if(StringUtils.isNotEmpty(formScript.getSubmitAfterFun())) {
            if(scriptBuilder.length() > 0) {
                scriptBuilder.append("\n");
            }
            scriptBuilder.append("function afterFormSubmit(response,param){\n")
                    .append(FormHelper.restoreScriptContent(formScript.getSubmitAfterFun()))
                    .append("\n }");
        }
        return scriptBuilder.toString();
    }

}
