package com.quinn.dto.res;

import java.util.LinkedHashMap;

import com.quinn.common.ExceptionCode;
import com.quinn.vo.MyPageParam;
import org.springframework.util.Assert;

public class ResponseDTO extends LinkedHashMap<String, Object> {
    public static final String ERR_CODE = "err_code";
    public static final String ERR_MSG = "err_msg";

    public ResponseDTO() {
        this(0, "OK");
    }

    public ResponseDTO(Integer errCode, String errMsg) {
        this(errCode, errMsg, System.currentTimeMillis() / 1000L);
    }

    public ResponseDTO(Integer errCode, String errMsg, Long timestamp) {
        this.addAttribute(ERR_CODE, errCode);
        this.addAttribute(ERR_MSG, errMsg);
        this.addAttribute("timestamp", timestamp);
    }

    public ResponseDTO(ExceptionCode exceptionCode) {
        this(exceptionCode.code, exceptionCode.msg);
    }

    public ResponseDTO(Integer errCode, String errMsg, String attrName, Object attrValue) {
        this(errCode, errMsg);
        this.addAttribute(attrName, attrValue);
    }

    public static ResponseDTO ok() {
        return new ResponseDTO();
    }

    public static ResponseDTO ok(String msg) {
        ResponseDTO ret = ok();
        ret.setErrorMsg(msg);
        return ret;
    }

    public ResponseDTO addAttribute(String attrName, Object attrValue) {
        Assert.notNull(attrName, "属性名称不能为空");
        this.put(attrName, attrValue);
        return this;
    }

    public ResponseDTO setPage(MyPageParam pagination) {
        this.addAttribute("page", pagination);
        return this;
    }

    public ResponseDTO setData(Object obj){
        this.addAttribute("data",obj);
        return this;
    }

    public void setExceptionCode(ExceptionCode exceptionCode) {
        this.addAttribute("err_code", exceptionCode.code);
        this.addAttribute("err_msg", exceptionCode.msg);
    }

    public void setErrorCode(Integer errCode) {
        this.addAttribute("err_code", errCode);
    }

    public void setErrorMsg(String errMsg) {
        this.addAttribute("err_msg", errMsg);
    }
}
