package com.jkcredit.invoice.service.nocar.impl;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jkcredit.invoice.mapper.binvoce.BillInvoiceMapper;
import com.jkcredit.invoice.mapper.waybill.NoCarWaybillMapper;
import com.jkcredit.invoice.mapper.waybill.WayBillFileMapper;
import com.jkcredit.invoice.model.entity.invoice.BillInvoice;
import com.jkcredit.invoice.model.entity.waybill.NoCarWayBill;
import com.jkcredit.invoice.model.entity.waybill.NoCarWayBillFileInfo;
import com.jkcredit.invoice.service.nocar.WayBillFileService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
@Slf4j
public class WayBillFileServiceImpl extends ServiceImpl<WayBillFileMapper, NoCarWayBillFileInfo> implements WayBillFileService {
    @Autowired
    WayBillFileMapper wayBillFileMapper;
    @Override
    public int insert(NoCarWayBillFileInfo noCarWayBillFileInfo) {
        return wayBillFileMapper.insert(noCarWayBillFileInfo);
    }

    @Override
    public IPage<List<NoCarWayBillFileInfo>> selectAllFiles(Page page, NoCarWayBillFileInfo noCarWayBillFileInfo) {
        return wayBillFileMapper.selectAllFiles( page, noCarWayBillFileInfo);
    }

    @Override
    public NoCarWayBillFileInfo selectFileInfo(String batchNum,String wayBillNum) {
        if(StringUtils.isEmpty(batchNum)){
            return wayBillFileMapper.selectFileInfoNoBatch(wayBillNum);
        }
        return wayBillFileMapper.selectFileInfo(batchNum,wayBillNum);
    }

    @Override
    public NoCarWayBillFileInfo selectFileInfoNoFile(String batchNum,String wayBillNum) {
        if(StringUtils.isEmpty(batchNum)){
            return wayBillFileMapper.selectFileInfoNoFileNoBatch(wayBillNum);
        }
        return wayBillFileMapper.selectFileInfoNoFile(batchNum,wayBillNum);
    }
    @Autowired
    NoCarWaybillMapper noCarWaybillMapper;
    @Autowired
    BillInvoiceMapper billInvoiceMapper;
    @Override
    @Transactional(isolation = Isolation.READ_COMMITTED,rollbackFor=Exception.class)
    public void migrateData1(NoCarWayBill noCarWayBill) {
        log.info("开始迁移数据{}",noCarWayBill.getBillNum());
        noCarWaybillMapper.insertHis(noCarWayBill);
        noCarWaybillMapper.deleteWayBill(noCarWayBill.getBillNum());
        List<BillInvoice> billInvoices = billInvoiceMapper.selectByBillNum(noCarWayBill.getBillNum());
        billInvoices.forEach(billInvoice -> {billInvoiceMapper.insert(billInvoice);});
        billInvoiceMapper.deleteByBillNum(noCarWayBill.getBillNum());
    }
}
