package org.dromara.settlement.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alipay.api.internal.util.AlipaySignature;
import com.fasterxml.jackson.core.type.TypeReference;
import org.dromara.common.core.utils.DateUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.settlement.api.domain.Account;
import org.dromara.settlement.api.domain.AccountLog;
import org.dromara.settlement.api.domain.AccountSyn;
import org.dromara.settlement.api.domain.SignZhifubao;
import org.dromara.settlement.common.bank.zhifubao.ZhiFuBaoConfig;
import org.dromara.settlement.mapper.AccountMapper;
import org.dromara.settlement.mapper.AccountSynMapper;
import org.dromara.settlement.mapper.SignZhifubaoMapper;
import org.dromara.settlement.service.IPublicService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.*;

@Service("publicServiceImpl")
public class PublicServiceImpl implements IPublicService {
	private static final Logger log = LoggerFactory.getLogger(PublicServiceImpl.class);

	@Autowired
	private ZhiFuBaoServiceImpl zhiFuBaoServiceImpl;

	@Autowired
	private AccountServiceTransactionImpl transactionImpl;

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

	@Autowired
	private AccountMapper accountDao;//银行账户dao

	@Autowired
	private AccountSynMapper accountSynDao;//银行账户同步dao

	@Override
	public String zfbNotify(Map<String, String> paramss) {
		// TODO 自动生成的方法存根
		String ret = "success";
		try {
			if(paramss.size() > 0 && paramss.containsKey("app_id")) {
				SignZhifubao sign = signZhifubaoDao.selectByAppId(paramss.get("app_id"));
				if(sign != null) {
					long unitId = sign.getUnitId();
					ZhiFuBaoConfig config = zhiFuBaoServiceImpl.getBankConfig(unitId);
					if(AlipaySignature.certVerifyV1(paramss, config.alipayCertPublicKey, "UTF-8", "RSA2")) {
						Map<String, String> params = JSONObject.parseObject(paramss.get("biz_content"), Map.class);
						if(params.containsKey("payee_identity_type") && params.get("payee_identity_type").equals("ACCOUNT_BOOK_ID")) {//记账本
							Account acc = accountDao.selectByArgNoAndType(unitId, "支付宝", params.get("payee_identity"));
							if (acc == null) {
								log.info("银行账户的支付宝协议编号["+params.get("payee_identity")+"]不存在，延迟接收支付宝充值通知");
								return "fail";
							}
							AccountSyn syn = accountSynDao.selectByPrimaryKey(acc.getId());
							if (syn == null) {
								syn = new AccountSyn();
								syn.setId(acc.getId());
								syn.setUnitId(acc.getUnitId());
								syn.setType(acc.getType());
								syn.setBankCard(acc.getBankCard());
								syn.setBankType(acc.getBankType());
								syn.setType(acc.getType());
								syn.setSynLock((byte)0);
								accountSynDao.insertSelective(syn);
							}
							syn.setBalance(acc.getBalance());
							syn.setAddAmount(0l);
							syn.setReductionAmount(0l);
							syn.setTrxnbrs("");
							AccountLog log = new AccountLog();
							log.setAccId(syn.getId());
							log.setAddBy("系统");
							log.setAddTime(new Date());
							log.setBankCard(syn.getBankCard());
							log.setBankType(syn.getBankType());
							log.setRpyacc(params.get("payer_identity"));
							log.setRpynam(params.get("payer_name"));
							log.setTranTime(log.getAddTime());
							log.setTrxamt(new BigDecimal(params.get("amount")).multiply(new BigDecimal(100))
									.longValue());
							log.setTrxnbr(params.get("order_no"));
							log.setTrxdir((short) 1);
							log.setBalance(syn.getBalance());
							log.setUnitId(syn.getUnitId());
							syn.setLogs(new ArrayList<AccountLog>());
							syn.getLogs().add(log);
							if (StringUtils.isNotBlank(syn.getTrxnbrs())) {
								syn.setTrxnbrs(syn.getTrxnbrs() + ",");
							}
							syn.setTrxnbrs(syn.getTrxnbrs() + "'" + log.getTrxnbr() + "'");
							transactionImpl.saveAccountLog(syn);
						}
					}
				}
			}
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			log.error("支付宝充值通知解析出错（"+JSONObject.toJSONString(paramss)+"）：",e);
			ret = "fail";
		}
		return ret;
	}

	@Override
	public String signNotify(Map<String, String> paramss) {
		// TODO 自动生成的方法存根
		Map<String, String> params = null;
		String ret = "success";
		try {
			//params = getParamMap(request);
			if(params.size() > 0) {
				long unitId = Long.parseLong(params.get("external_agreement_no"));
				ZhiFuBaoConfig config = zhiFuBaoServiceImpl.getBankConfig(unitId);
				if(AlipaySignature.certVerifyV1(params, config.alipayCertPublicKey, "UTF-8", "RSA2")) {
					SignZhifubao upd = new SignZhifubao();
					upd.setAgreementNo(params.get("agreement_no"));
					upd.setAlipayLogonId(params.get("alipay_logon_id"));
					upd.setAppId(params.get("app_id"));
					upd.setSignTime(DateUtils.parseStringToDate(DateUtils.YYYY_MM_DD_HH_MM_SS, params.get("sign_time")));
					upd.setStatus(params.get("status"));
					upd.setUnitId(unitId);
					upd.setValidTime(DateUtils.parseStringToDate(DateUtils.YYYY_MM_DD_HH_MM_SS, params.get("valid_time")));
					upd.setEditTime(new Date());
					upd.setAddTime(upd.getEditTime());
					Integer row = signZhifubaoDao.insertSelective(upd);
					if (row == 0) {
						upd.setAddTime(null);
						signZhifubaoDao.updateByAppId(upd);
					}
				}
			}
		} catch (Exception e) {
			// TODO 自动生成的 catch 块
			log.error("支付宝签约通知解析出错（"+JSONObject.toJSONString(params)+"）：",e);
			ret = "fail";
		}
		return ret;
	}
}
