package com.liquidnet.service.reconciliation.biz;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.liquidnet.commons.lang.util.DateUtil;
import com.liquidnet.service.reconciliation.constant.ReconConstants.BatchStatusEnum;
import com.liquidnet.service.reconciliation.constant.ReconConstants.MistakeHandleStatusEnum;
import com.liquidnet.service.reconciliation.constant.ReconConstants.MistakeTypeEnum;
import com.liquidnet.service.reconciliation.entity.LrAccountCheckBatch;
import com.liquidnet.service.reconciliation.entity.LrAccountCheckMistake;
import com.liquidnet.service.reconciliation.entity.LrAccountCheckMistakeScratchPool;
import com.liquidnet.service.reconciliation.service.ILrAccountCheckBatchService;
import com.liquidnet.service.reconciliation.service.ILrAccountCheckMistakeScratchPoolService;
import com.liquidnet.service.reconciliation.service.core.ILrAccountCheckTransactionService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author AnJiabin <jiabin.an@lightnet.io>
 * @version V1.0
 * @Description: 对账验证biz，(检查是否已经对过账).
 * @class: ReconciliationValidateBiz
 * @Package com.liquidnet.service.reconciliation.biz
 * @Copyright: LightNet @ Copyright (c) 2020
 * @date 2020/10/21 14:20
 */
@Slf4j
@Component("reconciliationValidateBiz")
public class ReconciliationValidateBiz {

	@Autowired
	private ILrAccountCheckBatchService rpAccountCheckBatchService;
	@Autowired
	private ILrAccountCheckTransactionService rpAccountCheckTransactionService;
	@Autowired
	private ILrAccountCheckMistakeScratchPoolService rpAccountCheckMistakeScratchPoolService;

	/**
	 * 判断某支付方式某天是否对过账，避免重复对账
	 *
	 * @param interfaceCode
	 *            支付方式
	 * @param billDate
	 *            账单日
	 * @return
	 */
	public Boolean isChecked(String interfaceCode, Date billDate) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String billDateStr = sdf.format(billDate);
		log.info("检查,支付方式[" + interfaceCode + "],订单日期[" + billDateStr + "]");

		//查询条件
		LambdaQueryWrapper<LrAccountCheckBatch> wrapper = new LambdaQueryWrapper<>();
//		try {
//			wrapper.eq(!StringUtils.isEmpty(billDate),LrAccountCheckBatch::getBillDate,DateUtil.parse(billDateStr,DateUtil.DATE_SMALL_STR));
//		} catch (ParseException e) {
//			e.printStackTrace();
//		}
		if(!StringUtils.isEmpty(billDate)){
			try {
				wrapper.ge(LrAccountCheckBatch::getBillDate,DateUtil.parse(billDateStr,DateUtil.DATE_SMALL_STR));
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		if(!StringUtils.isEmpty(billDate)){
			try {
				wrapper.lt(LrAccountCheckBatch::getBillDate, DateUtil.addDay(DateUtil.parse(billDateStr,DateUtil.DATE_SMALL_STR),1));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		wrapper.eq(!StringUtils.isEmpty(interfaceCode),LrAccountCheckBatch::getBankType, interfaceCode);
		wrapper.in(LrAccountCheckBatch::getStatus,BatchStatusEnum.SUCCESS.name());
		log.info("wrapper : {}",wrapper.toString());
		List<LrAccountCheckBatch> list = rpAccountCheckBatchService.list(wrapper);
		if (list.isEmpty()) {
			return false;
		}
		return true;
	}

	/**
	 * 如果缓冲池中有三天前的数据就清理掉并记录差错
	 */
	public void validateScratchPool() {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		String dateStr = sdf.format(DateUtil.addDay(new Date(), -3));
		// 查询是否有创建时间是三天前的数据
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("create_time", dateStr);
		List<LrAccountCheckMistakeScratchPool> list = rpAccountCheckMistakeScratchPoolService.listByMap(paramMap);
		List<LrAccountCheckMistake> mistakeList = null;
		// 如果有数据
		if (!list.isEmpty()) {
			mistakeList = new ArrayList<LrAccountCheckMistake>();
			for (LrAccountCheckMistakeScratchPool scratchRecord : list) {
				// 创建差错记录
				LrAccountCheckMistake mistake = new LrAccountCheckMistake();
				mistake.setBatchNo(scratchRecord.getBatchNo());
				mistake.setBillDate(scratchRecord.getBillDate());
				mistake.setErrType(MistakeTypeEnum.BANK_MISS.name());
				mistake.setHandleStatus(MistakeHandleStatusEnum.NOHANDLE.name());
				mistake.setBankType(scratchRecord.getPayWayCode());

				mistake.setOrderNo(scratchRecord.getMerchantOrderNo());
				mistake.setTradeTime(scratchRecord.getPaySuccessTime());
				mistake.setTrxNo(scratchRecord.getTrxNo());
				mistake.setOrderAmount(scratchRecord.getOrderAmount());
				mistake.setRefundAmount(scratchRecord.getSuccessRefundAmount());
				mistake.setTradeStatus(scratchRecord.getStatus());
				mistake.setFee(scratchRecord.getPlatCost());
				mistakeList.add(mistake);
			}

			rpAccountCheckTransactionService.removeDateFromPool(list, mistakeList);

		}

	}
}
