package com.config;




import com.jfinal.core.Controller;
import com.jfinal.kit.PropKit;
import com.jfinal.log.Log;


import com.jfinal.plugin.activerecord.ActiveRecordPlugin;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.DbPro;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.druid.DruidPlugin;
import com.jfinal.plugin.ehcache.CacheKit;
import com.jfinal.plugin.ehcache.CacheName;
import com.tools.JwtUtils;
import org.apache.commons.lang3.StringEscapeUtils;
import org.apache.commons.lang3.StringUtils;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;


import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 提取一些经常的代码，主要用于继承
 * @author hkc
 *
 */
public class BaseController extends Controller {
	public Log logger = Log.getLog(BaseController.class);
	public SimpleDateFormat format1 = new SimpleDateFormat("yyyy-MM-dd");
	public SimpleDateFormat format2 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
	public SimpleDateFormat format3 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	public final static String VIEW_PATH=PropKit.get("view_path");
	public final static String BASEVIEWDIR="/skin/"+VIEW_PATH+"/views/";
	//public static final int PAGESIZE = 20;//每页现实条数
	public static final int PAGESIZE = Integer.valueOf(PropKit.get("pagesize"));//每页现实条数

	public static final int CODE_AUTH=201;



	/**
	 * 将List转换为数组对象
	 * @param list
	 * @return
	 */
	public static Object[] listToArray(List<Object> list){
		return list.toArray(new Object[list.size()]);
	}

	public void success(Object o){
		Map result = new HashMap();
		result.put("code",200);
		result.put("msg","调用成功");
		result.put("data",o);
		this.renderJson(result);
	}

	public void reData(Object o){
		this.renderJson(o);
	}

	public void success(int code,String msg,Object o){
		Map result = new HashMap();
		result.put("code",code);
		result.put("msg",msg);
		result.put("data",o);
		this.renderJson(result);
	}

	public void success(int code,String msg,Object[] o,int count){
		Map result = new HashMap();
		result.put("code",code);
		result.put("msg",msg);
		result.put("count",count);
		result.put("data",o);
		this.renderJson(result);
	}

	public void success(int code,String msg){
		Map result = new HashMap();
		result.put("code",code);
		result.put("msg",msg);
		this.renderJson(result);
	}

	public void success(){
		Map result = new HashMap();
		result.put("code",200);
		result.put("msg","操作成功");
		this.renderJson(result);
	}
	public static Map successMap(){
		Map result = new HashMap();
		result.put("code",200);
		result.put("msg","操作成功");
		return result;
	}
	public void fail(int code, String msg){
		Map result = new HashMap();
		result.put("code",code);
		result.put("msg",msg);

		this.renderJson(result);
	}
	public static Map failMap(int code, String msg){
		Map result = new HashMap();
		result.put("code",code);
		result.put("msg",msg);
		return result;
	}
	public void fail(){
		Map result = new HashMap();
		result.put("code","0");
		result.put("msg","请求错误");
		this.renderJson(result);
	}
	public void fail_token(){
		Map result = new HashMap();
		result.put("code","3");
		result.put("msg","token验证错误");
		this.renderJson(result);
	}

	public Map weixinTokenFail(){
		Map result = new HashMap();
		result.put("resCode","301");
		result.put("resMsg", "权限验证失败");
		return result;
	}
	public Map weixinFail(String msg){
		Map result = new HashMap();
		result.put("resCode","-1");
		if(StringUtils.isEmpty(msg)){
			msg = "操作失败！";
		}
		result.put("resMsg", msg);
		return result;
	}
	public Map weixinSuccess(Object bean){
		Map result = new HashMap();
		result.put("resCode","200");
		result.put("resMsg", bean);
		return result;
	}


	public void formatDate(List<Record> list, SimpleDateFormat format){
		for(Record r : list){
			String[] keys = r.getColumnNames();
			for(String key : keys){
				if(r.get(key) instanceof java.util.Date){
					r.set(key, format.format(r.getDate(key)));
				}
				if(r.get(key) instanceof String){
					if(r.get(key) != null){
						r.set(key, r.getStr(key).trim());
					}

				}
			}
		}
	}


	private int getOperatorid(String token ){
		int operatorid = JwtUtils.validateJWTForUserId(token);
		if(operatorid == 0){
			fail(3,"token错误");
		}
		return operatorid;
	}

	/**
	 * 该方法用户微信端根据账号的orgid获取对应的数据源
	 * @param key
	 * @return
	 */
	public DbPro weixinDb(Object key){
		int datasourceid =0 ;
		if(key instanceof Integer){
			datasourceid = getWxDataSourceid((Integer) key);
		}else{
			datasourceid = getWxDataSourceid((String)key);
			if(datasourceid == 0 ){
				return null;
			}
		}
		return Db.use("wxdatasource"+datasourceid);
	}

	@CacheName("WXDATASOURCE")
	private int getWxDataSourceid(int orgid){
		return Db.findById("t_wx_datasource","orgid",orgid).getInt("datasourceid");
	}
	@CacheName("WXDATASOURCE")
	private int getWxDataSourceid(String openid){
		Record record = Db.findById("t_wx_openid_orgid","openid",openid);
		if(record == null){
			return 0;
		}
		int orgid = record.getInt("orgid");
		return Db.findById("t_wx_datasource","orgid",orgid).getInt("datasourceid");
	}
	/**
	 * 本地文件（图片、excel等）转换成Base64字符串
	 *
	 * @param imgPath
	 */
	public static String convertFileToBase64(String imgPath) {
		byte[] data = null;
		// 读取图片字节数组
		try {
			InputStream in = new FileInputStream(imgPath);
			//System.out.println("文件大小（字节）="+in.available());
			data = new byte[in.available()];
			in.read(data);
			in.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 对字节数组进行Base64编码，得到Base64编码的字符串
		BASE64Encoder encoder = new BASE64Encoder();
		String base64Str = encoder.encode(data);


		return base64Str;
	}


}
