package com.wx.application.base;


import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.i18n.LocaleContextHolder;

import java.util.Locale;

/**
 * @author zj
 * @description : 控制器的基类,抽象方法,标准控制器有crud4个方法 ---------------------------------
 * @since 2017-11-14
 */
public abstract class BaseController {

    private static MessageSource messageSource;

    @Autowired
    public void setMessageSource(MessageSource messageSource) {
        BaseController.messageSource = messageSource;
    }

    public static ResponseData success() {
        return success(null);
    }

    public static ResponseData success(Object object) {
        ResponseData rData = new ResponseData();
        rData.setCode(ErrorCodeEnum.SUCCESS.toString());
        rData.setMsg(getMsg(rData.getCode()));
        rData.setData(object);
        return rData;
    }

    public static ResponseData success(Object object, String msg) {
        ResponseData rData = new ResponseData();
        rData.setCode(ErrorCodeEnum.SUCCESS.toString());
        rData.setMsg(getMsg(rData.getCode()));
        rData.setData(msg);
        return rData;
    }

    public static ResponseData error(ErrorCodeEnum errorCodeEnum) {
        return error(errorCodeEnum, null);
    }

    public static ResponseData error(ErrorCodeEnum errorCodeEnum, Object object) {
        ResponseData rData = new ResponseData();
        rData.setCode(errorCodeEnum.toString());
        rData.setMsg(getMsg(rData.getCode()));
        rData.setData(object);
        return rData;
    }

    protected static String getMsg(String code) {
        Locale locale = LocaleContextHolder.getLocale();
        try {
            return messageSource.getMessage(code, null, locale);
        } catch (NoSuchMessageException ex) {
            return "";
        }
    }
}
