package com.liquidnet.service.reconciliation.strategy.funddata.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.liquidnet.commons.lang.util.BeanUtil;
import com.liquidnet.commons.lang.util.DateUtil;
import com.liquidnet.service.account.common.FinConstants;
import com.liquidnet.service.adam.constant.AdamFundingConstants;
import com.liquidnet.service.adam.constant.AdamTransactionConstants;
import com.liquidnet.service.api.sequence.feign.FeignSequenceClient;
import com.liquidnet.service.reconciliation.constant.CurrencyCodeEnum;
import com.liquidnet.service.reconciliation.constant.ReconConstants;
import com.liquidnet.service.reconciliation.constant.ReconConstants.BankChannelEnum;
import com.liquidnet.service.reconciliation.constant.ReconConstants.BatchStatusEnum;
import com.liquidnet.service.reconciliation.entity.LrAccountCheckBatch;
import com.liquidnet.service.reconciliation.entity.LrFundflowLiquidnetWallet;
import com.liquidnet.service.reconciliation.entity.wallet.FinWlN07;
import com.liquidnet.service.reconciliation.service.ILrFundflowLiquidnetWalletService;
import com.liquidnet.service.reconciliation.service.wallet.IFinWlN07Service;
import com.liquidnet.service.reconciliation.strategy.funddata.IGetFundDataStrategy;
import com.liquidnet.service.reconciliation.strategy.funddata.annotation.StrategyGetFundDataHandler;
import com.liquidnet.service.reconciliation.vo.ReconciliationEntityVo;
import lombok.extern.slf4j.Slf4j;
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.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author AnJiabin <jiabin.an@lightnet.io>
 * @version V1.0
 * @Description: liquidnet-wallet
 * @class: LiquidnetWalletGetFundDataStrategyImpl
 * @Package com.liquidnet.service.reconciliation.strategy.transtype.impl
 * @Copyright: LightNet @ Copyright (c) 2020
 * @date 2020/10/27 14:58
 */
@Slf4j
@Component
@StrategyGetFundDataHandler(BankChannelEnum.LIQUIDNET_WALLET)
public class GetFundDataStrategyLiquidnetWalletImpl implements IGetFundDataStrategy {
    @Autowired
    private FeignSequenceClient feignSequenceClient;

    @Autowired
    private ILrFundflowLiquidnetWalletService lrFundflowLiquidnetWalletService;

    @Autowired
    private IFinWlN07Service finWlN07Service;

    @Override
    public List<ReconciliationEntityVo> getTransFundData(LrAccountCheckBatch batch, String bankChannel, Date billDate) {
        //查询条件
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String billDateStr = sdf.format(billDate);
        log.info("getTransFundData bankChannel:{} batchNo:{} billDate:{} ",bankChannel,batch.getBatchNo(),billDateStr);

        LambdaQueryWrapper<FinWlN07> wrapper = new LambdaQueryWrapper<>();
        if(!StringUtils.isEmpty(billDate)){
            try {
                wrapper.ge(FinWlN07::getCreateTime,DateUtil.parse(billDateStr,DateUtil.DATE_SMALL_STR));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        if(!StringUtils.isEmpty(billDate)){
            try {
                wrapper.lt(FinWlN07::getCreateTime, DateUtil.addDay(DateUtil.parse(billDateStr,DateUtil.DATE_SMALL_STR),1));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        wrapper.in(FinWlN07::getTransStatus, FinConstants.TxStatus.SUCCESS.getVal());
        //目前只查已经确认的资金账户信息
        wrapper.in(FinWlN07::getTransType,FinConstants.TransType.CREDIT_CONFIRM.name(),FinConstants.TransType.DEBIT_CONFIRM.name());
        List<FinWlN07> finWlN07List = finWlN07Service.list(wrapper);


        //设置batchNo
        List<LrFundflowLiquidnetWallet>  fundFlowList = new ArrayList<>();
        finWlN07List.stream().forEach(record ->{
            LrFundflowLiquidnetWallet fundBean = new LrFundflowLiquidnetWallet();
            BeanUtil.copy(record,fundBean);
            fundBean.setBatchNo(batch.getBatchNo());
            fundBean.setCurrency(CurrencyCodeEnum.getDescByCode(record.getWalletNo().substring(0,4)));
            fundBean.setTransTypeOriginal(record.getTransType());
            if(fundBean.getTracingType().equalsIgnoreCase(AdamTransactionConstants.TypeEnum.FUNDING.getCode())){
                fundBean.setTransType(ReconConstants.TransTypeEnum.RECHARGE.getCode());
            }else if(fundBean.getTracingType().equalsIgnoreCase(AdamTransactionConstants.TypeEnum.PAYOUT.getCode())){
                fundBean.setTransType(ReconConstants.TransTypeEnum.PAYOUT.getCode());
            }else if(fundBean.getTracingType().equalsIgnoreCase(AdamTransactionConstants.TypeEnum.FX_CONVERSION.getCode())){
                fundBean.setTransType(ReconConstants.TransTypeEnum.EXCHANGE.getCode());
            }
            fundFlowList.add(fundBean);
        });

        //保存批次及明细信息
        lrFundflowLiquidnetWalletService.saveBatch(fundFlowList);

        //转换为公共对象
        List<ReconciliationEntityVo> reconList = new ArrayList<>();
        // 交易笔数、金额、手续费累计
        int totalCount = 0;
        BigDecimal totalAmount = BigDecimal.ZERO;
        BigDecimal totalFee = BigDecimal.ZERO;

        for(LrFundflowLiquidnetWallet fundRecord:fundFlowList){
            // 统计
            totalCount++;
            totalAmount = totalAmount.add(fundRecord.getAmount());
            totalFee = totalFee.add(BigDecimal.ZERO);

            ReconciliationEntityVo reconVo = ReconciliationEntityVo.getNew();
            reconVo.setId(feignSequenceClient.nextId().toString());
            reconVo.setBankChannel(BankChannelEnum.LIQUIDNET_WALLET.getCode());
            reconVo.setBatchNo(batch.getBatchNo());
            reconVo.setBillDate(billDate);
//            reconVo.setOrderNo();
            reconVo.setTransactionId(fundRecord.getTracingNo());
            reconVo.setTransType(fundRecord.getTransType());
            reconVo.setCurrency(fundRecord.getCurrency());
            reconVo.setAmount(fundRecord.getAmount());
            reconVo.setCostFee(BigDecimal.ZERO);
//            reconVo.setRefundAmount();
//            reconVo.setTradeStatus();
//            reconVo.setRefTransId();
//            reconVo.setCheckResult();
//            reconVo.setOrderTime();
//            reconVo.setTransDate();
//            reconVo.setTransTime();
//            reconVo.setBankOrderNo();
//            reconVo.setBankTrxNo();
            reconList.add(reconVo);
        }

        batch.setBankTradeCount(totalCount);
        batch.setBankTradeAmount(totalAmount);
        batch.setBankRefundAmount(BigDecimal.ZERO);
        batch.setBankFee(totalFee);
        return reconList;
    }
}
