package org.dromara.payment.sys.service.impl;

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

import org.apache.dubbo.config.annotation.DubboReference;
import org.dromara.common.core.exception.ServiceException;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.payment.sys.domain.AccAccounts;
import org.dromara.payment.sys.mapper.AccAccountsMapper;
import org.dromara.settlement.api.RemoteAccountService;
import org.dromara.settlement.api.RemoteConfigService;
import org.dromara.settlement.api.domain.Account;
import org.dromara.settlement.api.domain.Result;
import org.dromara.settlement.api.domain.UnitConfDetail;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


@Service
public class BankAccountServiceTransactionImpl
{
	private static final Logger log = LoggerFactory.getLogger(BankAccountServiceTransactionImpl.class);

	@Autowired
	private AccAccountsMapper accountsDao;//银行账户dao

	@DubboReference
	private RemoteAccountService accountService;//银行账户

	@DubboReference
	private RemoteConfigService wConfigService;// 配置

	@Transactional
	public void useAccount(AccAccounts acc) {
		AccAccounts exist = accountsDao.selectByCardAndType(acc.getBankCard(), acc.getBankType());
		if (exist == null) {
			throw new ServiceException("账户不存在");
		}
		if (exist.getIsUse() == 1) {
			throw new ServiceException("账户已被使用");
		}
		AccAccounts upd = new AccAccounts();
		upd.setId(exist.getId());
		upd.setIsUse(1);
		upd.setUseObj(acc.getUseObj());
		upd.setUseObjId(acc.getUseObjId());
		upd.setUseObjName(acc.getUseObjName());
		upd.setBankArgNo(acc.getBankArgNo());
		Integer num = accountsDao.useAccount(upd);
		if (num == 0) {
			throw new ServiceException("账户已被使用");
		}
	}

	@Transactional
	public void updateAccountArgNo(AccAccounts acc) {
		String bankType = "交通银行";
    	if(acc.getBankType().equals(bankType)) {
	    	Map<String, String> configMap = existsBank(acc.getSydId(), bankType);
			if (configMap != null) {
				AccAccounts exist = accountsDao.selectByCardAndType(acc.getBankCard(), acc.getBankType());
				if (exist == null) {
					throw new ServiceException("账户不存在");
				}
				Account bankAcc = new Account();
				bankAcc.setBankType(bankType);
				bankAcc.setBankCard(acc.getBankCard());
				bankAcc.setUnitId(acc.getSydId());
				bankAcc.setName(acc.getBankAccName());
				bankAcc.setBankArgNo(acc.getBankArgNo());
				bankAcc.setType((short)1);//1:云账户
				Result<Account> accountRtn = accountService.addAccount(bankAcc);
				if (accountRtn.hasError() || accountRtn.hasTip() || accountRtn.getRtnData() == null) {
					throw new RuntimeException("修改交通银行虚拟户协议编号失败："+accountRtn.getResult());
				}
				AccAccounts upd = new AccAccounts();
				upd.setId(exist.getId());
				upd.setBankArgNo(acc.getBankArgNo());
				accountsDao.updateByPrimaryKeySelective(upd);
			}
    	}
	}

	/**
	 * 验证银行类型是否可用
	 * @author 张涛
	 * @date 2022年7月8日
	 * @param sydId 结算中心id
	 * @param bankType 银行类型
	 * @return
	 */
	public Map<String, String> existsBank(long sydId,String bankType) {
		String bankClass = "";
		if (bankType.equals("招商银行")) {
			bankClass = "settlement.zhaoshang";
		} else if (bankType.equals("交通银行")) {
			bankClass = "settlement.jiaotong";
		} else if (bankType.equals("支付宝")) {
			bankClass = "settlement.zhifubao";
		} else if (bankType.equals("民生银行")) {
			bankClass = "settlement.minsheng";
		}
		Result<List<UnitConfDetail>> bankConfigRtn = wConfigService.getConfDetailByUnit(sydId, bankClass);
		if (bankConfigRtn.hasError()) {
			throw new RuntimeException(bankConfigRtn.getResult());
		}
		boolean exists = false;
		//配置明细
		Map<String, String> configMap = new HashMap<String, String>();
		if (bankConfigRtn.getRtnData() != null) {
			for (UnitConfDetail ucd : bankConfigRtn.getRtnData()) {
				if(bankType.equals("招商银行")) {
					if (ucd.getConf_item().equals("zhaoshang_prikey") && StringUtils.isNotBlank(ucd.getConf_value())) {
						exists = true;
					}
				}else if (bankType.equals("交通银行")) {
					if (ucd.getConf_item().equals("jiaotong_super_acc") && StringUtils.isNotBlank(ucd.getConf_value())) {
						exists = true;
					}
				}else if (bankType.equals("支付宝")) {
					if (ucd.getConf_item().equals("zhifubao_bank_appid") && StringUtils.isNotBlank(ucd.getConf_value())) {
						exists = true;
					}
				} else if (bankType.equals("民生银行")) {
					if (ucd.getConf_item().equals("minsheng_bank_merchantNum") && StringUtils.isNotBlank(ucd.getConf_value())) {
						exists = true;
					}
				}
				configMap.put(ucd.getConf_item(), ucd.getConf_value());
			}
		}
		return exists ? configMap : null;
	}

	/**
	 * 创建虚拟银行账号
	 * @author 张涛
	 * @date 2021年8月18日
	 * @param unitId 税源地id
	 * @param userId 用户id（单位id或自雇者id或税源地id）
	 * @param userName 用户名称（单位名称或自雇者姓名或税源地名称）
	 * @return
	 */
	public AccAccounts addAccount(long unitId,Long userId,String userName,String bankType){
		Result<Account> accountRtn = accountService.addAccount(unitId, 1,userId,userName,bankType,null);
		if (accountRtn.hasError()) {
			throw new RuntimeException(accountRtn.getResult());
		}else if (accountRtn.hasTip()) {
			throw new ServiceException(accountRtn.getResult());
		}
		AccAccounts newAcc = new AccAccounts();
		newAcc.setSydId(unitId);
		newAcc.setBankType(accountRtn.getRtnData().getBankType());
		newAcc.setBankCard(accountRtn.getRtnData().getBankCard());
		newAcc.setBankAccName(accountRtn.getRtnData().getName());
		accountsDao.insertSelective(newAcc);
		return newAcc;
	}
}
