package com.yifu.cloud.plus.v1.check.utils;

import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.yifu.cloud.plus.v1.check.constant.ChecksConstants;
import com.yifu.cloud.plus.v1.check.entity.TCheckBankNo;
import com.yifu.cloud.plus.v1.check.entity.TCheckIdCard;
import com.yifu.cloud.plus.v1.check.entity.TCheckMobile;
import com.yifu.cloud.plus.v1.yifu.common.core.constant.CommonConstants;
import com.yifu.cloud.plus.v1.yifu.common.core.util.Common;
import com.yifu.cloud.plus.v1.yifu.common.core.util.R;

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

/**
 * @author hgw2
 * @description 测试身份证
 * @date 2022/5/7
 */

public class ChecksUtil {


     private static final String APP_ID = "oi0mucL4";

     private static final String APP_KEY_IDCARD = "s4lW5JRA";
	 private static final String API_URL = "https://api.253.com/open/idcard/id-card-auth";
	 private static final String API_URL_MOBILE = "https://api.253.com/open/unn/batch-ucheck";
	 private static final String API_URL_BANK_NO ="https://api.253.com/open/bankcard/card-auth";
	 private static final String API_URL_BANK_NO_TWO ="https://api.253.com/open/bankcard/card-two-auth";
	 private static final String API_URL_BANK_NO_THREE ="https://api.253.com/open/bankcard/card-three-auth";
	 private static JsonParser jsonParser = new JsonParser();

     public static void checkIdCard(TCheckIdCard checkIdCard, boolean canCheck) {

          if (canCheck) {
               // 1.调用身份信息校验api
               checkIdCardMethod(checkIdCard);
          } else {
               //checkIdCard.setIsTrue(CommonConstants.ZERO_INT);
               //checkIdCard.setReason(ChecksConstants.NACOS_CHECK_CONFIG_ERROR);
			   checkIdCard.setIsTrue(CommonConstants.ONE_INT);
			   checkIdCard.setReason(ChecksConstants.CHECK_CONFIG_ACCESS);
          }
     }
	/**
	 * @Author fxj
	 * @Description 手机号码状态检测
	 * @Date 17:50 2022/6/20
	 * @param  mobiles  检测手机号，多个手机号码用英文半角逗号隔开，仅支持国内号码   一次请求最多五十个号码
	 **/
	public static R<Map<String,TCheckMobile>> checkMobile(String mobiles, boolean canCheck) {
		Map<String,TCheckMobile>  checkMobiles = new HashMap<>();
		if (canCheck) {
			// 1.调用手机信息校验api
			return checkMobileMethod(mobiles,checkMobiles);
		} else {
			TCheckMobile checkMobile;
			List<String> mobileList = Common.initStrToList(mobiles,CommonConstants.COMMA_STRING);
			Map<String,TCheckMobile> resMap = new HashMap<>();
			if (Common.isNotNull(mobileList)){
				for (String m:mobileList){
					checkMobile = new TCheckMobile();
					checkMobile.setMobile(m);
					checkMobile.setStatus(CommonConstants.ONE_STRING);
					checkMobile.setType(CommonConstants.ONE_STRING);
					checkMobile.setMessage(ChecksConstants.CHECK_CONFIG_ACCESS);
					resMap.put(m,checkMobile);
				}
			}
			return R.ok(resMap);
		}
	}
	/**
	 * @Author fxj
	 * @Description 银行卡四要素标准版 校验
	 * @Date 17:50 2022/6/20
	 * @param  name	姓名	是	[string]
	 * @param  cardNo	银行卡号，限单个	是	[string]
	 **/
	public static R<TCheckBankNo> checkBankNoTwo(String name, String cardNo, boolean canCheck) {
		if (canCheck) {
			// 1.调用银行卡信息校验api
			return checkBankNoTwoMethod(name,cardNo);
		} else {
			TCheckBankNo checkBankNo = new TCheckBankNo();
			checkBankNo.setBankNo(cardNo);
			checkBankNo.setName(name);
			checkBankNo.setMessage(ChecksConstants.CHECK_CONFIG_ACCESS);
			checkBankNo.setResult("01");
			checkBankNo.setType(CommonConstants.ONE_STRING);
			checkBankNo.setRemark(ChecksConstants.CHECK_CONFIG_ACCESS);
			return R.ok(checkBankNo);
		}
	}
	/**
	 * @Author fxj
	 * @Description 银行卡四要素标准版 校验
	 * @Date 17:50 2022/6/20
	 * @param  name	姓名	是	[string]
	 * @param  cardNo	银行卡号，限单个	是	[string]
	 **/
	public static R<TCheckBankNo> checkBankNoThree(String name, String cardNo, String idNum, boolean canCheck) {
		if (canCheck) {
			// 1.调用银行卡信息校验api
			return checkBankNoThreeMethod(name,cardNo,idNum);
		} else {
			TCheckBankNo checkBankNo = new TCheckBankNo();
			checkBankNo.setBankNo(cardNo);
			checkBankNo.setName(name);
			checkBankNo.setIdNum(idNum);
			checkBankNo.setMessage(ChecksConstants.CHECK_CONFIG_ACCESS);
			checkBankNo.setResult("01");
			checkBankNo.setType(CommonConstants.ONE_STRING);
			checkBankNo.setRemark(ChecksConstants.CHECK_CONFIG_ACCESS);
			return R.ok(checkBankNo);
		}
	}
	public static R<TCheckBankNo> checkBankNoTwoMethod(String name, String cardNo) {
		final JsonObject jsonObject = ChecksUtil.invokeBankNoTwoAuth(name,cardNo);
		TCheckBankNo checkBankNo = new TCheckBankNo();
		// 2.处理返回结果
		if (jsonObject != null) {
			//响应code码。200000：成功，其他失败
			String code = jsonObject.get(ChecksConstants.CODE).getAsString();
			if (ChecksConstants.CODE_200000.equals(code) && jsonObject.get(ChecksConstants.DATA) != null) {
				// 调用身份信息校验成功
				// 解析结果数据，进行业务处理
				// 校验状态码  200000：成功，其他失败
				JsonObject resJson = jsonObject.get(ChecksConstants.DATA).getAsJsonObject();
				String message = jsonObject.get(ChecksConstants.MESSAGE).getAsString();
				if (Common.isNotNull(resJson)){
					checkBankNo.setBankNo(cardNo);
					checkBankNo.setBankName(getJsonElementValue(resJson.getAsJsonObject().get("bankName")));
					checkBankNo.setCardCategory(getJsonElementValue(resJson.getAsJsonObject().get("cardCategory")));
					checkBankNo.setCardType(getJsonElementValue(resJson.getAsJsonObject().get("cardType")));
					checkBankNo.setResult(getJsonElementValue(resJson.getAsJsonObject().get(ChecksConstants.RESULT)));
					checkBankNo.setMessage(message);
					checkBankNo.setRemark(getJsonElementValue(resJson.getAsJsonObject().get(ChecksConstants.REMARK)));
					checkBankNo.setType(CommonConstants.ONE_STRING);
					checkBankNo.setName(name);
				}
			} else {
				// 记录错误日志，正式项目中请换成log打印
				return R.failed("银行卡号校验失败:"+jsonObject.get(ChecksConstants.MESSAGE).getAsString());
			}
		} else {
			return R.failed(ChecksConstants.NO_DATA_RESULT);
		}
		return R.ok(checkBankNo);
	}

	private static R<TCheckBankNo> checkBankNoThreeMethod(String name, String cardNo, String idNum) {
		final JsonObject jsonObject = ChecksUtil.invokeBankNoThreeAuth(name,cardNo,idNum);
		TCheckBankNo checkBankNo = new TCheckBankNo();
		// 2.处理返回结果
		if (jsonObject != null) {
			//响应code码。200000：成功，其他失败
			String code = jsonObject.get(ChecksConstants.CODE).getAsString();
			if (ChecksConstants.CODE_200000.equals(code) && jsonObject.get(ChecksConstants.DATA) != null) {
				// 调用身份信息校验成功
				// 解析结果数据，进行业务处理
				// 校验状态码  200000：成功，其他失败
				JsonObject resJson = jsonObject.get(ChecksConstants.DATA).getAsJsonObject();
				String message = jsonObject.get(ChecksConstants.MESSAGE).getAsString();
				if (Common.isNotNull(resJson)){
					checkBankNo.setBankNo(cardNo);
					checkBankNo.setBankName(getJsonElementValue(resJson.getAsJsonObject().get("bankName")));
					checkBankNo.setCardCategory(getJsonElementValue(resJson.getAsJsonObject().get("cardCategory")));
					checkBankNo.setCardType(getJsonElementValue(resJson.getAsJsonObject().get("cardType")));
					checkBankNo.setResult(getJsonElementValue(resJson.getAsJsonObject().get(ChecksConstants.RESULT)));
					checkBankNo.setMessage(message);
					checkBankNo.setRemark(getJsonElementValue(resJson.getAsJsonObject().get(ChecksConstants.REMARK)));
					checkBankNo.setType(CommonConstants.ONE_STRING);
					checkBankNo.setName(name);
				}
			} else {
				// 记录错误日志，正式项目中请换成log打印
				return R.failed("银行卡号校验失败:"+jsonObject.get(ChecksConstants.MESSAGE).getAsString());
			}
		} else {
			return R.failed(ChecksConstants.NO_DATA_RESULT);
		}
		return R.ok(checkBankNo);
	}

	private static String getJsonElementValue(JsonElement temp) {
		String msg = "";
		if (Common.isNotNull(temp)) {
			try {
				return temp.getAsString();
			} catch (Exception e) {
				msg = temp.toString();
				if (msg.length() > 10) {
					msg = temp.toString().substring(0, 10);
				}
				return "创蓝云智返回异常：" + msg;
			}
		} else {
			return CommonConstants.EMPTY_STRING;
		}
	}

	/**
	 * @Author fxj
	 * @Description 手机号码状态检测
	 * @Date 17:50 2022/6/20
	 * @param  mobiles  检测手机号，多个手机号码用英文半角逗号隔开，仅支持国内号码
	 **/
	private static R<Map<String,TCheckMobile>> checkMobileMethod(String mobiles, Map<String,TCheckMobile>  checkMobileMap) {
		final JsonObject jsonObject = ChecksUtil.invokeMobile(mobiles);
		// 2.处理返回结果
		if (jsonObject != null) {
			//响应code码。200000：成功，其他失败
			String code = jsonObject.get(ChecksConstants.CODE).getAsString();
			if (ChecksConstants.CODE_200000.equals(code) && jsonObject.get(ChecksConstants.DATA) != null) {
				// 调用身份信息校验成功
				// 解析结果数据，进行业务处理
				// 校验状态码  200000：成功，其他失败
				JsonArray mobileArray = jsonObject.get(ChecksConstants.DATA).getAsJsonArray();
				String message = jsonObject.get(ChecksConstants.MESSAGE).getAsString();
				if (Common.isNotNull(mobileArray) && mobileArray.size() > CommonConstants.ZERO_INT){
					TCheckMobile mobile = null;
					for (int i = 0;i < mobileArray.size(); i++){
						mobile = new TCheckMobile();
						mobile.setMobile(getJsonElementValue(mobileArray.get(i).getAsJsonObject().get(ChecksConstants.MOBILE)));
						mobile.setArea(getJsonElementValue(mobileArray.get(i).getAsJsonObject().get(ChecksConstants.AREA)));
						mobile.setNumbertype(getJsonElementValue(mobileArray.get(i).getAsJsonObject().get(ChecksConstants.NUMBER_TYPE)));
						mobile.setChargesstatus(getJsonElementValue(mobileArray.get(i).getAsJsonObject().get(ChecksConstants.CHARGES_STATUS)));
						mobile.setStatus(getJsonElementValue(mobileArray.get(i).getAsJsonObject().get(ChecksConstants.STATUS)));
						mobile.setMessage(message);
						mobile.setType(CommonConstants.ONE_STRING);
						checkMobileMap.put(mobile.getMobile(),mobile);
					}
				}
			} else {
				// 记录错误日志，正式项目中请换成log打印
				return R.failed("手机号校验失败:" + jsonObject.get(ChecksConstants.MESSAGE).getAsString());
			}
		} else {
			return R.failed(ChecksConstants.NO_DATA_RESULT);
		}
		return R.ok(checkMobileMap);
	}

	// 核心调用
     private static void checkIdCardMethod(TCheckIdCard checkIdCard) {
          final JsonObject jsonObject = ChecksUtil.invokeIdCard(checkIdCard.getName(), checkIdCard.getIdCard());
          // 2.处理返回结果
          if (jsonObject != null) {
               //响应code码。200000：成功，其他失败
               String code = jsonObject.get(ChecksConstants.CODE).getAsString();
               if (ChecksConstants.CODE_200000.equals(code) && jsonObject.get(ChecksConstants.DATA) != null) {
                    // 调用身份信息校验成功
                    // 解析结果数据，进行业务处理
                    // 校验状态码  200000：成功，其他失败
				   JsonObject resultJson = jsonObject.get(ChecksConstants.DATA).getAsJsonObject();
				   String  resultStr = getJsonElementValue(resultJson.getAsJsonObject().get(ChecksConstants.RESULT));
                    if ("01".equals(resultStr)) {
                         checkIdCard.setIsTrue(CommonConstants.ONE_INT);
                         checkIdCard.setReason("正确");
                    } else {
                         checkIdCard.setIsTrue(CommonConstants.ZERO_INT);
                         String remark = getJsonElementValue(resultJson.get(ChecksConstants.REMARK));
                         checkIdCard.setReason("调用身份信息校验失败:" + remark);
                    }
               } else {
                    // 记录错误日志，正式项目中请换成log打印
                    checkIdCard.setIsTrue(CommonConstants.ZERO_INT);
                    checkIdCard.setReason("调用身份信息校验失败:" + jsonObject.get(ChecksConstants.MESSAGE).getAsString());
               }
          } else {
               checkIdCard.setIsTrue(CommonConstants.ZERO_INT);
               checkIdCard.setReason(ChecksConstants.NO_DATA_RESULT);
          }
     }

     private static JsonObject invokeIdCard(String name, String idNum) {
          Map<String, String> params = new HashMap<>();
          params.put(ChecksConstants.APP_ID, APP_ID);
          params.put(ChecksConstants.APP_KEY, APP_KEY_IDCARD);
          params.put(ChecksConstants.NAME, name);
          params.put(ChecksConstants.ID_NUM, idNum);
          String result = HttpUtils.post(API_URL, params);
          // 解析json,并返回结果
		 if (Common.isNotNull(result)){
			 return jsonParser.parse(result).getAsJsonObject();
		 }
		 return null;
     }

	 /**
	  * @Author fxj
	  * @Description 手机号码状态检测
	  * @Date 17:50 2022/6/20
	  * @param  mobiles  检测手机号，多个手机号码用英文半角逗号隔开，仅支持国内号码
	 **/
	private static JsonObject invokeMobile(String mobiles) {
		Map<String, String> params = new HashMap<>();
		params.put(ChecksConstants.APP_ID, APP_ID);
		params.put(ChecksConstants.APP_KEY, APP_KEY_IDCARD);
		params.put(ChecksConstants.MOBILES, mobiles);
		String result = HttpUtils.post(API_URL_MOBILE, params);
		// 解析json,并返回结果
		if (Common.isNotNull(result)){
			return jsonParser.parse(result).getAsJsonObject();
		}
		return null;
	}

	private static JsonObject invokeBankNo(String name, String idNum, String cardNo, String mobile) {
		Map<String, String> params = new HashMap<>();
		params.put(ChecksConstants.APP_ID, APP_ID);
		params.put(ChecksConstants.APP_KEY, APP_KEY_IDCARD);
		params.put(ChecksConstants.NAME, name);
		params.put(ChecksConstants.ID_NUM, idNum);
		params.put(ChecksConstants.CARD_NO, cardNo);
		if (Common.isNotNull(mobile)){
			params.put(ChecksConstants.MOBILE, mobile);
		}
		String result = HttpUtils.post(API_URL_BANK_NO, params);
		// 解析json,并返回结果
		if (Common.isNotNull(result)){
			return jsonParser.parse(result).getAsJsonObject();
		}
		return null;
	}

	private static JsonObject invokeBankNoTwoAuth(String name,String cardNo) {
		Map<String, String> params = new HashMap<>();
		params.put(ChecksConstants.APP_ID, APP_ID);
		params.put(ChecksConstants.APP_KEY, APP_KEY_IDCARD);
		params.put(ChecksConstants.NAME, name);
		params.put(ChecksConstants.CARD_NO, cardNo);
		String result = HttpUtils.post(API_URL_BANK_NO_TWO, params);
		// 解析json,并返回结果
		if (Common.isNotNull(result)){
			return jsonParser.parse(result).getAsJsonObject();
		}
		return null;
	}
	private static JsonObject invokeBankNoThreeAuth(String name,String cardNo,String idNum) {
		Map<String, String> params = new HashMap<>();
		params.put(ChecksConstants.APP_ID, APP_ID);
		params.put(ChecksConstants.APP_KEY, APP_KEY_IDCARD);
		params.put(ChecksConstants.NAME, name);
		params.put(ChecksConstants.CARD_NO, cardNo);
		params.put(ChecksConstants.ID_NUM, idNum);
		String result = HttpUtils.post(API_URL_BANK_NO_THREE, params);
		// 解析json,并返回结果
		if (Common.isNotNull(result)){
			return jsonParser.parse(result).getAsJsonObject();
		}
		return null;
	}
}
