package com.uas.finance.filter;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.ui.ModelMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * controller基础类
 * 
 * @author yingp
 *
 */
public class BaseController {

	protected static final String defultCharset = "UTF-8";

	@Autowired
	protected HttpServletRequest request;

	@Autowired
	protected HttpServletResponse response;

	protected static ModelMap success() {
		return new ModelMap("success", true);
	}

	protected static ModelMap success(Object data) {
		return new ModelMap("success", true).addAttribute("content", data);
	}

	protected static ModelMap error(String errMsg) {
		return new ModelMap("error", true).addAttribute("errMsg", errMsg);
	}

	protected static ModelMap error(String errCode, String errMsg) {
		return new ModelMap("error", true).addAttribute("errCode", errCode).addAttribute("errMsg", errMsg);
	}

	/**
	 * 输出json格式
	 * 
	 * @param obj
	 * @throws IOException
	 */
	protected void printJson(Object obj) throws IOException {
		response.setStatus(HttpStatus.FORBIDDEN.value());
		response.addHeader("Content-Type", "application/json; charset=" + defultCharset);
		PrintWriter printWriter = response.getWriter();
		printWriter.append(JSON.toJSONString(obj));
		printWriter.flush();
		printWriter.close();
	}

	/**
	 * 输出流
	 * 
	 * @param fileName
	 *            文件名
	 * @param bytes
	 * @throws IOException
	 */
	protected ResponseEntity<byte[]> outputStream(String fileName, byte[] bytes) {
		HttpHeaders headers = new HttpHeaders();
		headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
		headers.setContentDispositionFormData("attachment", fileName);
		return new ResponseEntity<byte[]>(bytes, headers, HttpStatus.CREATED);
	}

}
