package com.bcxin.ins.weixin.util;

import com.alibaba.fastjson.JSON;
import com.bcxin.ins.core.util.SessionUtil;
import com.bcxin.ins.vo.ClientUserVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by Apple on 2017/5/24.
 */
public class CTLUtil {
    public static final String LACK_P_MSG="必要参数确实";
    private static Logger log = LoggerFactory.getLogger("");

    public static Map<Object,Object> initWX(HttpServletRequest request, Map<Object,Object> params){
        //TODO 从缓存中获取参数
        ClientUserVo userVo  = (ClientUserVo)request.getSession().getAttribute("wxUserVo");
        params.put("system_params_login_ip", request.getRemoteAddr());
        if(userVo!=null ) params.put("system_params_user_id", userVo.getOid()); //在拦截器中设置的参数
        if(userVo!=null) params.put("system_params_login_name", userVo.getLogin_name()); //在拦截器中设置的参数
        //bootstrap 分页
        Object limit = params.get("limit");
        Object offset = params.get("offset");
        if(limit!=null && offset!=null){
            params.put("offset", Integer.valueOf(String.valueOf(offset)));
            params.put("limit", Integer.valueOf(String.valueOf(limit)));
        }
        return params;

    }

    /**
     * 保护必要的参数，不能为空
     * @param p
     * @param key
     */
    public static boolean pNotNull(Map<Object,Object> p , String ...key ){
        for (String k : key) {
            if(p.get(k)==null) return false;
        }
        return true;
    }
    /**
     * 传递json给客户端
     */
    public static void out(Object o, HttpServletResponse resp ){
        out(o,resp,"yyyy-MM-dd HH:mm:ss");
    }
    public static String toJSONDate(Object o ){
        return JSON.toJSONStringWithDateFormat(o, "yyyy-MM-dd HH:mm:ss");
    }
    public static String toJSONDateShort(Object o ){
        return JSON.toJSONStringWithDateFormat(o, "yyyy-MM-dd");
    } 

    public static void out(Object o, HttpServletResponse resp,String format){
        resp.setContentType("application/json;charset=UTF-8");
        PrintWriter pw =null;
        try {
            pw = resp.getWriter();
            String json = JSON.toJSONStringWithDateFormat(o, format);
            String s = json.replaceAll("\n","").replace("\t", "");
            pw.write(s);
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            pw.close();
        }
    }
    public static void out2(Object o, HttpServletResponse resp){
        String format = "yyyy-MM-dd HH:mm:ss";
//        resp.setContentType("text/html;charset=UTF-8");
        resp.setHeader("Content-Type","text/html;charset=UTF-8"); //跨域
        PrintWriter pw =null;
        try {
            pw = resp.getWriter();
            String json = JSON.toJSONStringWithDateFormat(o, format);
            String s = json.replaceAll("\n","").replace("\t", "");
            pw.write(s);
        } catch (IOException e) {
            e.printStackTrace();
        }finally{
            pw.close();
        }
    }

    /**
     * 传递json给客户端
     */
    public static void out(byte[] b, HttpServletResponse resp, String file ){
        if(b == null) return;
        resp.setHeader("Content-Type","image/jped");//设置响应的媒体类型，这样浏览器会识别出响应的是图片
        //resp.setHeader("Content-Disposition", "attachment; filename="+file+".jpg");
        // 以下关闭输入流！
        OutputStream out = null;
        try {
            out = resp.getOutputStream();
            out.write(b);
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 功能：判断字符串是否为日期格式
     */
    private static boolean isDate(String strDate) {
        if(strDate==null) return false;
        Pattern pattern = Pattern
                .compile("^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s(((0?[0-9])|([1-2][0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$");
        Matcher m = pattern.matcher(strDate);
        return m.matches();
    }

    /**
     * 校验是否为日期函数
     * @author chentj
     * @date  2016年3月10日 下午4:49:00
     */
    public static boolean isValidDate(Object string) {
        String str = String.valueOf(string);

        if(str.length()!=14) return false;

        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        try { // 设置lenient为false. 否则SimpleDateFormat会比较宽松地验证日期，比如2007/02/29会被接受，并转换成2007/03/01
            format.setLenient(false);
            format.parse(str);
        } catch (Exception e) {
            return false;
        }
        return true;
    }

    /**
     * 输入blob，输出流
     * @param blob
     */
    public static void outBlob(HttpServletResponse resp, byte[] blob) {
        InputStream in=null;
        OutputStream op = null;
        try {
            op = resp.getOutputStream();
             in = new ByteArrayInputStream(blob);
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = in.read(buf, 0, 1024)) != -1) {
                op.write(buf, 0, len);
            }
            op.close();
        }catch (Exception e) {
            log.error("输出大对象错误",e);
        }
    }

    /** 如果是空串或者是null都返回为空*/
    public static String str(String str){
        return str==null?null
                :("".equals(str.trim())?null
                :str.trim());
    }

    /** 如果是空串或者是null都返回为空*/
    public static String str(Object str){
        return str==null?null
                :("".equals(String.valueOf(str).trim())?null
                :String.valueOf(str).trim());
    }

    /** 校验日期*/
    public static String datestr(String str){
        String s = str==null?null
                :("".equals(str.trim())?null
                :str);
        if(isDate(s)){
            return s;
        }else{
            return null;
        }

    }


}
