package com.bailuntec.job;

import com.bailuntec.domain.entity.DcBaseSku;
import com.bailuntec.domain.entity.DcBaseStockRecord;
import com.bailuntec.domain.entity.DcMidStockDate;
import com.bailuntec.domain.entity.JobPointLog;
import com.bailuntec.domain.example.DcBaseSkuExample;
import com.bailuntec.domain.example.DcMidStockDateExample;
import com.bailuntec.mapper.DcBaseSkuMapper;
import com.bailuntec.mapper.DcBaseStockOutMapper;
import com.bailuntec.mapper.DcBaseStockRecordMapper;
import com.bailuntec.mapper.DcMidStockDateMapper;
import com.bailuntec.support.PointJob;
import com.bailuntec.utils.SessionUtil;
import com.dangdang.ddframe.job.api.ShardingContext;
import lombok.extern.slf4j.Slf4j;

import java.time.LocalDateTime;
import java.util.List;

@Slf4j
public class CalculateStockRecordJob extends PointJob {


    @Override
    public void executeJob(ShardingContext shardingContext, JobPointLog jobPointLog) {

        jobPointLog.setPageIndex(1);
        Integer pickSize = 0;
        try {
            // 根据仓库、sku分组分页查询sku数量
            DcBaseStockRecordMapper dcBaseStockRecordMapper = SessionUtil.getSession().getMapper(DcBaseStockRecordMapper.class);
            pickSize = dcBaseStockRecordMapper.selectCountByGroup(jobPointLog);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("MYbatis操作DB失败", e);
        } finally {
            SessionUtil.closeSession();
        }
        Integer pageSize = pickSize % jobPointLog.getPageSize() == 0 ? pickSize/jobPointLog.getPageSize() : pickSize/jobPointLog.getPageSize() + 1;

        LocalDateTime localDateTime = LocalDateTime.now();

        do{
            // 根据仓库、sku分组分页查询sku
            DcBaseStockRecordMapper dcBaseStockRecordMapper = SessionUtil.getSession().getMapper(DcBaseStockRecordMapper.class);
            List<DcBaseStockRecord> dcBaseStockRecordList = dcBaseStockRecordMapper.selectPageByGroup((jobPointLog.getPageIndex() - 1) * jobPointLog.getPageSize(), jobPointLog.getPageSize());

            for(DcBaseStockRecord dcBaseStockRecord : dcBaseStockRecordList) {

                // 根据仓库、sku计算出库数量
                DcBaseStockOutMapper dcBaseStockOutMapper = SessionUtil.getSession().getMapper(DcBaseStockOutMapper.class);
                Integer stockOut = dcBaseStockOutMapper.selectCount(dcBaseStockRecord.getBailunSku(), dcBaseStockRecord.getWarehouseCode());

                // 根据仓库、sku，入库时间升序查询入库sku记录
                DcBaseStockRecordMapper midDcBaseStockRecordMapper = SessionUtil.getSession().getMapper(DcBaseStockRecordMapper.class);

                List<DcBaseStockRecord> baseStockRecordList = midDcBaseStockRecordMapper.selectByStockTime(dcBaseStockRecord.getBailunSku(), dcBaseStockRecord.getWarehouseCode());
                Integer quantityStock = 0;
                boolean firstMatch = true;
                DcMidStockDateMapper dcMidStockDateMapper = SessionUtil.getSession().getMapper(DcMidStockDateMapper.class);
                Integer stockNum = dcMidStockDateMapper.selectCount(dcBaseStockRecord.getBailunSku(), dcBaseStockRecord.getWarehouseCode());
                if(stockOut >= stockNum) {
                    DcMidStockDate dcMidStockDate = new DcMidStockDate();
                    dcMidStockDate.setQuantityStock(0);
                    dcMidStockDate.setBailunSku(dcBaseStockRecord.getBailunSku());
                    dcMidStockDate.setWarehouseCode(dcBaseStockRecord.getWarehouseCode());
                    dcMidStockDateMapper.updateByExampleSelective(dcMidStockDate, DcMidStockDateExample.newAndCreateCriteria().
                            andBailunSkuEqualTo(dcBaseStockRecord.getBailunSku())
                            .andWarehouseCodeEqualTo(dcBaseStockRecord.getWarehouseCode())
                            .andHasInitEqualTo(true)
                            .example());
                    stockOut = stockOut - stockNum;
                }else {
                    DcMidStockDate dcMidStockDate = new DcMidStockDate();
                    dcMidStockDate.setQuantityStock(stockNum - stockOut);
                    dcMidStockDate.setBailunSku(dcBaseStockRecord.getBailunSku());
                    dcMidStockDate.setWarehouseCode(dcBaseStockRecord.getWarehouseCode());
                    dcMidStockDateMapper.updateByExampleSelective(dcMidStockDate, DcMidStockDateExample.newAndCreateCriteria().
                            andBailunSkuEqualTo(dcBaseStockRecord.getBailunSku())
                            .andWarehouseCodeEqualTo(dcBaseStockRecord.getWarehouseCode())
                            .andHasInitEqualTo(true)
                            .example());
                    stockOut = 0;
                }
                for(DcBaseStockRecord midDcBaseStockRecord : baseStockRecordList) {
                    quantityStock = quantityStock + midDcBaseStockRecord.getQuantityStock();
                    if(quantityStock > stockOut) {
                        DcMidStockDate dcMidStockDate = new DcMidStockDate();
                        DcBaseSkuMapper dcBaseSkuMapper = SessionUtil.getSession().getMapper(DcBaseSkuMapper.class);
                        DcBaseSku dcBaseSku = dcBaseSkuMapper.selectOneByExample(DcBaseSkuExample.newAndCreateCriteria().andBailunSkuEqualTo(midDcBaseStockRecord.getBailunSku()).andCompanyIdEqualTo(1).example());
                        if(dcBaseSku != null) {
                         dcMidStockDate.setUnitPrice(dcBaseSku.getUnitPrice());
                        }
                        dcMidStockDate.setBailunSku(midDcBaseStockRecord.getBailunSku());
                        dcMidStockDate.setWarehouseCode(midDcBaseStockRecord.getWarehouseCode());
                        dcMidStockDate.setWarehouseName(midDcBaseStockRecord.getWarehouseName());
                        dcMidStockDate.setStockTime(midDcBaseStockRecord.getStockTime());
                        dcMidStockDate.setHasTransfer(midDcBaseStockRecord.getHasTransfer());
                        if(firstMatch) {
                            dcMidStockDate.setQuantityStock(quantityStock - stockOut);
                        }else{
                            dcMidStockDate.setQuantityStock(midDcBaseStockRecord.getQuantityStock());
                        }
                       // dcMidStockDate.setHasTransfer(midDcBaseStockRecord.getHasTransfer());
                        dcMidStockDate.setReportDate(localDateTime.toLocalDate());
                        try {
                            DcMidStockDateMapper dcMidStockDateMapper0 = SessionUtil.getSession().getMapper(DcMidStockDateMapper.class);
                            int result = dcMidStockDateMapper0.updateByExampleSelective(dcMidStockDate, DcMidStockDateExample.newAndCreateCriteria()
                                    .andBailunSkuEqualTo(dcMidStockDate.getBailunSku())
                                    .andWarehouseCodeEqualTo(dcMidStockDate.getWarehouseCode())
                                    .andStockTimeEqualTo(dcMidStockDate.getStockTime())
                                    .andHasTransferEqualTo(dcMidStockDate.getHasTransfer())
                                    .example());
                            if(result == 0) {
                                dcMidStockDateMapper0.upsertSelective(dcMidStockDate);
                            }
                            firstMatch = false;
                        } catch (Exception e) {
                            e.printStackTrace();
                            throw new RuntimeException("MYbatis操作DB失败", e);
                        } finally {
                            SessionUtil.closeSession();
                        }
                    }else {
                        DcMidStockDate dcMidStockDate = new DcMidStockDate();
                        DcBaseSkuMapper dcBaseSkuMapper = SessionUtil.getSession().getMapper(DcBaseSkuMapper.class);
                        DcBaseSku dcBaseSku = dcBaseSkuMapper.selectOneByExample(DcBaseSkuExample.newAndCreateCriteria().andBailunSkuEqualTo(midDcBaseStockRecord.getBailunSku()).andCompanyIdEqualTo(1).example());
                        if(dcBaseSku != null) {
                            dcMidStockDate.setUnitPrice(dcBaseSku.getUnitPrice());
                        }
                        dcMidStockDate.setBailunSku(midDcBaseStockRecord.getBailunSku());
                        dcMidStockDate.setWarehouseCode(midDcBaseStockRecord.getWarehouseCode());
                        dcMidStockDate.setWarehouseName(midDcBaseStockRecord.getWarehouseName());
                        dcMidStockDate.setStockTime(midDcBaseStockRecord.getStockTime());
                        dcMidStockDate.setQuantityStock(0);
                        dcMidStockDate.setHasTransfer(midDcBaseStockRecord.getHasTransfer());
                        dcMidStockDate.setReportDate(localDateTime.toLocalDate());
                        try {
                            DcMidStockDateMapper dcMidStockDateMapper0 = SessionUtil.getSession().getMapper(DcMidStockDateMapper.class);
                            int result = dcMidStockDateMapper0.updateByExampleSelective(dcMidStockDate, DcMidStockDateExample.newAndCreateCriteria()
                                    .andBailunSkuEqualTo(dcMidStockDate.getBailunSku())
                                    .andWarehouseCodeEqualTo(dcMidStockDate.getWarehouseCode())
                                    .andStockTimeLessThanOrEqualTo(dcMidStockDate.getStockTime())
                                    .andHasInitEqualTo(false)
                                    .example());
                            if(result == 0) {
                                dcMidStockDateMapper0.upsertSelective(dcMidStockDate);
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                            throw new RuntimeException("MYbatis操作DB失败", e);
                        } finally {
                            SessionUtil.closeSession();
                        }
                    }
                }
            }
            jobPointLog.setPageIndex(jobPointLog.getPageIndex() + 1);
        }while(jobPointLog.getPageIndex() <= pageSize);
    }
}
