package com.bailuntec.job;

import com.bailuntec.domain.dto.OutStockQuantity;
import com.bailuntec.mapper.DcMidTransitMapper;
import com.bailuntec.utils.SessionUtil;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.TransactionIsolationLevel;

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

@Slf4j
public class CalculateOutStockJob implements SimpleJob {

    @Override
    public void execute(ShardingContext shardingContext) {
        SqlSession sqlSession = SessionUtil.getFactory().openSession(TransactionIsolationLevel.READ_UNCOMMITTED);
        try {
            DcMidTransitMapper mapper = sqlSession.getMapper(DcMidTransitMapper.class);
            List<OutStockQuantity> listQuantityOutStock = mapper.selectQuantityOutStock();
            LocalDateTime localDateTime = LocalDateTime.now();
            for(OutStockQuantity outStockQuantity: listQuantityOutStock) {
                outStockQuantity.setGmtOutStockModified(localDateTime);
                mapper.calculateOutStock(outStockQuantity);
            }
            sqlSession.commit();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("计算缺货数失败",e);
        } finally {
            if (sqlSession != null) {
                sqlSession.close();
            }
        }
        SqlSession sqlSessionUpdate = SessionUtil.getFactory().openSession(TransactionIsolationLevel.READ_UNCOMMITTED);
        try {
            DcMidTransitMapper mapper = sqlSessionUpdate.getMapper(DcMidTransitMapper.class);
            LocalDateTime localDateTime = mapper.selectMaxOutStockModified();
            mapper.updateOldOutStockToZero(localDateTime);
            sqlSessionUpdate.commit();
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("更新缺货数失败",e);
        } finally {
            if(sqlSessionUpdate !=null) {
                sqlSessionUpdate.close();
            }
        }
    }
}
