package cn.com.smart.form.service;

import cn.com.smart.bean.SmartResponse;
import cn.com.smart.form.bean.entity.TFormScript;
import cn.com.smart.form.helper.FormHelper;
import cn.com.smart.service.impl.MgrServiceImpl;
import com.mixsmart.utils.LoggerUtils;
import com.mixsmart.utils.StringUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 乌草坡 2019-09-10
 * @since 1.0
 */
@Service
public class FormScriptService extends MgrServiceImpl<TFormScript> {

    /**
     * 获取表单脚本对象
     * @param formId 表单ID
     * @return 返回对象
     */
    public TFormScript getFormScript(String formId) {
        Map<String, Object> param = new HashMap<>(1);
        param.put("formId", formId);
        SmartResponse<TFormScript> smartResp = super.findByParam(param);
        if(OP_SUCCESS.equals(smartResp.getResult())) {
            return smartResp.getDatas().get(0);
        }
        return null;
    }

    /**
     * 保存或更新脚本对象
     * @param script
     * @return
     */
    public SmartResponse<String> saveOrUpdate(TFormScript script) {
        boolean isEmpty = true;
        if(isScriptEmpty(script.getInitFun())) {
            script.setInitFun(null);
        } else {
            script.setInitFun(FormHelper.replaceScriptContent(script.getInitFun()));
            isEmpty = isEmpty && false;
        }
        if(isScriptEmpty(script.getSubmitBeforeFun())) {
            script.setSubmitBeforeFun(null);
        } else {
            script.setSubmitBeforeFun(FormHelper.replaceScriptContent(script.getSubmitBeforeFun()));
            isEmpty = isEmpty && false;
        }
        if(isScriptEmpty(script.getSubmitAfterFun())) {
            script.setSubmitAfterFun(null);
        } else {
            script.setSubmitAfterFun(FormHelper.replaceScriptContent(script.getSubmitAfterFun()));
            isEmpty = isEmpty && false;
        }
        SmartResponse<String> smartResp = new SmartResponse<>();
        if(isEmpty) {
            LoggerUtils.error(logger, "脚本内容为空");
            smartResp.setMsg("脚本内容为空");
            return smartResp;
        }
        if(StringUtils.isEmpty(script.getId())) {
            smartResp = super.save(script);
        } else {
            smartResp = super.update(script);
        }
        return smartResp;
    }

    /**
     * 判断脚本是否为空
     * @param content 脚本内容
     * @return 如果为空返回true；否则返回false
     */
    private boolean isScriptEmpty(String content) {
        return StringUtils.isEmpty(replaceHtmlTag(content));
    }

    /**
     * 去掉HTML标签
     * @param content 脚本内容
     * @return
     */
    private String replaceHtmlTag(String content) {
        if(StringUtils.isEmpty(content)) {
            return content;
        }
        content = content.replaceAll("<br />|<br/>|&nbsp;", "");
        return content;
    }

}
