package com.zjrs.zwnw.bsdb.util;

import org.mohrss.leaf.core.framework.util.CurrentUser;
import org.mohrss.leaf.core.framework.util.SecurityUtils;
import org.mohrss.leaf.core.framework.web.controller.AjaxResponse;
import com.zjrs.zwnw.bsdb.po.AbstractBaenum;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

public class AppUtils {

    /**
     * 初始化创建人, 创建时间等字段信息
     * @param po
     */
    public static void initParams(AbstractBaenum po) {
        CurrentUser cUser = SecurityUtils.getCurrentUser();
        Date date = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String cUserId = cUser.getUserid() == null ? "admin" : cUser.getUserid();
        String cUserOrgId= cUser.getOrgid() == null ? "广州华资软件" : cUser.getUserid();

        po.setBae001(cUserOrgId);
        po.setBae002(cUserId);
        po.setBae003(df.format(date));
        po.setBae004(cUserId);
        po.setBae005(df.format(date));
        po.setBae006(cUserOrgId);
    }

    /**
     * 初始化修改人, 修改时间字段信息
     * @param po
     */
    public static void updateParams(AbstractBaenum po) {
        CurrentUser cUser = SecurityUtils.getCurrentUser();
        Date date = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String cUserId = cUser.getUserid() == null ? "admin" : cUser.getUserid();
        String cUserOrgId= cUser.getOrgid() == null ? "广州华资软件" : cUser.getUserid();

        po.setBae004(cUserId);
        po.setBae005(df.format(date));
        po.setBae006(cUserOrgId);
    }

    /**
     * 获取校验的异常信息
     * @param ajaxResponse
     * @param bindingResult
     * @return
     */
    public static AjaxResponse getValidAjaxResponse(AjaxResponse ajaxResponse, BindingResult bindingResult) {
        ajaxResponse.setAppcode("1");
        ajaxResponse.setErrorMsg(AppUtils.getFieldErrorStr(bindingResult.getFieldErrors()));
        return ajaxResponse;
    }

    /**
     * 校验信息处理
     * @param fieldErrors
     * @return
     */
    public static String getFieldErrorStr(List<FieldError> fieldErrors) {
        StringBuilder errmsg = new StringBuilder();
        for(FieldError error : fieldErrors)
            errmsg.append(error.getDefaultMessage()).append(";");

        return errmsg.toString().substring(0, errmsg.length() - 1);
    }

}
