package org.dromara.settlement.dubbo;

import java.net.URLEncoder;
import java.util.Map;

import com.alibaba.fastjson.JSONObject;
import org.apache.dubbo.config.annotation.DubboService;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.settlement.api.RemoteAuthService;
import org.dromara.settlement.api.domain.Result;
import org.dromara.settlement.api.domain.auth.BankCardInfo;
import org.dromara.settlement.api.domain.auth.BankInfo;
import org.dromara.settlement.api.domain.auth.CardIdBack;
import org.dromara.settlement.api.domain.auth.CardIdPositive;
import org.dromara.settlement.common.PostDataTools;
import org.dromara.settlement.service.impl.ZhiFuBaoServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMethod;


@Service
@DubboService
public class RemoteAuthServiceImpl implements RemoteAuthService
{
	private static final Logger log = LoggerFactory.getLogger(RemoteAuthServiceImpl.class);

	@Autowired
	private ZhiFuBaoServiceImpl zhiFuBaoServiceImpl;//支付宝业务

	@Override
	public Result<CardIdPositive> authCardIdPositive(String positive) {
		// TODO 自动生成的方法存根
		Result<CardIdPositive> result = new Result<CardIdPositive>();
		try {
			String json = PostDataTools.getIstance().sendMessageInfo("https://ocridcard.market.alicloudapi.com/idimages", "image="+positive+"&idCardSide=front",
					new String[] { "Content-Type:application/x-www-form-urlencoded;charset=utf-8","Authorization:APPCODE a8b81c2f4630449398ad5649fd72425d" },
					false, false);
			if(StringUtils.isBlank(json)) {
				throw new ServiceException("认证身份证正面出错，请检查参数");
			}

			Map<String, Object> param = JSONObject.parseObject(json,Map.class);
			if (param.get("code").equals("1")) {
				CardIdPositive worker = JSONObject.parseObject(JSONObject.toJSONString(param.get("result")), CardIdPositive.class);
				worker.setBirthday(worker.getBirthday().substring(0,4)+"-"+worker.getBirthday().substring(4,6)+"-"+worker.getBirthday().substring(6,8));
				result.setRtnData(worker);
			}else {
				throw new ServiceException(param.get("msg")+"");
			}
		} catch (Exception e) {
			String msgStr = "认证身份证正面出错（"+positive+"）：";
			log.error(msgStr,e);
			if(e instanceof ServiceException)
				result.tip(e.getMessage());
			else
				result.addError(msgStr+","+e.getMessage());
		}
		return result;
	}

	@Override
	public Result<CardIdBack> authCardIdBack(String back) {
		// TODO 自动生成的方法存根
		Result<CardIdBack> result = new Result<CardIdBack>();
		try {
			String json = PostDataTools.getIstance().sendMessageInfo("https://ocridcard.market.alicloudapi.com/idimages", "image="+back+"&idCardSide=back",
					new String[] { "Content-Type:application/x-www-form-urlencoded;charset=utf-8","Authorization:APPCODE a8b81c2f4630449398ad5649fd72425d" },
					false, false);
			if(StringUtils.isBlank(json)) {
				throw new ServiceException("认证身份证反面出错，请检查参数");
			}
			Map<String, Object> param = JSONObject.parseObject(json,Map.class);
			if (param.get("code").equals("1")) {
				CardIdBack worker = JSONObject.parseObject(JSONObject.toJSONString(param.get("result")), CardIdBack.class);
				worker.setIssueDate(worker.getIssueDate().substring(0,4)+"-"+worker.getIssueDate().substring(4,6)+"-"+worker.getIssueDate().substring(6,8));
				if(worker.getExpiryDate().length() == 8) {
					worker.setExpiryDate(worker.getExpiryDate().substring(0,4)+"-"+worker.getExpiryDate().substring(4,6)+"-"+worker.getExpiryDate().substring(6,8));
				}
				result.setRtnData(worker);
			}else {
				throw new ServiceException(param.get("msg")+"");
			}
		} catch (Exception e) {
			String msgStr = "认证身份证反面出错（"+back+"）：";
			log.error(msgStr,e);
			if(e instanceof ServiceException)
				result.tip(e.getMessage());
			else
				result.addError(msgStr+","+e.getMessage());
		}
		return result;
	}

	@Override
	public Result<BankInfo> authBankMatch(String bankcard, String name, String idcard) {
		// TODO 自动生成的方法存根
		Result<BankInfo> result = new Result<BankInfo>();
		try {
			String json = PostDataTools.getIstance().sendMessageNullParam("https://bankcard234.shumaidata.com/bankcard234?bankcard="+bankcard+"&idcard="+idcard+"&name="+URLEncoder.encode(name,"UTF-8"), RequestMethod.GET,
					new String[] { "Content-Type:application/json; charset=utf-8","Authorization:APPCODE a8b81c2f4630449398ad5649fd72425d" },false);
			if(StringUtils.isBlank(json)) {
				throw new ServiceException("认证银行卡出错，请检查参数");
			}
			Map<String, Object> param = JSONObject.parseObject(json,Map.class);
			if (param.get("code").toString().equals("200") && param.containsKey("data")) {
				Map data = (Map)param.get("data");
				if (data.get("result").toString().equals("0") && data.containsKey("bank_info")) {
					result.setRtnData(JSONObject.parseObject(JSONObject.toJSONString(data.get("bank_info")), BankInfo.class));
				}
			}else {
				throw new ServiceException(param.get("msg")+"");
			}
		} catch (Exception e) {
			String msgStr = "认证银行卡是否一致出错（"+bankcard+","+name+","+idcard+"）：";
			log.error(msgStr,e);
			if(e instanceof ServiceException)
				result.tip(e.getMessage());
			else
				result.addError(msgStr+","+e.getMessage());
		}
		return result;
	}

	@Override
	public Result<BankCardInfo> authBankInfo(String bankcardUrl) {
		// TODO 自动生成的方法存根
		Result<BankCardInfo> result = new Result<BankCardInfo>();
		try {
			String json = PostDataTools.getIstance().sendMessageInfo("https://cardid.market.alicloudapi.com/ai_market/ai_ocr_universal/yin_hang_ka/v1", "IMAGE="+bankcardUrl+"&IMAGE_TYPE=1",
					new String[] { "Content-Type:application/x-www-form-urlencoded;charset=utf-8","Authorization:APPCODE a8b81c2f4630449398ad5649fd72425d" },
					false, false);
			if(StringUtils.isBlank(json)) {
				throw new ServiceException("认证银行卡出错，请检查参数");
			}
			Map<String, Object> param = JSONObject.parseObject(json,Map.class);
			if (param.containsKey("银行卡实体信息")) {
				Map map = (Map)param.get("银行卡实体信息");
				BankCardInfo bank = new BankCardInfo();
				bank.setCard(map.get("银行卡号")+"");
				bank.setExpireDate(map.get("银行卡有效期")+"");
				bank.setName(map.get("银行名称")+"");
				bank.setType(map.get("银行卡类型")+"");
				bank.setTypeName(map.get("银行卡类型名称")+"");
				result.setRtnData(bank);
			}else {
				throw new ServiceException(param.get("msg")+"");
			}
		} catch (Exception e) {
			String msgStr = "认证银行卡信息出错（"+bankcardUrl+"）：";
			log.error(msgStr,e);
			if(e instanceof ServiceException)
				result.tip(e.getMessage());
			else
				result.addError(msgStr+","+e.getMessage());
		}
		return result;
	}

	@Override
	public Result<Boolean> valiAccount(long unitId, String bankType, String bankCard, String mobile, String name,
			String cardId) {
		// TODO 自动生成的方法存根
		Result<Boolean> result = new Result<Boolean>(false);
		try {
			if (bankType.equals("支付宝")) {
				result.setRtnData(zhiFuBaoServiceImpl.valiAccount(bankCard, mobile, name, cardId));
			}
		} catch (Exception e) {
			String msgStr = "验证银行账号是否有效出错（"+unitId+","+bankType+","+bankCard+","+mobile+","+name+","+cardId+"）：";
			log.error(msgStr,e);
			if(e instanceof ServiceException)
				result.tip(e.getMessage());
			else
				result.addError(msgStr+","+e.getMessage());
		}
		return result;
	}
}
