package com.clx.performance.listener.excel;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.clx.performance.dao.settle.SettlementOwnerDetailDao;
import com.clx.performance.dto.excel.InvoiceData;
import com.clx.performance.model.settle.SettlementOwnerDetail;
import com.clx.performance.param.pc.owner.PageInvoiceOwnerSettlementOwnerDetailParam;
import lombok.AllArgsConstructor;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.List;

import static com.clx.performance.enums.settle.SettlementOwnerDetailEnum.InvoiceStatus.NO;
import static com.clx.performance.enums.settle.SettlementOwnerEnum.InvoiceType.ORDINARY;

@AllArgsConstructor
public class InvoiceDataListener extends AnalysisEventListener<InvoiceData> {

    private final List<InvoiceData> invoiceDataList;
    private final SettlementOwnerDetailDao settlementOwnerDetailDao;;

    @Override
    public void invoke(InvoiceData invoiceData, AnalysisContext context) {
        // 每解析一行都会调用一次，逐行校验数据
        PageInvoiceOwnerSettlementOwnerDetailParam param = new PageInvoiceOwnerSettlementOwnerDetailParam();
        param.setInvoiceStatus(NO.getCode());
        param.setChildNo(invoiceData.getChildNo());
        //param.setInvoiceType(ORDINARY.getCode());
        IPage<SettlementOwnerDetail> page = settlementOwnerDetailDao.pageInvoiceOwnerSettlementOrderDetailList(param);
        List<SettlementOwnerDetail> records = page.getRecords();
        if (CollectionUtils.isEmpty(records)) {
            invoiceData.setRemark("校验失败（运单编号不匹配）");
        }else if(!ORDINARY.getCode().equals(records.get(0).getInvoiceType())){
            invoiceData.setRemark("校验失败（开票标识非普通单）");
        }else if(records.get(0).getInvoiceFreight().compareTo(invoiceData.getInvoiceFreight().multiply(new BigDecimal(100))) != 0){
            invoiceData.setRemark("校验失败（开票金额不匹配）");
        }else {
            invoiceData.setRemark("校验通过");
            invoiceData.setLoadNet(records.get(0).getLoadNet());
        }
        invoiceDataList.add(invoiceData);
    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        // 解析完成后调用
        // 可在此进行后续操作，如保存数据到数据库
    }
}

