package com.clx.performance.event;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.json.JSONUtil;
import com.clx.performance.component.OrderChildLoanComponent;
import com.clx.performance.dao.loan.OrderChildLoanRetryRecordDao;
import com.clx.performance.dao.loan.OwnerLoanAccountRunningWaterRecordDao;
import com.clx.performance.dao.loan.OwnerRepaymentDao;
import com.clx.performance.dao.settle.SettlementDriverDao;
import com.clx.performance.dao.settle.SettlementDriverDetailDao;
import com.clx.performance.dao.settle.SettlementOwnerDetailDao;
import com.clx.performance.dto.OwnerLoanMqDTO;
import com.clx.performance.enums.loan.OwnerLoanAccountRunningWaterRecordEnum;
import com.clx.performance.enums.loan.OwnerLoanRecordEnum;
import com.clx.performance.enums.loan.OwnerRePaymentEnum;
import com.clx.performance.model.OrderChild;
import com.clx.performance.model.loan.OrderChildLoanRetryRecord;
import com.clx.performance.model.loan.OwnerLoanAccount;
import com.clx.performance.model.loan.OwnerLoanAccountRunningWaterRecord;
import com.clx.performance.model.loan.OwnerRepayment;
import com.clx.performance.model.settle.SettlementDriverDetail;
import com.clx.performance.model.settle.SettlementOwnerDetail;
import com.clx.performance.service.settle.SettlementMqService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

@Component
@Slf4j
@AllArgsConstructor
public class EventListenerComponent {

    private final SettlementOwnerDetailDao settlementOwnerDetailDao;

    private final SettlementDriverDetailDao settlementDriverDetailDao;

    private final OrderChildLoanRetryRecordDao orderChildLoanRetryRecordDao;

    private final OwnerRepaymentDao ownerRepaymentDao;

    private final OrderChildLoanComponent orderChildLoanComponent;

    private final SettlementMqService settlementMqService;

    private final ApplicationEventPublisher applicationEventPublisher;

    private final SettlementDriverDao settlementDriverDao;

    private final OwnerLoanAccountRunningWaterRecordDao ownerLoanAccountRunningWaterRecordDao;


    @EventListener(classes = {SettlementUpdateEvent.class})
    public void listen(SettlementUpdateEvent event) {
        log.info("SettlementUpdateEvent事件执行");
        SettlementOwnerDetail settlementOwnerDetail = event.getSettlementOwnerDetail();
        SettlementDriverDetail settlementDriverDetail = event.getSettlementDriverDetail();
        log.info("当前货主结算信息{},车主结算信息：{}", JSONUtil.parse(settlementOwnerDetail), JSONUtil.parse(settlementDriverDetail));
        settlementOwnerDetailDao.updateInvoiceType(settlementOwnerDetail);
        settlementDriverDetailDao.updateInvoiceTypeAndPrepayFreightFlag(settlementDriverDetail);

        OrderChildLoanRetryRecord entity = new OrderChildLoanRetryRecord();
        entity.setSettlementOwnerId(settlementOwnerDetail.getId());
        entity.setSettlementDriverId(settlementDriverDetail.getId());
        entity.setOwnerUserNo(settlementOwnerDetail.getOwnerUserNo());
        // 保存重试记录
        orderChildLoanRetryRecordDao.saveEntity(entity);
    }

    @EventListener(classes = {OwnerRepaymentUpdateEvent.class})
    public void listen(OwnerRepaymentUpdateEvent event) {
        log.info("OwnerRepaymentUpdateEvent事件执行");
        OwnerRepayment update = new OwnerRepayment();
        update.setId(event.getId());
        update.setBeOverdue(OwnerRePaymentEnum.BeOverdue.YES.getCode());
        ownerRepaymentDao.updateEntityByKey(update);
    }

    @EventListener(classes = {OwnerLoanEvent.class})
    public void listen(OwnerLoanEvent event) {
        log.info("OwnerLoanEvent事件执行");
        OwnerLoanMqDTO param = event.getParam();
        SettlementOwnerDetail settlementOwnerDetail = param.getSettlementOwnerDetail();
        SettlementDriverDetail settlementDriverDetail = param.getSettlementDriverDetail();
        OrderChild orderChild = param.getOrderChild();

        try {
            //生成借款标识
            orderChildLoanComponent.childLoanConfirmAfterProcess(settlementDriverDetail, settlementOwnerDetail, orderChild);
        } catch (Exception e) {
            //未借款
            settlementDriverDetail.setLoanFlag(OwnerLoanRecordEnum.LoanFlag.NO_LOAN.getCode());
            applicationEventPublisher.publishEvent(new SettlementUpdateEvent(this, settlementDriverDetail, settlementOwnerDetail));
            log.error("处理货主借款监听器执行异常,数据为{},异常信息{}", JSONUtil.parse(param), ExceptionUtil.getMessage(e));
            throw e;
        }
        log.info("处理货主借款监听器执行成功");
        settlementOwnerDetailDao.updateInvoiceType(settlementOwnerDetail);
        settlementDriverDetailDao.updateInvoiceTypeAndPrepayFreightFlag(settlementDriverDetail);

        // 发送mq 通过开票标识
        settlementMqService.invoiceTypeSync(settlementDriverDetail.getChildNo(), settlementDriverDetail.getInvoiceType());
    }


    @EventListener(classes = {OwnerLoanFlagEvent.class})
    public void listen(OwnerLoanFlagEvent event) {
        log.info("OwnerLoanFlagEvent事件执行");
        Long loanNo = event.getLoanNo();
        List<OwnerLoanAccountRunningWaterRecord> records = ownerLoanAccountRunningWaterRecordDao.selectLoanRunningWatterRecord(loanNo);
        if (CollectionUtil.isEmpty(records)) {
            return;
        }

        Map<String, List<OwnerLoanAccountRunningWaterRecord>> listMap = records.stream().collect(Collectors.groupingBy(OwnerLoanAccountRunningWaterRecord::getChildNo));

        for (Map.Entry<String, List<OwnerLoanAccountRunningWaterRecord>> entry : listMap.entrySet()) {
            if (entry.getValue().size() > 1) {
                log.info("当前运单{}存在多条流水,不更新还款标志", entry.getKey());
                listMap.remove(entry.getKey());
            }
        }
        log.info("当前需要更新的运单数量:{}", listMap.size());

        settlementDriverDetailDao.updateLoanFlagByChildNoList(listMap.keySet());
        settlementDriverDao.updateLoanFlagByChildNoList(listMap.keySet());
    }

    @EventListener(classes = {OrderChildCancelEvent.class})
    public void listen(OrderChildCancelEvent event) {
        log.info("OrderChildCancelEvent事件执行");
        List<String> childNoList = event.getChildNoList();
        log.info("需要解冻借款的的运单号:{}", JSONUtil.parse(childNoList));

        List<OwnerLoanAccountRunningWaterRecord> runningWaterRecordList = ownerLoanAccountRunningWaterRecordDao.getListByChildNoAndRunningWaterType(childNoList, OwnerLoanAccountRunningWaterRecordEnum.RunWaterType.APPROVE_FROZEN.getCode());

        if (CollectionUtil.isEmpty(runningWaterRecordList)) {
            return;
        }

        Long ownerUserNo = runningWaterRecordList.get(0).getOwnerUserNo();
        log.info("当前解冻货主：{},流水记录长度{},流水记录{}", ownerUserNo, runningWaterRecordList.size(), JSONUtil.parse(runningWaterRecordList));

        for (OwnerLoanAccountRunningWaterRecord record : runningWaterRecordList) {
            Long loanNo = record.getLoanNo();
            Integer loanType = record.getLoanType();
            String ownerUserName = record.getOwnerUserName();
            String childNo = record.getChildNo();
            BigDecimal balance = record.getAlterationBalance();
            //解冻借款
            orderChildLoanComponent.thawOwnerLoanAccount(loanNo, loanType, ownerUserNo, record.getMobile(), ownerUserName, childNo, balance);
        }

    }

    @EventListener(classes = {OwnerLoanThawEvent.class})
    public void listen(OwnerLoanThawEvent event) {
        log.info("OwnerLoanThawEvent事件执行");
        log.info("需要解冻借款的的运单号:{}", event.getChildNo());

        List<OwnerLoanAccountRunningWaterRecord> runningWaterRecordList = ownerLoanAccountRunningWaterRecordDao.getListByChildNoAndRunningWaterType(event.getChildNo());

        if (CollectionUtil.isEmpty(runningWaterRecordList)) {
            return;
        }
        Map<Integer, List<OwnerLoanAccountRunningWaterRecord>> listMap = runningWaterRecordList.stream().collect(Collectors.groupingBy(OwnerLoanAccountRunningWaterRecord::getRunningWaterType));

        List<OwnerLoanAccountRunningWaterRecord> thawRecord = listMap.get(OwnerLoanAccountRunningWaterRecordEnum.RunWaterType.APPROVE_THAW.getCode());
        if (CollectionUtil.isNotEmpty(thawRecord)) {
            log.info("3.1 有借款解冻记录,说明是是重复记录,直接返回");
            return;
        } else {
            runningWaterRecordList = listMap.get(OwnerLoanAccountRunningWaterRecordEnum.RunWaterType.APPROVE_FROZEN.getCode());
        }
        Long ownerUserNo = runningWaterRecordList.get(0).getOwnerUserNo();
        log.info("当前解冻货主：{},流水记录长度{},流水记录{}", ownerUserNo, runningWaterRecordList.size(), JSONUtil.parse(runningWaterRecordList));

        for (OwnerLoanAccountRunningWaterRecord record : runningWaterRecordList) {
            Long loanNo = record.getLoanNo();
            Integer loanType = record.getLoanType();
            String ownerUserName = record.getOwnerUserName();
            String childNo = record.getChildNo();
            BigDecimal balance = record.getAlterationBalance();
            //解冻借款
            orderChildLoanComponent.thawOwnerLoanAccount(loanNo, loanType, ownerUserNo, record.getMobile(), ownerUserName, childNo, balance);
        }

    }
}
