package com.sunda.spmscommon;

import com.alibaba.fastjson.util.TypeUtils;

import java.lang.reflect.Array;
import java.util.*;

/**
* @Description:
* @Param: 
* @return: 
* @Author: Wayne Wu
* @Date: 2020-04-22 15:01
*/
public class ResponseResult {

    //请求结果编码
    private int code;

    //返回消息
    private String msg;

    //数据集
    private Map<String, Object> data = new HashMap<>();

    public ResponseResult(){
        super();
    }

    //返回请求成功信息
    public static ResponseResult success(){
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(200);
        responseResult.setMsg("请求成功");
        return responseResult;
    }

    //返回请求成功，及自定义信息
    public static ResponseResult success(String msg){
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(200);
        responseResult.setMsg(msg);
        return responseResult;
    }

    //返回请求失败信息
    public static ResponseResult error(){
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(100);
        responseResult.setMsg("请求失败");
        return responseResult;
    }

    //返回请求失败，及自定义信息
    public static ResponseResult error(String msg){
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(100);
        responseResult.setMsg(msg);
        return responseResult;
    }

    public static ResponseResult error(String msg, int code){
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(code);
        responseResult.setMsg(msg);
        return responseResult;
    }

    public static ResponseResult loginError(String msg){
        ResponseResult responseResult = new ResponseResult();
        responseResult.setCode(401);
        responseResult.setMsg(msg);
        return responseResult;
    }

    //返回请求追加数据信息
    public  ResponseResult add(String key, Object value) {
        this.data.put(key, value);
        return this;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public Map<String, Object> getData() {
        return data;
    }

    public <T> T getObject(String key, Class<T> clazz) {
        Object obj = this.data.get(key);
        return TypeUtils.castToJavaBean(obj, clazz);
    }

    public void setData(Map<String, Object> data) {
        this.data = data;
    }

    public List<?> getDataList(String key) {
        Object obj=this.data.get(key);
        List<?> list = new ArrayList<>();
        if (obj.getClass().isArray()) {
            list = Arrays.asList((Object[])obj);
        } else if (obj instanceof Collection) {
            list = new ArrayList<>((Collection<?>)obj);
        }
        return list;
    }

}
