package com.ym.mec.thirdparty.adapay;

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

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.huifu.adapay.core.exception.BaseAdaPayException;
import com.ym.mec.thirdparty.adapay.entity.AccountInfo;
import com.ym.mec.thirdparty.exception.ThirdpartyException;

/**
 * 结算账户服务
 * 注：若用户想更新银行卡，则需要先调用删除结算账户对象，再使用原 member_id 重新创建结算账户对象，且必须与原创建结算账户使用的身份证和银行卡户名保持一致。
 */
@Service
public class SettleAccountService {

	public String create(String merchantKey, String appId, AccountInfo accountInfo) {
		Map<String, Object> settleCountParams = new HashMap<String, Object>();
		Map<String, Object> accountInfoMap = new HashMap<String, Object>();
		accountInfoMap.put("card_id", accountInfo.getCardId());
		accountInfoMap.put("card_name", accountInfo.getCardName());
		accountInfoMap.put("cert_id", accountInfo.getCertId());
		accountInfoMap.put("cert_type", accountInfo.getCertType());
		accountInfoMap.put("tel_no", accountInfo.getTelNo());
		accountInfoMap.put("bank_code", accountInfo.getBankCode());
		accountInfoMap.put("bank_acct_type", accountInfo.getBankAcctType());
		accountInfoMap.put("prov_code", accountInfo.getProvCode());
		accountInfoMap.put("area_code", accountInfo.getAreaCode());
		settleCountParams.put("member_id", accountInfo.getMemberId());
		settleCountParams.put("app_id", appId);
		settleCountParams.put("channel", "bank_account");
		settleCountParams.put("account_info", accountInfo);
		try {
			Map<String, Object> resp = com.huifu.adapay.model.SettleAccount.create(settleCountParams, merchantKey);
			if (StringUtils.equals("succeeded", resp.get("status").toString())) {
				return resp.get("id").toString();
			}
		} catch (BaseAdaPayException e) {
			new ThirdpartyException("结算账户创建失败:{}", e, e.getMessage());
		}
		return null;
	}

	public boolean delete(String merchantKey, String appId, String memberId, String settleAccountId) {
		Map<String, Object> req = new HashMap<String, Object>();
		req.put("settle_account_id", settleAccountId);
		req.put("member_id", memberId);
		req.put("app_id", appId);
		try {
			Map<String, Object> resp = com.huifu.adapay.model.SettleAccount.delete(req, merchantKey);

			if (StringUtils.equals("succeeded", resp.get("status").toString())) {
				return true;
			}

		} catch (BaseAdaPayException e) {
			new ThirdpartyException("结算账户删除失败:{}", e, e.getMessage());
		}
		return false;
	}
}
