package org.dromara.settlement.service.impl;

import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

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.common.BussinessVariable;
import org.dromara.settlement.mapper.AccountLogMapper;
import org.dromara.settlement.mapper.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;



@Service
public class AccountServiceTransactionImpl
{
	@Autowired
	private AccountMapper accountDao;//银行账户dao

	@Autowired
	private AccountLogMapper accountLogDao;//银行账户同步明细dao

	@Transactional
	public void saveAccountLog(AccountSyn syn) {
		// TODO 自动生成的方法存根
		if (syn.getLogs() != null && syn.getLogs().size() > 0) {
			Collections.sort(syn.getLogs(),new Comparator<AccountLog>() {
	            @Override
	            public int compare(AccountLog o1, AccountLog o2) {
	                // 返回值为int类型，大于0表示正序，小于0表示逆序
	                if(o2.getTranTime().getTime() > o1.getTranTime().getTime()) {
	                	return -1;
	                }else if (o2.getTranTime().getTime() < o1.getTranTime().getTime()) {
	                	return 1;
					}else {
						return 0;
					}
	            }
	        });
			String beginTime = DateUtils.parseDateToString(DateUtils.YYYY_MM_DD_HH_MM_SS, syn.getLogs().get(0).getTranTime());
		    String endTime = DateUtils.parseDateToString(DateUtils.YYYY_MM_DD_HH_MM_SS, syn.getLogs().get(syn.getLogs().size()-1).getTranTime());
			List<String> exists = accountLogDao.selectTrxnbrByAccId(syn.getId(), syn.getTrxnbrs(), beginTime, endTime);
			Iterator<AccountLog> iter = syn.getLogs().iterator();
			//key:银行交易流水号,value:交易记录
			Map<String,AccountLog> refundTrxnbrs = new HashMap<String, AccountLog>();
			String refundBeginTime = null;//退票记录所属开始时间
			String refundEndTime = null;//退票记录所属结束时间
			boolean balanceChange = false;//账户余额是否变动
			while (iter.hasNext()) {
				AccountLog log = (AccountLog) iter.next();
				if (exists.contains(log.getTrxnbr())) {
					iter.remove();
				}else {
					if (log.getTrxdir().intValue() == 1) {//收入
						syn.setBalance(syn.getBalance()+log.getTrxamt());
					}else if (log.getTrxdir().intValue() == 2) {//支出,Trxamt是复数
						syn.setBalance(syn.getBalance()+log.getTrxamt());
					}
					log.setBalance(syn.getBalance());
					balanceChange = true;
					if (StringUtils.isNotBlank(log.getRefundTrxnbr())) {
						refundTrxnbrs.put(log.getRefundTrxnbr(),log);
						if (StringUtils.isBlank(refundBeginTime) || DateUtils.parseStringToDate(DateUtils.YYYY_MM_DD_HH_MM_SS, log.getRefundDate()+" 00:00:00").getTime() <
								DateUtils.parseStringToDate(DateUtils.YYYY_MM_DD_HH_MM_SS, refundBeginTime).getTime()) {
							refundBeginTime = log.getRefundDate()+" 00:00:00";
						}
						if (StringUtils.isBlank(refundEndTime) || DateUtils.parseStringToDate(DateUtils.YYYY_MM_DD_HH_MM_SS, log.getRefundDate()+" 23:59:59").getTime() >
                            DateUtils.parseStringToDate(DateUtils.YYYY_MM_DD_HH_MM_SS, refundEndTime).getTime()) {
							refundEndTime = log.getRefundDate()+" 23:59:59";
						}
					}
				}
			}
			if (refundTrxnbrs.size() > 0) {
				StringBuffer sf = new StringBuffer("");
				for (String code : refundTrxnbrs.keySet()) {
					if ("".equals(sf.toString())) {
						sf.append("'" + code + "'");
					} else {
						sf.append("," + "'" + code + "'");
					}
				}
				List<AccountLog> refundTrxnbrList = accountLogDao.selectNarinnByAccId(syn.getId(), sf.toString(), refundBeginTime, refundEndTime);
				for (AccountLog l : refundTrxnbrList) {
					refundTrxnbrs.get(l.getTrxnbr()).setNarinn(l.getNarinn());
				}
			}
			int batchSize = BussinessVariable.getMaxSizeOfInsert(17);//每批插入条数
			int batchNum = (int)Math.ceil(syn.getLogs().size()/(double)batchSize);
			for (int i = 0,total = syn.getLogs().size(); i < batchNum; i++) {
				int fromIndex = i * batchSize;//list中开始索引
				int toIndex = fromIndex + batchSize;//list中结束索引
				if(toIndex >= total)
					toIndex = total;
				accountLogDao.insertAll(syn.getLogs().subList(fromIndex, toIndex));
			}
			if(balanceChange) {
				Account accUpd = new Account();
				accUpd.setId(syn.getId());
				accUpd.setBalance(syn.getBalance());
				accUpd.setEditTime(new Date());
				accountDao.updateByPrimaryKeySelective(accUpd);
			}
		}
	}
}
