package org.dromara.settlement.service.impl;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.util.Date;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FileUtils;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.settlement.api.domain.*;
import org.dromara.settlement.common.bank.zhifubao.ZhiFuBaoConfig;
import org.dromara.settlement.common.bank.zhifubao.ZhiFuBaoResponse;
import org.dromara.settlement.common.bank.zhifubao.ZhiFuBaoUtil;
import org.dromara.settlement.domain.SysLog;
import org.dromara.settlement.mapper.SignZhifubaoMapper;
import org.dromara.settlement.mapper.SysLogMapper;
import org.dromara.settlement.mapper.TransactionLogMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import org.dromara.settlement.api.RemoteConfigService;
import com.alipay.api.AlipayRequest;
import com.alipay.api.request.AlipayDataBillAccountbookereceiptQueryRequest;
import com.alipay.api.request.AlipayDataBillEreceiptagentApplyRequest;
import com.alipay.api.request.AlipayFundAccountbookCreateRequest;
import com.alipay.api.request.AlipayFundAccountbookNotifyQueryRequest;
import com.alipay.api.request.AlipayFundAccountbookNotifySubscribeRequest;
import com.alipay.api.request.AlipayFundAccountbookNotifyUnsubscribeRequest;
import com.alipay.api.request.AlipayFundTransCommonQueryRequest;
import com.alipay.api.request.AlipayFundTransUniTransferRequest;
import com.alipay.api.request.AlipayUserAgreementPageSignRequest;
import com.alipay.api.request.AlipayUserAgreementQueryRequest;
import com.alipay.api.request.AlipayUserAgreementUnsignRequest;
import com.alipay.api.request.AlipayUserCertdocCertverifyConsultRequest;
import com.alipay.api.request.AlipayUserCertdocCertverifyPreconsultRequest;
import com.alipay.api.response.AlipayDataBillAccountbookereceiptQueryResponse;
import com.alipay.api.response.AlipayDataBillEreceiptagentApplyResponse;
import com.alipay.api.response.AlipayFundAccountbookCreateResponse;
import com.alipay.api.response.AlipayFundAccountbookNotifyQueryResponse;
import com.alipay.api.response.AlipayFundTransCommonQueryResponse;
import com.alipay.api.response.AlipayFundTransUniTransferResponse;
import com.alipay.api.response.AlipayUserAgreementPageSignResponse;
import com.alipay.api.response.AlipayUserAgreementQueryResponse;
import com.alipay.api.response.AlipayUserCertdocCertverifyConsultResponse;
import com.alipay.api.response.AlipayUserCertdocCertverifyPreconsultResponse;
import com.jcraft.jsch.SftpException;


@Service
public class ZhiFuBaoServiceImpl {
	private Logger log = LoggerFactory.getLogger(ZhiFuBaoServiceImpl.class);

	@Autowired
	private RemoteConfigService wConfigService;// 配置

	@Autowired
	private TransactionLogMapper transactionLogDao;// 交易记录dao

	@Autowired
	private SysLogMapper sysLogDao;// 日志

	@Autowired
	private SignZhifubaoMapper signZhifubaoDao;// 支付宝签约信息

	private ZhiFuBaoResponse request(long unitId, AlipayRequest request, boolean record) {
		return request(unitId, request, record, null, false);
	}

	private ZhiFuBaoResponse requestPage(long unitId, AlipayRequest request, boolean record) {
		return request(unitId, request, record, null, true);
	}

	private ZhiFuBaoResponse request(long unitId, AlipayRequest request, boolean record, Long tranId) {
		return request(unitId, request, record, tranId, false);
	}

	private ZhiFuBaoResponse request(long unitId, AlipayRequest request, boolean record, Long tranId, boolean isPage) {
		ZhiFuBaoResponse response = null;
		ZhiFuBaoConfig config = getBankConfig(unitId);
		String reqid = DateUtils.parseDateToString("yyyyMMddHHmmssSSS", new Date());
		SysLog sysLog = new SysLog();
		if (record) {
			sysLog.setTranId(tranId);
		}
		sysLogDao.insert(sysLog);
		reqid = reqid + sysLog.getId();
		if (record) {
			sysLog.setReqid(reqid);
			sysLog.setRequestTime(new Date());
		}
		Result<ZhiFuBaoResponse> requsetRtn = ZhiFuBaoUtil.getInstance().request(config, request, isPage);
		if (requsetRtn != null) {
			response = requsetRtn.getRtnData();
			if (record) {
				sysLog.setRequest(requsetRtn.getResult());
				sysLog.setResponseTime(new Date());
				if (requsetRtn.getRtnData() != null) {
					sysLog.setResponse(JSONObject.toJSONString(requsetRtn.getRtnData()));
				}
			}
		}
		if (sysLog.getId() != null) {
			if (record) {
				if (tranId != null) {
					sysLogDao.deleteByTranId(tranId, sysLog.getId());
				}
				sysLogDao.updateByPrimaryKeySelective(sysLog);
			} else
				sysLogDao.deleteByPrimaryKey(sysLog.getId());
		}
		return response;
	}

	public ZhiFuBaoConfig getBankConfig(long unitId) {
		ZhiFuBaoConfig config = new ZhiFuBaoConfig();
		if (wConfigService != null && unitId > 0) {
			config.URL = wConfigService.getItem(unitId, "zhifubao_bank_api");
			//config.URL = config.URL.replace("test://", "https://");//测试时使用
			config.APPID = wConfigService.getItem(unitId, "zhifubao_bank_appid");
			config.accName = wConfigService.getItem(unitId, "zhifubao_acc_name");
			config.prikeyStr = wConfigService.getItem(unitId, "zhifubao_bank_prikey");
			String uploadPhyPath = wConfigService.getUploadPhyPath(unitId) + "/";
			config.alipayCertPublicKey = uploadPhyPath
					+ wConfigService.getItem(unitId, "zhifubao_bank_alipayCertPublicKey");
			config.alipayRootCert = uploadPhyPath + wConfigService.getItem(unitId, "zhifubao_bank_alipayRootCert");
			config.appCertPublicKey = uploadPhyPath + wConfigService.getItem(unitId, "zhifubao_bank_appCertPublicKey");
			config.notifyUrl = wConfigService.getItem(unitId, "zhifubao_bank_notifyUrl");
			if (StringUtils.isBlank(config.APPID)) {
				String key = "config:" + unitId;
				RedisUtils.deleteObject(key);
			}
			log.info("读取结算中心的账户配置（" + unitId + "）：" + config.APPID);
		}
		return config;
	}

	/**
	 * 解约支付宝协议
	 *
	 * @author 张涛
	 * @date 2022年8月29日
	 * @param unitId 结算单位id
	 * @return
	 */
	public void cancelAgreement(long unitId) {
		AlipayUserAgreementUnsignRequest request = new AlipayUserAgreementUnsignRequest();
		request.setBizContent("{" + "  \"personal_product_code\":\"FUND_SAFT_SIGN_WITHHOLDING_P\","
				+ "  \"sign_scene\":\"INDUSTRY|SATF_ACC\"," + "  \"external_agreement_no\":\"" + unitId + "\","
				+ "  \"third_party_type\":\"PARTNER\"" + "}");
		request(unitId, request, false);
	}

	/**
	 * 获取支付宝协议二维码
	 *
	 * @author 张涛
	 * @date 2022年8月29日
	 * @param unitId 结算单位id
	 * @return
	 */
	public SignZhifubao getAgreementQrcode(long unitId, String unitName) {
		ZhiFuBaoConfig config = getBankConfig(unitId);
		if (StringUtils.isBlank(config.APPID)) {
			return new SignZhifubao();
		}
		AlipayUserAgreementQueryRequest queryReq = new AlipayUserAgreementQueryRequest();
		queryReq.setBizContent("{" +
		        "    \"personal_product_code\": \"FUND_SAFT_SIGN_WITHHOLDING_P\"," +
		        "    \"sign_scene\": \"INDUSTRY|SATF_ACC\"," +
		        "    \"product_code\": \"FUND_SAFT_SIGN_WITHHOLDING\"," +
		        "    \"external_agreement_no\": \""+unitId+"\"," +
		        "    \"third_party_type\": \"PARTNER\"" +
		        "}");//设置业务参数
		ZhiFuBaoResponse queryRes = request(unitId, queryReq, false);
		if (queryRes == null) {
			throw new ServiceException("请检查结算中心的配置是否正确");
		}
		SignZhifubao result = new SignZhifubao();
		if (queryRes.getResultcode().equals("10000")) {
			AlipayUserAgreementQueryResponse queryResObj = (AlipayUserAgreementQueryResponse)queryRes.getData();
			result.setAppId(config.APPID);
			result.setAgreementNo(queryResObj.getAgreementNo());
			result.setAlipayLogonId(queryResObj.getAlipayLogonId());
			result.setSignTime(DateUtils.parseStringToDate(DateUtils.YYYY_MM_DD_HH_MM_SS, queryResObj.getSignTime()));
			result.setStatus(queryResObj.getStatus());
			result.setValidTime(DateUtils.parseStringToDate(DateUtils.YYYY_MM_DD_HH_MM_SS, queryResObj.getValidTime()));
		}
		AlipayUserAgreementPageSignRequest request = new AlipayUserAgreementPageSignRequest();
		request.setNotifyUrl(config.notifyUrl + "public/signAgr");
		request.setBizContent("{" + "    \"external_logon_id\": \"" + unitName + "\","
				+ "    \"personal_product_code\": \"FUND_SAFT_SIGN_WITHHOLDING_P\","
				+ "    \"sign_scene\": \"INDUSTRY|SATF_ACC\"," + "    \"external_agreement_no\": \"" + unitId + "\","
				+ "    \"third_party_type\": \"PARTNER\"," + "    \"product_code\": \"FUND_SAFT_SIGN_WITHHOLDING\","
				+ "    \"access_params\": {" + "        \"channel\": \"QRCODE\"" + "    }" + "}");// 设置业务参数
		ZhiFuBaoResponse res = requestPage(unitId, request, false);
		if (res != null) {
			AlipayUserAgreementPageSignResponse response = (AlipayUserAgreementPageSignResponse) res.getData();
			System.out.println(response.getBody());
			result.setSignUrl(response.getBody());
		}
		return result;
	}

	/**
	 * 创建支付宝记账本
	 *
	 * @author 张涛
	 * @date 2021年8月24日
	 * @param unitId 结算单位id
	 * @param code   记账本编号
	 * @param name   记账本名称
	 * @param prefix 记账本编号前缀
	 */
	public Account createAccount(long unitId, String code, String name, String prefix) {
		ZhiFuBaoConfig config = getBankConfig(unitId);
		SignZhifubao sign = signZhifubaoDao.selectByAppId(config.APPID);
		if (sign == null) {
			throw new ServiceException("未签约协议");
		}
		int total = 10;
		if (StringUtils.isNotEmpty(prefix)) {
			total -= prefix.length();
		}
		if (code.length() < 10) {
			for (int i = code.length(); i < total; i++) {
				code = "0" + code;
			}
			if (StringUtils.isNotEmpty(prefix)) {
				code = prefix + code;
			}
		}
		AlipayFundAccountbookCreateRequest request = new AlipayFundAccountbookCreateRequest();
		request.setBizContent("  {" + "    \"merchant_user_id\":\"" + code + "\","
				+ "    \"merchant_user_type\":\"BUSINESS_ORGANIZATION\"," + "    \"scene_code\":\"SATF_FUND_BOOK\","
				+ "    \"ext_info\":\"{\\\"agreement_no\\\":\\\"" + sign.getAgreementNo() + "\\\",\\\"userId\\\":\\\""
				+ code + "\\\",\\\"userName\\\":\\\"" + name + "\\\",\\\"userType\\\":\\\"" + prefix
				+ "\\\",\\\"unitId\\\":\\\"" + unitId + "\\\"}\"" + " }");
		ZhiFuBaoResponse res = request(unitId, request, false);
		if (res != null && res.getResultcode().equals("10000")) {
			AlipayFundAccountbookCreateResponse book = (AlipayFundAccountbookCreateResponse) res.getData();
			String subscribeBiz = "{" + "  \"product_code\":\"SATF_FUND_BOOK\"," + "  \"biz_scene\":\"DEFAULT\","
					+ "  \"account_book_id\":\"" + book.getAccountBookId() + "\"," + "  \"agreement_no\":\""
					+ sign.getAgreementNo() + "\"" + "}";
			AlipayFundAccountbookNotifyQueryRequest subSearch = new AlipayFundAccountbookNotifyQueryRequest();
			subSearch.setBizContent(subscribeBiz);
			ZhiFuBaoResponse subRes = request(unitId, subSearch, false);
			if (subRes != null) {
				boolean subSuccess = true;// 是否订阅成功
				AlipayFundAccountbookNotifyQueryResponse subSearchRes = (AlipayFundAccountbookNotifyQueryResponse) subRes
						.getData();
				if ("SUBSCRIPTION_RELATION_NOT_EXIST".equals(subSearchRes.getSubCode()) || "ACCOUNT_BOOK_INFO_QUERY_FAIL".equals(subSearchRes.getSubCode())
						|| (StringUtils.isNotBlank(subSearchRes.getSubscribeStatus()) && subSearchRes.getSubscribeStatus().equals("INVALID"))) {
					if (StringUtils.isNotBlank(subSearchRes.getSubscribeStatus()) && subSearchRes.getSubscribeStatus().equals("INVALID")) {
						AlipayFundAccountbookNotifyUnsubscribeRequest unsubReq = new AlipayFundAccountbookNotifyUnsubscribeRequest();
						unsubReq.setBizContent(subscribeBiz);
						request(unitId, unsubReq, false);
					}
					AlipayFundAccountbookNotifySubscribeRequest subReq = new AlipayFundAccountbookNotifySubscribeRequest();
					subReq.setBizContent(subscribeBiz);
					subRes = request(unitId, subReq, false);
					if (subRes == null || !subRes.getResultcode().equals("10000")) {
						subSuccess = false;
					}
				}
				if (subSuccess) {
					Account account = new Account();
					account.setBankType("支付宝");
					account.setBankTypeName("支付宝");
					account.setBankCard(book.getExtCardInfo().getCardNo());
					account.setBankArgNo(book.getAccountBookId());
					account.setBankAddress(book.getExtCardInfo().getCardLocation());
					account.setBalance(0l);
					return account;
				}
			}
		}
		return null;
	}

	/**
	 * 记账本内部转账
	 *
	 * @author 张涛
	 * @date 2021年9月7日
	 * @param log
	 * @return
	 */
	public TransactionLog innerTransfer(TransactionLog log) {
		ZhiFuBaoConfig config = getBankConfig(log.getUnitId());
		SignZhifubao sign = signZhifubaoDao.selectByAppId(config.APPID);
		if (sign == null) {
			log.setResult((short)3);//失败
			log.setReason("未签约协议");
			return log;
		}
		AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest();
		String amt = String.format("%.2f", log.getAmount() / 100.0);
		request.setBizContent("{" +
				"\"out_biz_no\":\""+log.getOrderNo()+"\"," +
				"\"trans_amount\":"+amt+"," +
				"\"product_code\":\"SINGLE_TRANSFER_NO_PWD\"," +
				"\"biz_scene\":\"ENTRUST_ALLOCATION\"," +
				"\"order_title\":\""+log.getRemark()+"\"," +
				"\"payee_info\":{" +
				"\"identity_type\":\"ACCOUNT_BOOK_ID\"," +
				"\"identity\":\""+log.getTargetCard()+"\"," +
				"\"name\":\""+log.getTargetAccName()+"\"," +
				" \"ext_info\": \"{\\\"agreement_no\\\":\\\""+sign.getAgreementNo()+"\\\"}\"" +
				"    }," +
				"\"payer_info\":{" +
				"\"identity_type\":\"ACCOUNT_BOOK_ID\"," +
				"\"identity\":\""+log.getSourceCard()+"\"," +
				" \"ext_info\": \"{\\\"agreement_no\\\":\\\""+sign.getAgreementNo()+"\\\"}\"" +
				"    }," +
				"\"remark\":\""+log.getRemark()+"\"," +
				"\"business_params\":\"{\\\"payer_show_name_use_alias\\\":\\\"true\\\"}\"," +
				"  }");
		ZhiFuBaoResponse res = request(log.getUnitId(), request, true, log.getId());
		AlipayFundTransUniTransferResponse tranRes = null;
		if(res.getData() != null) {
			tranRes = (AlipayFundTransUniTransferResponse)res.getData();
		}
		if (res == null || !res.getResultcode().equals("10000")) {
			String msg = "内部转账失败";
			if (tranRes != null) {
				if (StringUtils.isNotBlank(tranRes.getSubMsg())) {
					msg = tranRes.getSubMsg();
				}else if (StringUtils.isNotBlank(tranRes.getMsg())) {
					msg = tranRes.getMsg();
				}
			}else if (StringUtils.isNotBlank(res.getResultmsg())) {
				msg = res.getResultmsg();
			}
			this.log.error(msg);
			log.setResult((short) -1);
			return log;
		}
		log.setSourceBankNo(tranRes.getOrderId());
		log.setTargetBankNo(tranRes.getPayFundOrderId());
		log.setResult((short) 1);
		log.setReason("");
		return log;
	}

	/**
	 * 转账
	 *
	 * @author 张涛
	 * @date 2021年9月7日
	 * @param log
	 * @return
	 */
	public TransactionLog transfer(TransactionLog log) {
		ZhiFuBaoConfig config = getBankConfig(log.getUnitId());
		SignZhifubao sign = signZhifubaoDao.selectByAppId(config.APPID);
		if (sign == null) {
			log.setResult((short)3);//失败
			log.setReason("未签约协议");
			return log;
		}
		AlipayFundTransUniTransferRequest request = new AlipayFundTransUniTransferRequest();
		String amt = String.format("%.2f", log.getAmount() / 100.0);
		request.setBizContent("{" +
		"\"out_biz_no\":\""+log.getOrderNo()+"\"," +
		"\"trans_amount\":"+amt+"," +
		"\"product_code\":\"SINGLE_TRANSFER_NO_PWD\"," +
		"\"biz_scene\":\"ENTRUST_TRANSFER\"," +
		"\"order_title\":\""+log.getRemark()+"\"," +
		"\"payee_info\":{" +
		"\"identity\":\""+log.getTargetCard()+"\"," +
		"\"identity_type\":\"ALIPAY_LOGON_ID\"," +
		"\"name\":\""+log.getTargetAccName()+"\"" +
		"    }," +
		"\"remark\":\""+log.getRemark()+"\"," +
		"\"business_params\":\"{\\\"payer_show_name_use_alias\\\":\\\"true\\\"}\"," +
		"\"payer_info\":{" +
		"\"identity\":\""+log.getSourceCard()+"\"," +
		"\"identity_type\":\"ACCOUNT_BOOK_ID\"," +
		" \"ext_info\": \"{\\\"agreement_no\\\":\\\""+sign.getAgreementNo()+"\\\"}\"" +
		"    }" +
		"  }");
		ZhiFuBaoResponse res = request(log.getUnitId(), request, true, log.getId());
		AlipayFundTransUniTransferResponse tranRes = null;
		if(res.getData() != null) {
			tranRes = (AlipayFundTransUniTransferResponse)res.getData();
		}
		if (res == null || !res.getResultcode().equals("10000")) {
			String msg = "转账失败";
			if (tranRes != null) {
				if (StringUtils.isNotBlank(tranRes.getSubMsg())) {
					msg = tranRes.getSubMsg();
				}else if (StringUtils.isNotBlank(tranRes.getMsg())) {
					msg = tranRes.getMsg();
				}
			}else if (StringUtils.isNotBlank(res.getResultmsg())) {
				msg = res.getResultmsg();
			}
			throw new ServiceException(msg);
		}
		log.setSourceBankNo(tranRes.getOrderId());
		log.setTargetBankNo(tranRes.getPayFundOrderId());
		log.setResult((short) 1);
		log.setReason("");
		return log;
	}

	/**
	 * 同步内部交易结果
	 *
	 * @author 张涛
	 * @date 2021年9月7日
	 * @param log
	 * @return
	 */
	public TransactionLog synInnerTransfer(TransactionLog log) {
		AlipayFundTransCommonQueryRequest request = new AlipayFundTransCommonQueryRequest();
		request.setProdCode("SINGLE_TRANSFER_NO_PWD");
		request.setBizContent("{" + "  \"product_code\":\"SINGLE_TRANSFER_NO_PWD\"," + "  \"biz_scene\":\"ENTRUST_ALLOCATION\","
				+ "  \"out_biz_no\":\"" + log.getOrderNo() + "\"}");
		ZhiFuBaoResponse res = request(log.getUnitId(), request, false, log.getId());
		if (res != null) {
			if (!res.getResultcode().equals("10000")) {
				throw new ServiceException(
						res != null && StringUtils.isNotBlank(res.getResultmsg()) ? res.getResultmsg()
								: "同步支付宝对私交易结果失败");
			}
			AlipayFundTransCommonQueryResponse queryRes = (AlipayFundTransCommonQueryResponse)res.getData();
			if (queryRes.getStatus().equals("SUCCESS")) {
				log.setResult((short) 2);
				log.setTranTime(new Date());
			}else if (!queryRes.getStatus().equals("WAIT_PAY")) {
				log.setResult((short) 3);
				log.setReason(queryRes.getFailReason());
				log.setTranTime(new Date());
			}
		}
		return log;
	}

	/**
	 * 同步交易结果
	 *
	 * @author 张涛
	 * @date 2021年9月7日
	 * @param log
	 * @return
	 */
	public TransactionLog synTransfer(TransactionLog log) {
		AlipayFundTransCommonQueryRequest request = new AlipayFundTransCommonQueryRequest();
		request.setProdCode("SINGLE_TRANSFER_NO_PWD");
		request.setBizContent("{" + "  \"product_code\":\"SINGLE_TRANSFER_NO_PWD\"," + "  \"biz_scene\":\"ENTRUST_TRANSFER\","
				+ "  \"out_biz_no\":\"" + log.getOrderNo() + "\"}");
		ZhiFuBaoResponse res = request(log.getUnitId(), request, false, log.getId());
		if (res != null) {
			if (!res.getResultcode().equals("10000")) {
				throw new ServiceException(
						res != null && StringUtils.isNotBlank(res.getResultmsg()) ? res.getResultmsg()
								: "同步支付宝交易结果失败");
			}
			AlipayFundTransCommonQueryResponse queryRes = (AlipayFundTransCommonQueryResponse)res.getData();
			if (queryRes.getStatus().equals("SUCCESS")) {
				log.setResult((short) 2);
				log.setTranTime(new Date());
			}else if (!queryRes.getStatus().equals("WAIT_PAY")) {
				log.setResult((short) 3);
				log.setReason(queryRes.getFailReason());
				log.setTranTime(new Date());
			}
		}
		return log;
	}

	/**
	 * 获取交易回置单
	 *
	 * @author 张涛
	 * @date 2021年9月16日
	 * @param log
	 * @return
	 * @throws IOException
	 * @throws SftpException
	 */

	public String getTransferCallback(TransactionLog log) throws IOException {
		ZhiFuBaoConfig config = getBankConfig(log.getUnitId());
		SignZhifubao sign = signZhifubaoDao.selectByAppId(config.APPID);
		if (sign == null) {
			throw new ServiceException("未签约协议");
		}
		AlipayDataBillAccountbookereceiptQueryRequest queryReq = new AlipayDataBillAccountbookereceiptQueryRequest();
		queryReq.setBizContent("{"
		                      + "\"file_id\":\""+log.getPayReceiptId()+"\","
		                      + "\"agreement_no\":\""+sign.getAgreementNo()+"\""
		                      + "  }");
		String callBackFile = "";
		ZhiFuBaoResponse res = request(log.getUnitId(),queryReq,false,log.getId());
		if (res != null && res.getResultcode().equals("10000")) {
			AlipayDataBillAccountbookereceiptQueryResponse queryRes = (AlipayDataBillAccountbookereceiptQueryResponse)res.getData();
			if(queryRes.getStatus().equals("SUCCESS")) {
				String uploadPhyPath = wConfigService.getUploadPhyPath(log.getUnitId()) + "/";
				String uploadNetPath = wConfigService.getUploadNetPath(log.getUnitId());
				String fileName = log.getOrderNo()+".pdf";
				FileUtils.copyURLToFile(new URL(queryRes.getDownloadUrl()), new File(uploadPhyPath, fileName));
				callBackFile = (uploadPhyPath+fileName).replace(uploadPhyPath, uploadNetPath);
			}
        }
		return callBackFile;
	}

	/**
	 * 获取交易流水号
	 *
	 * @author 张涛
	 * @date 2021年9月22日
	 * @param log
	 * @param trsseq 断点续传编号
	 * @return
	 */
	public String getTransferBankNo(TransactionLog log) {
		ZhiFuBaoConfig config = getBankConfig(log.getUnitId());
		SignZhifubao sign = signZhifubaoDao.selectByAppId(config.APPID);
		if (sign == null) {
			throw new ServiceException("未签约协议");
		}
		String result = "";
		boolean isApply = true;//是否需要申请回单
		if(StringUtils.isNotBlank(log.getPayReceiptId())) {
			isApply = false;
			AlipayDataBillAccountbookereceiptQueryRequest queryReq = new AlipayDataBillAccountbookereceiptQueryRequest();
			queryReq.setBizContent("{"
			                      + "\"file_id\":\""+log.getPayReceiptId()+"\","
			                      + "\"agreement_no\":\""+sign.getAgreementNo()+"\""
			                      + "  }");
			ZhiFuBaoResponse res = request(log.getUnitId(),queryReq,false,log.getId());
			if (res != null) {
				if(res.getResultcode().equals("10000")) {
					AlipayDataBillAccountbookereceiptQueryResponse queryRes = (AlipayDataBillAccountbookereceiptQueryResponse)res.getData();
					if(queryRes.getStatus().equals("SUCCESS")) {
						result = log.getTargetBankNo();
					}else if (queryRes.getStatus().equals("FAIL")) {
						isApply = true;
					}
				}else if (res.getData() != null && StringUtils.isNotBlank(res.getData().getSubMsg()) && res.getData().getSubMsg().indexOf("业务异常申请记录不存在") > -1) {
					isApply = true;
				}
				if (isApply) {
					TransactionLog upd = new TransactionLog();
					upd.setId(log.getId());
					upd.setPayReceiptId("");
					transactionLogDao.updateByPrimaryKeySelective(upd);
				}
			}
		}
		if(isApply) {
			AlipayDataBillEreceiptagentApplyRequest request = new AlipayDataBillEreceiptagentApplyRequest();
			request.setBizContent("{" +
			    "\"type\":\"FUND_DETAIL\"," +
			    "\"key\":\""+log.getTargetBankNo()+"\"," +
			    "\"agreement_no\":\""+sign.getAgreementNo()+"\"" +
			    "  }");
	        ZhiFuBaoResponse res = request(log.getUnitId(),request,false,log.getId());
	        if (res == null || !res.getResultcode().equals("10000")) {
	        	throw new ServiceException(StringUtils.isNotBlank(res.getResultmsg()) ? res.getResultmsg() : "获取交易回置单失败");
	        }

	        AlipayDataBillEreceiptagentApplyResponse applyRes = (AlipayDataBillEreceiptagentApplyResponse)res.getData();
	        if(StringUtils.isNotBlank(applyRes.getFileId())) {
	        	TransactionLog upd = new TransactionLog();
				upd.setId(log.getId());
				upd.setPayReceiptId(applyRes.getFileId());
				transactionLogDao.updateByPrimaryKeySelective(upd);
	        }
		}
		return result;
	}

	public boolean valiAccount(String bankCard, String mobile, String name,
			String cardId) {
		SignZhifubao sign = signZhifubaoDao.selectValid();
		if (sign == null) {
			throw new ServiceException("支付宝账户认证失败【错误代码：1】");
		}
		AlipayUserCertdocCertverifyPreconsultRequest request = new AlipayUserCertdocCertverifyPreconsultRequest();
		StringBuffer bizContentStr = new StringBuffer("{");
		bizContentStr.append("  \"user_name\":\""+name+"\",");
		bizContentStr.append("  \"cert_type\":\"IDENTITY_CARD\",");
		bizContentStr.append("  \"cert_no\":\""+cardId+"\",");
		if(StringUtils.isNotBlank(mobile)) {
			bizContentStr.append("  \"mobile\":\""+mobile+"\",");
		}
		bizContentStr.append("  \"logon_id\":\""+bankCard+"\"");
		bizContentStr.append("}");
		request.setBizContent(bizContentStr.toString());
		ZhiFuBaoResponse res = request(sign.getUnitId(),request,false);
        if (res == null || !res.getResultcode().equals("10000")) {
        	throw new ServiceException(StringUtils.isNotBlank(res.getResultmsg()) ? res.getResultmsg() : "支付宝账户认证失败【错误代码：2】");
        }
        AlipayUserCertdocCertverifyPreconsultResponse verifyRes = (AlipayUserCertdocCertverifyPreconsultResponse)res.getData();
        if (StringUtils.isBlank(verifyRes.getVerifyId())) {
        	throw new ServiceException("支付宝账户认证失败【错误代码：3】");
		}
        AlipayUserCertdocCertverifyConsultRequest consultRequest = new AlipayUserCertdocCertverifyConsultRequest();
        consultRequest.setBizContent("{" +
        "  \"verify_id\":\""+verifyRes.getVerifyId()+"\"" +
        "}");
        ZhiFuBaoResponse consultRes = request(sign.getUnitId(),consultRequest,false);
        if (consultRes == null || !consultRes.getResultcode().equals("10000")) {
        	throw new ServiceException(StringUtils.isNotBlank(consultRes.getResultmsg()) ? consultRes.getResultmsg() : "支付宝账户认证失败【错误代码：4】");
        }
        AlipayUserCertdocCertverifyConsultResponse response = (AlipayUserCertdocCertverifyConsultResponse)consultRes.getData();
        if (!"T".equals(response.getPassed())) {
        	throw new ServiceException(StringUtils.isNotBlank(response.getFailReason()) ? response.getFailReason() : "支付宝账户认证失败【错误代码：5】");
		}
		return true;
	}
}
