package com.yd.util.config;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.Properties;

import com.yd.Application;
import com.yd.util.SpringContextUtil;

public class ZHBErrorConfig {
	
	 /**
     * 获取最惠比平台的错误信息
     * @param zhbErrorCode	错误编码，如果传入insurerId，则为第三方的错误编码，相反，则为自定义的错误编码
     * @return	zhbErrorMessage
     */
    public static String getErrorInfo(String zhbErrorCode){
    	return SpringContextUtil.getMessage(zhbErrorCode);
    }
    
    /**
     * 获取最惠比平台的错误信息
     * @param zhbErrorCode	错误编码，如果传入insurerId，则为第三方的错误编码，相反，则为自定义的错误编码
     * @param params	参数信息
     * @return	zhbErrorMessage
     */
    public static String getErrorInfo(String zhbErrorCode,String[] params){
		String zhbErrorMessage = null;
		zhbErrorMessage = SpringContextUtil.getMessage(zhbErrorCode);
		if(!isNullOrBlank(zhbErrorMessage)){
			if(params != null && params.length > 0){
				for (int i = 0; i < params.length; i++) {
					zhbErrorMessage = zhbErrorMessage.replace("{"+i+"}", params[i]);
				}
			}
		}
    	return zhbErrorMessage;
    }
    
    /**
     * 获取最惠比平台的错误信息
     * @param zhbErrorCode	错误编码，如果传入insurerId，则为第三方的错误编码，相反，则为自定义的错误编码
     * @param insurerErrorMessage	错误信息，为第三方平台的错误信息，
     * @return	zhbErrorMessage
     */
    public static String getErrorInfo(Long insurerId,String insurerCode,String insurerErrorMessage){
		String zhbErrorMessage = null;
		String zhbErrorCode = null;
		if(insurerId != null && !isNullOrBlank(insurerCode)){
			zhbErrorCode = getErrorCode(insurerId, insurerCode);
			zhbErrorMessage = SpringContextUtil.getMessage(zhbErrorCode);
			if(!isNullOrBlank(zhbErrorMessage)){
				if("EQUAL".equals(zhbErrorMessage)){
					return insurerErrorMessage;
				}else if(zhbErrorMessage.contains("}{")){//保险公司错误
    				String[] errorMessageInfoArr = zhbErrorMessage.split("\\}\\{");
    				zhbErrorMessage = errorMessageInfoArr[1];	
    			}
    		}else{
    			return insurerErrorMessage;
    		}
		}
    	return zhbErrorMessage;
    }

    /**
     * 获取最惠比平台的错误信息
     * @param zhbErrorCode	错误编码，如果传入insurerId，则为第三方的错误编码，相反，则为自定义的错误编码
     * @param insurerErrorMessage	错误信息，为第三方平台的错误信息，非第三方平台，传null
     * @param params	参数信息
     * @return	zhbErrorMessage
     */
    public static String getErrorInfo(String zhbErrorCode,String insurerErrorMessage,String[] params){
		String zhbErrorMessage = null;
    	if(!isNullOrBlank(zhbErrorCode)){
    		zhbErrorMessage = readProperties("zhb-error.properties",zhbErrorCode);
    		if(!isNullOrBlank(zhbErrorMessage)){
    			if(zhbErrorMessage.contains("}{")){//保险公司错误
    				String[] errorMessageInfoArr = zhbErrorMessage.split("\\}\\{");
    				zhbErrorMessage = errorMessageInfoArr[1];
    				if("EQUAL".equals(zhbErrorMessage)){
    					zhbErrorMessage = insurerErrorMessage;
    				}
    			}else{//平台内部错误
    				if(params != null && params.length > 0){
        				for (int i = 0; i < params.length; i++) {
        					zhbErrorMessage = zhbErrorMessage.replace("{"+i+"}", params[i]);
        				}
        			}
    			}
    		}else{
    			if(!isNullOrBlank(insurerErrorMessage)){
    				zhbErrorMessage = ZHBErrorConfig.getErrorInfo("810036");
//        			writeProperties("zhb-error.properties",zhbErrorCode,insurerErrorMessage+"}{"+zhbErrorMessage);
    			}
    		}
    	}else{
    		try {
    			String [] paramss = {"zhbErrorCode"};
				throw new Exception(ZHBErrorConfig.getErrorInfo("610001", paramss));
			} catch (Exception e) {
				e.printStackTrace();
			}
    	}
    	return zhbErrorMessage;
    }
   
	/**
	 * 写properties文件
	 * @param fileName
	 * @param key
	 * @param value
	 * @throws Exception 
	 */
	@SuppressWarnings("unused")
	private static void writeProperties(String fileName,String key,String value){
		FileInputStream fis = null;
		String file = null;
		BufferedReader bf = null;
		FileOutputStream fos = null;
		BufferedWriter bw = null;
		Properties properties = new Properties();
		if(!isNullOrBlank(fileName)){
			file = Application.class.getClassLoader().getResource(fileName).getPath();
			try {
				fis = new FileInputStream(file);
				bf = new BufferedReader(new InputStreamReader(fis,"UTF-8"));
				properties.load(bf);
				properties.setProperty(key, value);
				fos = new FileOutputStream(file);
				bw = new BufferedWriter(new OutputStreamWriter(fos,"UTF-8"));
				properties.store(bw, "update");
			} catch (Exception e) {
				e.printStackTrace();
			}finally {
				if(bw != null){
					try {
						bw.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if(bf != null){
					try {
						bf.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if(fis != null){
					try {
						fis.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if(fos!= null){
					try {
						fos.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}else{
			try {
				String [] params = {"fileName"};
				throw new Exception(ZHBErrorConfig.getErrorInfo("610001", params));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	
	/**
	 * 读取properties文件
	 * @param fileName	文件名 （目录为{src\main\resources\fileName}）
	 * @param zhbErrorCode	properties的key值
	 * @return	properties的value值
	 * @throws Exception 
	 */
	private static String readProperties(String fileName,String zhbErrorCode){
		String errorMessage = null;
		FileInputStream fis = null;
		Properties properties = null;
		BufferedReader bf= null;
		String file = null;
		if(!isNullOrBlank(fileName)){
			file = Application.class.getClassLoader().getResource(fileName).getPath();
			try {
				properties = new Properties();
				fis = new FileInputStream(file);
				bf = new BufferedReader(new InputStreamReader(fis,"UTF-8"));
				properties.load(bf);
				errorMessage = properties.getProperty(zhbErrorCode);
			} catch (Exception e) {
				e.printStackTrace();
			}finally{
				if(properties != null){
					properties = null;
				}
				if(fis != null){
					try {
						fis.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if(bf != null){
					try {
						bf.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		}else{
			try {
				String [] params = {"fileName"};
				throw new Exception(ZHBErrorConfig.getErrorInfo("610001", params));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return errorMessage;
	}
	/**
	 * 生成最惠比的errorCode
	 * @param insurerId 保险公司id，微信999，支付宝998
	 * @param insurerCode 保险公errorCode
	 * @return 最惠比平台 errorCode
	 */
    private static String getErrorCode(Long insurerId, String insurerCode) {
		String zhbErrorCode = null;
		if (insurerId<10) {
			zhbErrorCode = "900"+insurerId;
		}else if(insurerId<100){
			zhbErrorCode = "90"+insurerId;
		}else {
			zhbErrorCode = "9"+insurerId;
		}
		zhbErrorCode = zhbErrorCode+insurerCode;
		return zhbErrorCode;
	}
	
	private static boolean isNullOrBlank(String source){
		boolean result = false;
		if(source == null){
			result = true;
		}else if("".equals(source.trim())){
			result = true;
		}
		return result ;
	}
}
