package cn.com.smart.form.controller;

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.form.service.FormScriptService;
import cn.com.smart.web.bean.UserInfo;
import com.mixsmart.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

/**
 * @author 乌草坡 2019-09-10
 * @since 1.0
 */
@Controller
@RequestMapping("/form/script")
public class FormScriptController extends BaseFormController {

    private static final String VIEW_DIR = BASE_FORM_VIEW_DIR+"script/";

    @Autowired
    private FormScriptService formScriptServ;

    /**
     * 编写JS脚本
     * @param request HTTP请求对象
     * @param formId 表单ID
     * @return 返回视图
     */
    @RequestMapping("/codeJs")
    public ModelAndView codeJs(HttpServletRequest request, String formId) {
        ModelAndView modelView = new ModelAndView();
        if(StringUtils.isNotEmpty(formId)) {
            TFormScript script = formScriptServ.getFormScript(formId);
            if (null != script) {
                script.setInitFun(FormHelper.restoreScriptContent(script.getInitFun()));
                script.setSubmitBeforeFun(FormHelper.restoreScriptContent(script.getSubmitBeforeFun()));
                script.setSubmitAfterFun(FormHelper.restoreScriptContent(script.getSubmitAfterFun()));
                modelView.getModelMap().put("objBean", script);
            }
        }
        modelView.setViewName(VIEW_DIR + "codeJs");
        return modelView;
    }

    /**
     * 保存表单js代码
     * @param request
     * @param script 脚本实体类
     * @return
     */
    @RequestMapping(value = "/saveJs", method = RequestMethod.POST)
    @ResponseBody
    public SmartResponse<String> saveJs(HttpServletRequest request, TFormScript script) {
        SmartResponse smartResp = new SmartResponse();
        if(StringUtils.isEmpty(script.getFormId())) {
            smartResp.setMsg("formId参数不能为空");
            return smartResp;
        }
        UserInfo userInfo = getUserInfoFromSession(request);
        if(StringUtils.isEmpty(script.getId())) {
            script.setUserId(userInfo.getId());
        }
        smartResp = formScriptServ.saveOrUpdate(script);
        return smartResp;
    }

}
