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.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 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);
          }
     }
	/**
	 * @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 {
			return R.failed(ChecksConstants.NACOS_CHECK_CONFIG_ERROR);
		}
	}
	/**
	 * @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 {
			return R.failed(ChecksConstants.NACOS_CHECK_CONFIG_ERROR);
		}
	}

	private 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("银行卡号校验失败,code:" + code + ",msg:" + jsonObject.get(ChecksConstants.MESSAGE).getAsString());
			}
		} else {
			return R.failed(ChecksConstants.NO_DATA_RESULT);
		}
		return R.ok(checkBankNo);
	}

	private static String getJsonElementValue(JsonElement temp){
		return Common.isNotNull(temp)?temp.getAsString():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("手机号校验失败,code:" + code + ",msg:" + 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("调用身份信息校验失败,resultStr:" + resultStr + ",msg:" + remark);
                    }
               } else {
                    // 记录错误日志，正式项目中请换成log打印
                    checkIdCard.setIsTrue(CommonConstants.ZERO_INT);
                    checkIdCard.setReason("调用身份信息校验失败,code:" + code + ",msg:" + 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,并返回结果
          return jsonParser.parse(result).getAsJsonObject();
     }

	 /**
	  * @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,并返回结果
		return jsonParser.parse(result).getAsJsonObject();
	}

	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,并返回结果
		return jsonParser.parse(result).getAsJsonObject();
	}

	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);
		String result = HttpUtils.post(API_URL_BANK_NO_TWO, params);
		// 解析json,并返回结果
		return jsonParser.parse(result).getAsJsonObject();
	}
}
