import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.fastjson.JSON;
import com.bailuntec.domain.constant.CommonConstant;
import com.bailuntec.domain.entity.DcBaseStock;
import com.bailuntec.domain.entity.JobPointLog;
import com.bailuntec.domain.entity.SalesDayConfig;
import com.bailuntec.domain.example.DcAutoTurnoverExample;
import com.bailuntec.domain.example.DcBaseStockExample;
import com.bailuntec.domain.example.DcMidTransitExample;
import com.bailuntec.excel.DcAutoTurnoverExcel;
import com.bailuntec.excel.ExcelListener;
import com.bailuntec.job.AutoTurnoverJob;
import com.bailuntec.mapper.DcAutoTurnoverMapper;
import com.bailuntec.mapper.DcBaseStockMapper;
import com.bailuntec.mapper.DcMidTransitMapper;
import com.bailuntec.mapper.SalesDayConfigMapper;
import com.bailuntec.utils.PropertiesUtil;
import com.bailuntec.utils.SessionUtil;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.executor.ShardingContexts;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.ExecutorType;
import org.apache.ibatis.session.SqlSession;
import org.junit.jupiter.api.Test;
import org.junit.platform.commons.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Slf4j
public class AutoTurnoverTest {
    //    @Test
    public void test1() throws Exception {
        LocalDate parse = LocalDate.parse("2018-01-01", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        LocalDate parse1 = LocalDate.parse("2018-01-02", DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        System.out.println(parse.isBefore(parse1));
        System.out.println(parse.isAfter(parse1));
        System.out.println(parse.isEqual(parse1));
        if (parse.isBefore(parse1)) {
            System.out.println(parse.compareTo(parse1));
        }
    }

    @Test
    public void test12() throws Exception {
        System.out.println(LocalDateTime.of(1990, 1, 1, 0, 0));
    }

    @Test
    public void test10() throws Exception {
        int interval = Period.between(LocalDate.now().minusDays(1), LocalDate.now()).getDays();
        int interval1 = Period.between(LocalDate.now(), LocalDate.now().minusDays(2)).getDays();
        int interval2 = Period.between(LocalDate.now(), LocalDate.now()).getDays();
        System.out.println(interval);
        System.out.println(interval1);
        System.out.println(interval2);
    }

    private PropertiesUtil propertiesUtil = PropertiesUtil.getInstance("const");

    @Test
    public void test() throws Exception {
        // 生成周转
        String queryTime = DateTimeFormatter.ofPattern(CommonConstant.DATE_FORMAT).format(LocalDate.now());
        AutoTurnoverJob autoTurnoverJob = new AutoTurnoverJob();
        DcBaseStock dcBaseStock = null;
        try {
            DcBaseStockMapper mapper = SessionUtil.getSession().getMapper(DcBaseStockMapper.class);
            dcBaseStock = mapper.selectOneByExample(DcBaseStockExample.newAndCreateCriteria().andBailunSkuEqualTo("229354801").andWarehouseCodeEqualTo("YHUSFBA").example());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            SessionUtil.closeSession();
        }
        autoTurnoverJob.autoTurnoverFromStock(dcBaseStock);
    }

    @Test
    public void test22() throws Exception {
        String queryTime = DateTimeFormatter.ofPattern(CommonConstant.DATE_FORMAT).format(LocalDate.now());
        AutoTurnoverJob autoTurnoverJob = new AutoTurnoverJob();
        List<DcBaseStock> dcBaseStockList = null;
        try {
            DcBaseStockMapper mapper = SessionUtil.getSession().getMapper(DcBaseStockMapper.class);
            dcBaseStockList = mapper.listInStockNotInAutoTurnover();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            SessionUtil.closeSession();
        }
        for (DcBaseStock dcBaseStock : dcBaseStockList) {
            autoTurnoverJob.autoTurnoverFromStock(dcBaseStock);
        }
    }

    @Test
    public void test3() throws Exception {
        String queryTime = DateTimeFormatter.ofPattern(CommonConstant.DATE_FORMAT).format(LocalDate.now());
        AutoTurnoverJob autoTurnoverJob = new AutoTurnoverJob();
        List<DcBaseStock> dcBaseStockList = null;
        try {
            DcBaseStockMapper mapper = SessionUtil.getSession().getMapper(DcBaseStockMapper.class);
            dcBaseStockList = mapper.selectByExample(DcBaseStockExample.newAndCreateCriteria().example());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            SessionUtil.closeSession();
        }
        for (DcBaseStock dcBaseStock : dcBaseStockList) {
            autoTurnoverJob.autoTurnoverFromStock(dcBaseStock);
        }
    }

    @Test
    public void test4() {
        AutoTurnoverJob autoTurnoverJob = new AutoTurnoverJob();
        HashMap<Integer, String> map = new HashMap<>();
        map.put(1, "");
        ShardingContext shardingContext = new ShardingContext(new ShardingContexts("", "", 1, "INCREMENT", map), 0);
        JobPointLog jobPointLog = new JobPointLog("", 6, 400, 1, 1, LocalDateTime.now().minusSeconds(1), LocalDateTime.now());
        autoTurnoverJob.executeJob(shardingContext, jobPointLog);
    }

    @Test
    public void test55() {
        LocalDateTime recordTime = LocalDateTime.now();
        LocalDateTime finalEstimatedArrivalTime = LocalDateTime.now().minusDays(1);
        int interval = Period.between(recordTime.toLocalDate(), finalEstimatedArrivalTime.toLocalDate()).getDays();
        System.out.println(interval);
    }

    @Test
    public void test66() {
        String filePath = "/Users/huluobin/Library/Containers/com.tencent.WeWorkMac/Data/Library/Application Support/WXWork/Data/1688853793439460/Cache/File/2020-12/广州-01仓停售停止监控部分AIMS需清除1128.xlsx";
        EasyExcel.read(filePath, RemoveSku.class, new RemoveSkuListener()).sheet().doRead();
    }

    static class RemoveSkuListener extends AnalysisEventListener<RemoveSku> {

        private static final Logger LOGGER = LoggerFactory.getLogger(RemoveSkuListener.class);
        /**
         * 每隔5条存储数据库，实际使用中可以3000条，然后清理list ，方便内存回收
         */
        private static final int BATCH_COUNT = 1000;


        List<RemoveSku> list = new ArrayList<>();


        @Override
        public void invoke(RemoveSku data, AnalysisContext context) {
            LOGGER.info("解析到一条数据:{}", JSON.toJSONString(data));
            list.add(data);
            if (list.size() >= BATCH_COUNT) {
                syncData();
                list.clear();
            }
        }

        @Override
        public void doAfterAllAnalysed(AnalysisContext context) {
            syncData();
            LOGGER.info("所有数据解析完成！");
        }

        /**
         * 加上存储数据库
         */
        private void syncData() {
            LOGGER.info("{}条数据，开始存储数据库！", list.size());
            SqlSession sqlSession = SessionUtil.getFactory().openSession(ExecutorType.BATCH);
            try {
                DcBaseStockMapper dcBaseStockMapper = sqlSession.getMapper(DcBaseStockMapper.class);
                DcMidTransitMapper dcMidTransitMapper = sqlSession.getMapper(DcMidTransitMapper.class);
                DcAutoTurnoverMapper dcAutoTurnoverMapper = sqlSession.getMapper(DcAutoTurnoverMapper.class);

                list.forEach(item -> {
                    if (StringUtils.isNotBlank(item.getBailunSku()) && StringUtils.isNotBlank(item.getWarehouseCode())) {
                        dcBaseStockMapper.deleteByExample(DcBaseStockExample.newAndCreateCriteria()
                                .andWarehouseCodeEqualTo(item.getWarehouseCode())
                                .andBailunSkuEqualTo(item.getBailunSku())
                                .example());

                        dcMidTransitMapper.deleteByExample(DcMidTransitExample.newAndCreateCriteria()
                                .andWarehouseCodeEqualTo(item.getWarehouseCode())
                                .andBailunSkuEqualTo(item.getBailunSku())
                                .example());

                        dcAutoTurnoverMapper.deleteByExample(DcAutoTurnoverExample.newAndCreateCriteria()
                                .andWarehouseCodeEqualTo(item.getWarehouseCode())
                                .andBailunSkuEqualTo(item.getBailunSku())
                                .example());
                    }
                });
            } finally {
                sqlSession.commit();
                sqlSession.close();
            }
            LOGGER.info("存储数据库成功！");
        }
    }

    @Data
    public static class RemoveSku implements Serializable {

        @ExcelProperty("id")
        private Integer id;
        @ExcelProperty("Sku")
        private String bailunSku;
        @ExcelProperty("仓库编码")
        private String warehouseCode;
    }

    @Test
    public void testDcAutoTurnover() {
        String filePath = "/Users/huluobin/Library/Containers/com.tencent.WeWorkMac/Data/Library/Application Support/WXWork/Data/1688853793439460/Cache/File/2020-08/实际冗余测试815.xlsx";
        EasyExcel.read(filePath, DcAutoTurnoverExcel.class, new ExcelListener()).sheet().doRead();

    }

    //949406801 GZBLWH
    @Test
    public void testXX() {
        SalesDayConfigMapper salesDayConfigMapper = SessionUtil.getSession().getMapper(SalesDayConfigMapper.class);
        AutoTurnoverJob autoTurnoverJob = new AutoTurnoverJob();

        List<SalesDayConfig> salesDayConfigList = salesDayConfigMapper.selectTarget();
        salesDayConfigList.parallelStream().forEach(salesDayConfig -> {
            DcBaseStock dcBaseStock = SessionUtil.getSession().getMapper(DcBaseStockMapper.class)
                    .selectOneByExample(DcBaseStockExample.newAndCreateCriteria()
                            .andBailunSkuEqualTo(salesDayConfig.getBailunSku())
                            .andWarehouseCodeEqualTo(salesDayConfig.getWarehouseCode())
                            .example());
            try {
                autoTurnoverJob.autoTurnoverFromStock(dcBaseStock);
            } catch (Exception e) {
                e.printStackTrace();
            }

        });
    }

    //{"bailun_sku":"N-GNS631-7ML","warehouse_code":"BLGZ03"}

    //{"bailun_sku":"N-GNS006-7ML","warehouse_code":"BLGZ03"}
    @Transactional
    @Test
    public void testXX2() {
        DcBaseStock dcBaseStock = SessionUtil.getSession().getMapper(DcBaseStockMapper.class)
                .selectOneByExample(DcBaseStockExample.newAndCreateCriteria()
                        .andBailunSkuEqualTo("243903601")
                        .andWarehouseCodeEqualTo("US4PXBL")
                        .example());
        try {
            AutoTurnoverJob autoTurnoverJob = new AutoTurnoverJob();
            long time = System.currentTimeMillis();
            log.info(Long.toString(time));
//            AutoTurnoverJob.shardingContextThreadLocal.set(new ShardingContext(new ShardingContexts("x", null, 8, Constant.AIR_HEAD, new HashMap<>()), 0));

            autoTurnoverJob.autoTurnoverFromStock(dcBaseStock);
            log.info(String.valueOf((System.currentTimeMillis() - time)));

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Test
    public void testBigDecimal() {

        SessionUtil.getSession().getMapper(DcAutoTurnoverMapper.class);
    }

    public void add(DcBaseStock dcBaseStock) {
        dcBaseStock.setInWarehouse(2);
    }
}
