package com.clx.performance.event;

import cn.hutool.json.JSONUtil;
import com.clx.performance.dao.loan.OrderChildLoanRetryRecordDao;
import com.clx.performance.dao.loan.OwnerRepaymentDao;
import com.clx.performance.dao.settle.SettlementDriverDetailDao;
import com.clx.performance.dao.settle.SettlementOwnerDetailDao;
import com.clx.performance.enums.loan.OwnerRePaymentEnum;
import com.clx.performance.model.loan.OrderChildLoanRetryRecord;
import com.clx.performance.model.loan.OwnerRepayment;
import com.clx.performance.model.settle.SettlementDriverDetail;
import com.clx.performance.model.settle.SettlementOwnerDetail;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

@Component
@Slf4j
@AllArgsConstructor
public class EventListenerComponent {

    private final SettlementOwnerDetailDao settlementOwnerDetailDao;

    private final SettlementDriverDetailDao settlementDriverDetailDao;

    private final OrderChildLoanRetryRecordDao orderChildLoanRetryRecordDao;

    private final OwnerRepaymentDao ownerRepaymentDao;


    @EventListener(classes = {SettlementUpdateEvent.class})
    public void listen(SettlementUpdateEvent event) {
        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());
        // 保存重试记录
        orderChildLoanRetryRecordDao.saveEntity(entity);
    }

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