package com.muchinfo.mtp3century.utils;


import com.muchinfo.mtp3common.enumtype.MessageType;
import com.muchinfo.mtp3common.utils.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.Arrays;

/**
 * 响应工具类
 */
public class ResponseUtils {
    private static final Logger logger = LoggerFactory.getLogger(ResponseUtils.class);

    /**
     * 向浏览器响应一个json字符串
     *
     * @param response 响应对象
     * @param status   状态码
     * @param msgType  响应信息
     */
    public static void writeSucceed(HttpServletResponse response, int status, String msgType, String languages, String token) {
        try {
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Cache-Control", "no-cache");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            response.setStatus(status);
            byte[] bytes = JsonUtils.toString(AjaxResult.success(status, msgType, languages, token)).getBytes();
            OutputStream out = response.getOutputStream();
            out.write(bytes);
        } catch (Exception e) {
            logger.error("响应出错：" + msgType, e);
        }
    }

    public static void writeFiled(HttpServletResponse response, int status, String msgType, String languages) {
        try {
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Cache-Control", "no-cache");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            response.setStatus(status);
            byte[] bytes = JsonUtils.toString(AjaxResult.error(status, msgType, languages)).getBytes();
            OutputStream out = response.getOutputStream();
            out.write(bytes);
        } catch (Exception e) {
            logger.error("响应出错：" + msgType, e);
        }
    }

    public static void writeFiledForParameters(HttpServletResponse response, int status, String [] param, String languages) {
        try {
            response.setHeader("Access-Control-Allow-Origin", "*");
            response.setHeader("Cache-Control", "no-cache");
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            response.setStatus(status);
            byte[] bytes = JsonUtils.toString(AjaxResult.error(status, MessageType.MESSAGE_CODE_SYSTEM027.getCode(),param, languages)).getBytes();
            OutputStream out = response.getOutputStream();
            out.write(bytes);
        } catch (Exception e) {
            logger.error("响应出错：" + Arrays.toString(param), e);
        }
    }
}

