package org.dromara.settlement.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.SftpException;
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.RemoteConfigService;
import org.dromara.settlement.api.domain.*;
import org.dromara.settlement.common.bank.minsheng.FileEncryptAndDecryptUtil;
import org.dromara.settlement.common.bank.minsheng.MinShengConfig;
import org.dromara.settlement.common.bank.minsheng.MinShengResponse;
import org.dromara.settlement.common.bank.minsheng.MinShengUtil;
import org.dromara.settlement.common.file.SftpUtils;
import org.dromara.settlement.domain.SysLog;
import org.dromara.settlement.mapper.SysLogMapper;
import org.dromara.settlement.mapper.TransactionLogMapper;
import org.redisson.api.RLock;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;

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

	@Autowired
	private RemoteConfigService wConfigService;// 配置

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

	@Autowired
	private SysLogMapper sysLogDao;// 日志

	private MinShengResponse request(long unitId, String funcode, String body, boolean record) {
		return request(unitId, funcode, body, record, null);
	}

	private MinShengResponse request(long unitId, String funcode, String body, boolean record, Long tranId) {
		MinShengResponse response = null;
		MinShengConfig 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<String> requsetRtn = MinShengUtil.getInstance().request(config, funcode, reqid, body);
		if (record && requsetRtn != null) {
			sysLog.setRequest(requsetRtn.getResult());
		}
		if (requsetRtn != null) {
			Result<MinShengResponse> responseRtn = MinShengUtil.getInstance().response(config, requsetRtn.getRtnData());
			if (record) {
				sysLog.setResponseTime(new Date());
			}
			if (responseRtn.hasError()) {
				log.error(responseRtn.getResult());
			}
			response = responseRtn.getRtnData();
			if (record && responseRtn != null) {
				sysLog.setResponse(responseRtn.getResult());
			}
		}
		if (sysLog.getId() != null) {
			if (record) {
				if (tranId != null) {
					sysLogDao.deleteByTranId(tranId, sysLog.getId());
				}
				sysLogDao.updateByPrimaryKeySelective(sysLog);
			} else
				sysLogDao.deleteByPrimaryKey(sysLog.getId());
		}
		return response;
	}

	private MinShengConfig getBankConfig(long unitId) {
		MinShengConfig config = new MinShengConfig();
		if (wConfigService != null && unitId > 0) {
			config.merchantNum = wConfigService.getItem(unitId, "minsheng_bank_merchantNum");
			config.systemCode = wConfigService.getItem(unitId, "minsheng_bank_systemCode");
			String uploadPhyPath = wConfigService.getUploadPhyPath(unitId) + "/";
			config.rsaCertPath = uploadPhyPath
					+ wConfigService.getItem(unitId, "minsheng_bank_rsaCertPath");
			config.rsaCertPsword = wConfigService.getItem(unitId, "minsheng_bank_rsaCertPsword");
			config.URL = wConfigService.getItem(unitId, "minsheng_bank_api");
			config.sm2CmbcPubCert = uploadPhyPath
					+ wConfigService.getItem(unitId, "minsheng_bank_sm2CmbcPubCert");
			config.sm2MhtPriCertPath = uploadPhyPath
					+ wConfigService.getItem(unitId, "minsheng_bank_sm2MhtPriCertPath");
			config.sm2MhtPriCertPsword = wConfigService.getItem(unitId, "minsheng_bank_sm2MhtPriCertPsword");
			config.CALLBACKHOST = wConfigService.getItem(unitId, "minsheng_bank_callback_host");
			config.CALLBACKPORT = wConfigService.getItem(unitId, "minsheng_bank_callback_port");
			config.CALLBACKNAME = wConfigService.getItem(unitId, "minsheng_bank_callback_name");
			config.CALLBACKPASSWORD = wConfigService.getItem(unitId, "minsheng_bank_callback_password");
			config.CALLBACKDIRECTORY = wConfigService.getItem(unitId, "minsheng_bank_callback_directory");
			config.customerSignId = wConfigService.getItem(unitId, "minsheng_bank_customerSignId");
			config.acctNo = wConfigService.getItem(unitId, "minsheng_bank_acctNo");
			if (StringUtils.isBlank(config.merchantNum)) {
				String key = "config:"+unitId;
				RedisUtils.deleteObject(key);
			}
			log.info("读取结算中心的账户配置（" + unitId + "）：" + config.merchantNum + "," + config.systemCode);
		}
		return config;
	}

	/**
	 * 创建民生银行云账户
	 * @author 张涛
	 * @date 2021年8月24日
	 * @param unitId 结算单位id
	 * @param code 云账户编号
	 * @param name 云账户名称
	 * @param prefix 云账户编号前缀
	 * @param bindAcctNo 绑卡账户号码(真实公户)
	 * @param bindAcctName 绑卡账户名称(真实公户)
	 */
	public Account createAccount(long unitId,String code,String name,String prefix,String bindAcctNo,String bindAcctName) {
		JSONObject body = new JSONObject();
		MinShengConfig config = getBankConfig(unitId);
		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;
			}
		}
		body.put("customerSignId",config.customerSignId);
		body.put("acctNo",config.acctNo);
		body.put("vacctBusiId",code);
		body.put("vacctBusiName",name);
		body.put("isApprove",0);
		body.put("isBindAcct",1);
		body.put("bindAcctNo",bindAcctNo);
		body.put("bindAcctName",bindAcctName);
		MinShengResponse res = request(unitId, "EIST_T01010401", body.toJSONString(), false);
		if (res != null && (res.getResultcode().equals("S") || "EIPSC_D_Q005000_E00010".equals(res.getRespCode()))) {
			if("EIPSC_D_Q005000_E00010".equals(res.getRespCode())){
				JSONObject old = getAccount(unitId,code);
				if (old == null){
					throw new ServiceException("民生银行子账户修改时不存在");
				}
				updateAccount(unitId,old,bindAcctNo,bindAcctName);
				res.setData(old);
			}
			Account account = new Account();
			account.setBankType("民生银行");
			account.setBankTypeName("民生银行");
			account.setBankCard(res.getData().getString("vacctNo"));
			account.setName(res.getData().getString("vacctName"));
			account.setBalance(0l);
			return account;
		}
        return null;
	}

	public void updateAccount(long unitId,JSONObject old,String bindAcctNo,String bindAcctName) {
		if(!old.getString("bindAcctNo").equals(bindAcctNo) || !old.getString("bindAcctName").equals(bindAcctName)) {
			JSONObject body = new JSONObject();
			MinShengConfig config = getBankConfig(unitId);
			body.put("customerSignId", config.customerSignId);
			body.put("vacctNo", old.getString("vacctNo"));
			body.put("operType", 2);
			body.put("bindAcctNo", bindAcctNo);
			body.put("bindAcctName", bindAcctName);
			MinShengResponse res = request(unitId, "EIST_T01000410", body.toJSONString(), false);
			if (res != null) {
				if (!res.getResultcode().equals("S")) {
					throw new ServiceException(
							res != null && StringUtils.isNotBlank(res.getResultmsg()) ? res.getResultmsg() : "修改民生银行子账户失败");
				}
			}
		}
	}

	public JSONObject getAccount(long unitId,String code) {
		JSONObject body = new JSONObject();
		MinShengConfig config = getBankConfig(unitId);
		body.put("customerSignId",config.customerSignId);
		body.put("acctNo",config.acctNo);
		body.put("bindFlag",1);
		int page = 1;
		int listSize = 0;
		do{
			listSize = 0;
			body.put("currentPage",page);
			body.put("pageSize",50);
			MinShengResponse res = request(unitId, "EIST_Q01010402", body.toJSONString(), false);
			if (res != null) {
				if (!res.getResultcode().equals("S")) {
					throw new ServiceException(
							res != null && StringUtils.isNotBlank(res.getResultmsg()) ? res.getResultmsg() : "查询民生银行子账户失败");
				}
				JSONArray resultList = res.getData().getJSONArray("resultList");
				listSize = resultList.size();
				if (listSize > 0) {
					for (int i = 0; i < listSize; i++) {
						JSONObject item = resultList.getJSONObject(i);
						if(StringUtils.isNotBlank(item.getString("vacctBusiId"))) {
							if (item.getString("vacctBusiId").equals(code)) {
								return item;
							}
						}else{
							listSize = 0;
						}
					}
					page++;
				}
			}
		}while (listSize > 0);
		return null;
	}

	/**
	 * 同步民生银行账户
	 *
	 * @author 张涛
	 * @date 2021年9月6日
	 * @param bankCard 银行卡号
	 * @return
	 */
	public AccountSyn synAccount(AccountSyn acc) {
		JSONObject body = new JSONObject();
		MinShengConfig config = getBankConfig(acc.getUnitId());
		String curDate = DateUtils.getDate();
		String synDate = null;// 最近同步日期
		if (acc.getSynTime() != null) {
			synDate = DateUtils.parseDateToString(DateUtils.YYYY_MM_DD, acc.getSynTime());
		} else {
			synDate = curDate;
		}
		body.put("customerSignId",config.customerSignId);
		body.put("vacctNo",acc.getBankCard());
		body.put("dateFrom",synDate.replace("-", ""));
		body.put("dateTo",synDate.replace("-", ""));
		boolean continueSyn = true;//是否继续同步
		int page = 1;
		int listSize = 0;
		do{
			listSize = 0;
			body.put("currentPage",page);
			body.put("pageSize",50);
			MinShengResponse res = request(acc.getUnitId(), "EIST_Q01000404", body.toJSONString(), false);
			if (res != null) {
				if (!res.getResultcode().equals("S")) {
					continueSyn = false;
					throw new ServiceException(
							res != null && StringUtils.isNotBlank(res.getResultmsg()) ? res.getResultmsg() : "同步民生银行账户失败");
				}
				JSONArray resultList = res.getData().getJSONArray("resultList");
				listSize = resultList.size();
				if (listSize > 0) {
					if(acc.getLogs() == null) {
						acc.setLogs(new ArrayList<AccountLog>());
					}
					Date curTime = new Date();
					for (int i = 0; i < listSize; i++) {
						JSONObject item = resultList.getJSONObject(i);
						if(StringUtils.isNotBlank(item.getString("transSeqNo"))) {
							AccountLog log = new AccountLog();
							log.setAccId(acc.getId());
							log.setAddBy("系统");
							log.setAddTime(curTime);
							log.setBankCard(acc.getBankCard());
							log.setBankType(acc.getBankType());
							log.setRpyacc(item.containsKey("otherAcctNo") ? item.getString("otherAcctNo") : null);
							log.setRpynam(item.containsKey("otherAcctName") ? item.getString("otherAcctName") : null);
							String trxtim = item.getString("transTime");
							String trxdat = item.containsKey("transDate") ? item.getString("transDate") : "";
							if (StringUtils.isNotBlank(trxdat)) {
								trxtim = trxdat.substring(0, 4) + "-" + trxdat.substring(4, 6) + "-"
										+ trxdat.substring(6, 8) + " " + trxtim.substring(0, 2) + ":"
										+ trxtim.substring(2, 4) + ":" + trxtim.substring(4, 6);
							} else {
								trxtim = curDate + " " + trxtim.substring(0, 2) + ":" + trxtim.substring(2, 4) + ":"
										+ trxtim.substring(4, 6);
							}
							log.setTranTime(
                                DateUtils.parseStringToDate(DateUtils.YYYY_MM_DD_HH_MM_SS, trxtim));
							log.setTrxamt(new BigDecimal(item.getString("transAmt")).multiply(new BigDecimal(100))
									.longValue());
							log.setTrxnbr(item.getString("transSeqNo"));
							String trxdir = item.getString("dcFlag");
							String narinn = null;
							if (trxdir.equals("1")) {
								log.setTrxamt(-log.getTrxamt());
								log.setTrxdir((short) 2);
							} else if (trxdir.equals("2")) {
								log.setTrxdir((short) 1);
								String postscript = item.getString("postscript");
								log.setTrxtxt(postscript);
								if (item.getString("detStat").equals("00") && StringUtils.isNotBlank(postscript) && postscript.indexOf("退汇") != -1) {
									//验证退汇的情况
									JSONObject refund = getRefund(acc, synDate, item.getString("otherAcctNo"),item.getString("otherAcctName"),item.getString("transAmt"));
									if (refund != null) {//退汇
										TransactionLog oldLog = transactionLogDao.selectBySourceBankNo(acc.getBankCard(), refund.getString("oriApplyId"));
										log.setRefundDate(refund.getString("refundTime").substring(0, 10));
										log.setRefundTrxnbr(oldLog.getOrderNo());
										narinn = oldLog.getOrderNo();
									}
								}
							}
							log.setNarinn(narinn);
							log.setBalance(acc.getBalance());
							log.setUnitId(acc.getUnitId());
							acc.getLogs().add(log);
							if (StringUtils.isNotBlank(acc.getTrxnbrs())) {
								acc.setTrxnbrs(acc.getTrxnbrs() + ",");
							}
							acc.setTrxnbrs(acc.getTrxnbrs() + "'" + log.getTrxnbr() + "'");
						}else{
							listSize = 0;
						}
					}
					page++;
				}
			}
		}while (listSize > 0);
		if(continueSyn){
			// 不是今天，或者当前没有同步完
			if (DateUtils.parseStringToDate(DateUtils.YYYY_MM_DD, synDate).getTime() < DateUtils.parseStringToDate(DateUtils.YYYY_MM_DD, curDate).getTime()) {
				//开始同步下一天的
				synDate = DateUtils.getEndDateByDays(synDate, 1);
				acc.setSynTime(DateUtils.parseStringToDate(DateUtils.YYYY_MM_DD, synDate));
				acc = synAccount(acc);
			}
			acc.setSynTime(new Date());
		}
		return acc;
	}

	/**
	 * 获取民生银行退汇信息
	 * @param acc 子账簿信息
	 * @param synDate 退汇日期
	 * @param oriPayeeAcctNo  退汇账号
	 * @param oriPayeeAcctName 退汇账号名称
	 * @param oriTransAmt 退汇金额
	 * @return
	 */
	public JSONObject getRefund(AccountSyn acc,String synDate,String oriPayeeAcctNo,String oriPayeeAcctName,String oriTransAmt) {
		JSONObject body = new JSONObject();
		MinShengConfig config = getBankConfig(acc.getUnitId());
		body.put("customerSignId",config.customerSignId);
		body.put("acctNo",config.acctNo);
		body.put("oriDraweeVacctNo",acc.getBankCard());
		body.put("dateFrom",synDate.replace("-", ""));
		body.put("dateTo",synDate.replace("-", ""));
		int page = 1;
		int listSize = 0;
		do{
			listSize = 0;
			body.put("currentPage",page);
			body.put("pageSize",50);
			MinShengResponse res = request(acc.getUnitId(), "EIST_Q01000415", body.toJSONString(), false);
			if (res != null) {
				if (!res.getResultcode().equals("S")) {
					throw new ServiceException(
							res != null && StringUtils.isNotBlank(res.getResultmsg()) ? res.getResultmsg() : "获取民生银行退汇信息失败");
				}
				JSONArray resultList = res.getData().getJSONArray("resultList");
				listSize = resultList.size();
				if (listSize > 0) {
					for (int i = 0; i < listSize; i++) {
						JSONObject item = resultList.getJSONObject(i);
						if(oriPayeeAcctNo.equals(item.getString("oriPayeeAcctNo")) && oriPayeeAcctName.equals(item.getString("oriPayeeAcctName")) && oriTransAmt.equals(item.getString("oriTransAmt"))) {
							return item;
						}else {
							listSize = 0;
						}
					}
					page++;
				}
			}
		}while (listSize > 0);
		return null;
	}

	/**
	 * 内部转账
	 * @author 张涛
	 * @date 2021年9月7日
	 * @param log
	 * @return
	 */
	public TransactionLog innerTransfer(TransactionLog log) {
		JSONObject body = new JSONObject();
		MinShengConfig config = getBankConfig(log.getUnitId());
		body.put("customerSignId",config.customerSignId);
		body.put("draweeVacctNo",log.getSourceCard());
		body.put("payeeVacctNo",log.getTargetCard());
		String amt = String.format("%.2f", log.getAmount() / 100.0);
		body.put("transAmt",amt);
		body.put("summary",log.getOrderNo());
		body.put("postscript",log.getRemark());
		MinShengResponse res = request(log.getUnitId(), "EIST_T01000406", body.toJSONString(), true, log.getId());
		if (res == null || !res.getResultcode().equals("S")) {
			this.log.error(res != null && StringUtils.isNotBlank(res.getResultmsg()) ? res.getResultmsg() : "内部转账失败");
        	log.setResult((short)-1);
    		return log;
		}
		log.setSourceBankNo(res.getReqSeq());
		log.setTargetBankNo(log.getSourceBankNo());
		log.setResult((short) 1);
		log.setReason("");
		return log;
	}

	/**
	 * 对私跨行转账
	 * @author 张涛
	 * @date 2021年9月7日
	 * @param log
	 * @return
	 */
	public TransactionLog crossPersionTransfer(TransactionLog log) {
		JSONObject body = new JSONObject();
		MinShengConfig config = getBankConfig(log.getUnitId());
		body.put("customerSignId",config.customerSignId);
		body.put("draweeVacctNo",log.getSourceCard());
		body.put("payeeAcctNo",log.getTargetCard());
		body.put("payeeAcctName",log.getTargetAccName());
		body.put("payeeAcctType",1);
		String amt = String.format("%.2f", log.getAmount() / 100.0);
		body.put("transAmt",amt);
		String remark = log.getRemark().replace("代发服务费","服务费");
		body.put("postscript",remark);
		body.put("summary",log.getOrderNo()+"〉〉"+remark);
		MinShengResponse res = request(log.getUnitId(), "EIST_T01000404", body.toJSONString(), true, log.getId());
		if (res == null || !res.getResultcode().equals("S")) {
			throw new ServiceException(
					res != null && StringUtils.isNotBlank(res.getResultmsg()) ? res.getResultmsg() : "代发转账失败");
		}
		log.setSourceBankNo(res.getData().getString("applyId"));
		log.setTargetBankNo(log.getSourceBankNo());
		log.setResult((short) 1);
		log.setReason("");
		return log;
	}

	/**
	 * 对公转账
	 *
	 * @author 张涛
	 * @date 2021年9月7日
	 * @param log
	 * @param targetKhhNo 收款人开户行行号
	 * @return
	 */
	public TransactionLog transfer(TransactionLog log,String targetKhhNo) {
		JSONObject body = new JSONObject();
		MinShengConfig config = getBankConfig(log.getUnitId());
		body.put("customerSignId",config.customerSignId);
		body.put("draweeVacctNo",log.getSourceCard());
		body.put("payeeBankNo",targetKhhNo);
		body.put("payeeAcctNo",log.getTargetCard());
		body.put("payeeAcctName",log.getTargetAccName());
		body.put("payeeAcctType",0);
		String amt = String.format("%.2f", log.getAmount() / 100.0);
		body.put("transAmt",amt);
		body.put("postscript",log.getRemark());
		body.put("summary",log.getOrderNo()+"〉〉"+log.getRemark());
		MinShengResponse res = request(log.getUnitId(), "EIST_T01000404", body.toJSONString(), true, log.getId());
		if (res == null || !res.getResultcode().equals("S")) {
			throw new ServiceException(
					res != null && StringUtils.isNotBlank(res.getResultmsg()) ? res.getResultmsg() : "转账失败");
		}
		log.setSourceBankNo(res.getData().getString("applyId"));
		log.setTargetBankNo(log.getSourceBankNo());
		log.setResult((short) 1);
		log.setReason("");
		return log;
	}

	/**
	 * 同步内部交易结果
	 *
	 * @author 张涛
	 * @date 2021年9月7日
	 * @param log
	 * @return
	 */
	public TransactionLog synInnerTransfer(TransactionLog log) {
		JSONObject body = new JSONObject();
		body.put("channelReqSeq",log.getSourceBankNo());
		MinShengResponse res = request(log.getUnitId(), "EIST_Q01000409", body.toJSONString(), false, log.getId());
		if (res != null) {
			if (!res.getResultcode().equals("S")) {
				throw new ServiceException(
						res != null && StringUtils.isNotBlank(res.getResultmsg()) ? res.getResultmsg() : "同步民生银行子账户间交易结果失败");
			}
			if (res.getData().getString("transStatus").equals("02")) {
				log.setResult((short) 2);
				log.setTranTime(new Date());
			}else if (res.getData().getString("transStatus").equals("03")) {
				log.setResult((short) -1);
				if (StringUtils.isNotEmpty(res.getData().getString("postscript"))) {
					log.setReason(res.getData().getString("postscript"));
				}
				if(StringUtils.isNotEmpty(log.getReason())){
					log.setReason(log.getReason() + "、");
				}
				if (StringUtils.isNotEmpty(res.getData().getString("summary"))) {
					log.setReason(log.getReason() + res.getData().getString("summary"));
				}
				log.setTranTime(new Date());
			}
		}
		return log;
	}

	/**
	 * 同步交易结果
	 *
	 * @author 张涛
	 * @date 2021年9月7日
	 * @param log
	 * @return
	 */
	public TransactionLog synTransfer(TransactionLog log) {
		JSONObject body = new JSONObject();
		body.put("applyId",log.getSourceBankNo());
		MinShengResponse res = request(log.getUnitId(), "EIST_Q01000405", body.toJSONString(), false, log.getId());
		if (res != null) {
			if (!res.getResultcode().equals("S")) {
				throw new ServiceException(
						res != null && StringUtils.isNotBlank(res.getResultmsg()) ? res.getResultmsg() : "同步民生银行对私交易结果失败");
			}
			if (res.getData().getString("transStatus").equals("02")) {
				log.setResult((short) 2);
				log.setTranTime(new Date());
			}else if (res.getData().getString("transStatus").equals("03")) {
				log.setResult((short) 3);
				log.setReason(res.getData().getString("retMsg"));
				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, InterruptedException {
		String callBackFile = "";
		String synDate = DateUtils.parseDateToString(DateUtils.YYYYMMDD,log.getTranTime());
		String lockKey = "minsheng:"+log.getUnitId()+":"+synDate;
        RLock lock = RedisUtils.getClient().getLock(lockKey);
		if(lock.tryLock(1000*60*30, TimeUnit.MILLISECONDS)) {
			JSONObject body = new JSONObject();
			MinShengConfig config = getBankConfig(log.getUnitId());
			if(StringUtils.isBlank(log.getPayReceiptId())) {
				body.put("customerSignId",config.customerSignId);
				body.put("transSeqNo",log.getTargetBankNo());
				body.put("transDate",synDate);
				body.put("acctNo",config.acctNo);
				MinShengResponse res = request(log.getUnitId(), "EIST_T01010301", body.toJSONString(), false);
				if (res != null) {
					if (res.getResultcode().equals("S")) {
						TransactionLog upd = new TransactionLog();
						upd.setId(log.getId());
						upd.setPayReceiptId(res.getReqSeq());
						transactionLogDao.updateByPrimaryKeySelective(upd);
						log.setPayReceiptId(upd.getPayReceiptId());
					}
				}
			}
			if(StringUtils.isNotBlank(log.getPayReceiptId())) {
				body = new JSONObject();
				body.put("channelReqSeq",log.getPayReceiptId());
				MinShengResponse res = request(log.getUnitId(), "EIST_Q01010302", body.toJSONString(), false);
				if (res != null) {
					if (res.getResultcode().equals("S")) {
						if("3".equals(res.getData().getString("status"))){
							TransactionLog upd = new TransactionLog();
							upd.setId(log.getId());
							upd.setPayReceiptId("");
							transactionLogDao.updateByPrimaryKeySelective(upd);
						}else if("2".equals(res.getData().getString("status"))) {
							String uploadPhyPath = wConfigService.getUploadPhyPath(log.getUnitId()) + "/";
							String flName = res.getData().getString("fileName");
							String saveFile = uploadPhyPath + config.acctNo + flName;
							File saveFileObj = new File(saveFile);
							if (!saveFileObj.exists()) {
								saveFileObj = null;
								SftpUtils sftpUtils = new SftpUtils();
								ChannelSftp sftp = null;
								try {
									String directory = "/";
									if(StringUtils.isNotBlank(config.CALLBACKDIRECTORY)){
										directory += config.CALLBACKDIRECTORY + "/";
									}
									sftp = sftpUtils.connect(config.CALLBACKHOST, Integer.parseInt(config.CALLBACKPORT), config.CALLBACKNAME, config.CALLBACKPASSWORD);
									if (sftpUtils.isExist(directory, flName, sftp)) {
										String downloadFileName = "encrypt"+config.acctNo + flName;
										if (sftpUtils.download(directory, flName, uploadPhyPath + downloadFileName, sftp)) {
											FileEncryptAndDecryptUtil.decryptFile(downloadFileName,uploadPhyPath,config.sm2MhtPriCertPath,config.sm2MhtPriCertPsword,saveFile);
											saveFileObj = new File(saveFile);
											if(saveFileObj.exists()) {
												sftpUtils.delete(directory, flName, sftp);
											}else{
												saveFileObj = null;
											}
											new File(uploadPhyPath + downloadFileName).delete();
										}
									}
								} catch (Exception e) {
									// TODO 自动生成的 catch 块
									this.log.error("下载民生银行交易回置单文件出错（" + flName + "）：", e);
								} finally {
									sftpUtils.disconnect(config.CALLBACKHOST, sftp);
								}
							}
							if (saveFileObj != null) {
								String uploadNetPath = wConfigService.getUploadNetPath(log.getUnitId());
								//回执单列表
								List<TransactionLog> callBackFileList = new ArrayList<TransactionLog>();
								TransactionLog callBack = new TransactionLog();
								callBack.setTargetBankNo(log.getTargetBankNo());
								callBack.setPayReceipt(saveFile.replace(uploadPhyPath, uploadNetPath));
								callBackFileList.add(callBack);
								transactionLogDao.updatePayReceipt("民生银行", callBackFileList);
								callBackFile = callBack.getPayReceipt();
							}
						}
					}
				}
			}
            lock.unlock();
		}
		return callBackFile;
	}

	/**
	 * 获取交易流水号
	 *
	 * @author 张涛
	 * @date 2021年9月22日
	 * @param log
	 * @param trsseq 断点续传编号
	 * @return
	 */
	public String getTransferBankNo(TransactionLog log) {
		return log.getSourceBankNo().substring(0,23);
		/*if(log.getTranTime() != null) {
			//同步到结果的日期（结束日期）
			String synDate = DateTimeUtils.parseDateToString(DateTimeUtils.pattern_yyyy_MM_dd, log.getTranTime());
			//开始日期（解决同步到结果的日期与银行出结果的时间差问题）
			String startDate = DateTimeUtils.parseDateToString(DateTimeUtils.pattern_yyyy_MM_dd, DateTimeUtils.addOneHour(log.getTranTime(), -1));

			JSONObject body = new JSONObject();
			MinShengConfig config = getBankConfig(log.getUnitId());
			body.put("customerSignId",config.customerSignId);
			body.put("vacctNo",log.getSourceCard());
			body.put("dateFrom",startDate.replace("-", ""));
			body.put("dateTo",synDate.replace("-", ""));
			int page = 1;
			int listSize = 0;
			do{
				listSize = 0;
				body.put("currentPage",page);
				body.put("pageSize",50);
				MinShengResponse res = request(log.getUnitId(), "EIST_Q01000404", body.toJSONString(), false);
				if (res != null) {
					if (!res.getResultcode().equals("S")) {
						throw new ServiceException(
								res != null && StringUtils.isNotBlank(res.getResultmsg()) ? res.getResultmsg() : "同步民生银行交易流水号失败");
					}
					JSONArray resultList = res.getData().getJSONArray("resultList");
					listSize = resultList.size();
					if (listSize > 0) {
						for (int i = 0; i < listSize; i++) {
							JSONObject item = resultList.getJSONObject(i);
							String summary = item.getString("summary");
							if (summary.indexOf("〉〉") != -1) {
								String[] summaryArr = summary.split("〉〉");
								if (summaryArr[0].equals(log.getOrderNo())){
									return item.getString("transSeqNo").substring(0,23);
								}
							}
						}
						page++;
					}
				}
			}while (listSize > 0);
		}
		return "";*/
	}
}
