package cn.ysk.cashier.quartz.task;

import cn.ysk.cashier.dto.product.StockCountDTO;
import cn.ysk.cashier.pojo.order.TbCashierCart;
import cn.ysk.cashier.pojo.product.TbProductStockDetail;
import cn.ysk.cashier.repository.order.StockCountRepository;
import cn.ysk.cashier.repository.order.TbCashierCartRepository;
import cn.ysk.cashier.repository.product.TbProductSkuRepository;
import cn.ysk.cashier.service.order.TbCashierCartService;
import cn.ysk.cashier.service.shop.TbShopStorageService;
import cn.ysk.cashier.utils.CacheKey;
import cn.ysk.cashier.utils.DateUtil;
import cn.ysk.cashier.utils.QueryHelp;
import cn.ysk.cashier.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.criteria.Predicate;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 测试用
 * @author Zheng Jie
 * @date 2019-01-08
 */
@Slf4j
@Service
public class TestTask {

    @Autowired
    private TbShopStorageService storageService;
    @Autowired
    private TbCashierCartRepository cartService;
    @Autowired
    private StockCountRepository stockCountRepository;

    @Autowired
    private TbProductSkuRepository skuRepository;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private EntityManager entityManager;
    private final TbCashierCartService tbCashierCartService;

    public TestTask(TbCashierCartService tbCashierCartService) {
        this.tbCashierCartService = tbCashierCartService;
    }


    public void run(){
        log.info("run 执行成功");
    }

    public void run1(String str){
        log.info("run1 执行成功，参数为： {}" , str);
    }

    public void run2(){
        log.info("run2 执行成功");
    }


    public void expStorage(){
        log.info("存酒过期开始执行");
        storageService.expStorage();
        log.info("存酒过期执行结束");
    }

    @Transactional(rollbackFor = Exception.class)
    public void cleanCart(){
        log.info("购物车清楚记录开始");
        List<TbCashierCart> all = cartService.findAll((root, criteriaQuery, criteriaBuilder) -> {
            Predicate predicate = QueryHelp.getPredicate(root, null, criteriaBuilder);
            predicate = criteriaBuilder.and(predicate, criteriaBuilder.isNull(root.get("masterId")));
            predicate = criteriaBuilder.and(predicate, criteriaBuilder.equal(root.get("status"), "create"));
            predicate = criteriaBuilder.and(predicate, criteriaBuilder.notEqual(root.get("tableId"), "0"));
            predicate = criteriaBuilder.and(predicate, criteriaBuilder.lt(root.get("updatedAt"), System.currentTimeMillis() - 60 * 1000L * 60 * 24));
            predicate = criteriaBuilder.and(predicate, criteriaBuilder.gt(root.get("updatedAt"), System.currentTimeMillis() - 60 * 1000L * 60 * 24 * 2));
            return predicate;
        });
        Set<String> keys = new HashSet<>();
        for (TbCashierCart cart : all) {
            tbCashierCartService.clearExpireOrder(cart);
            cart.setStatus("cancelled");
            cartService.save(cart);
            keys.add(CacheKey.PRODUCT_SKU + cart.getShopId() + ":" + cart.getSkuId());
        }
        String[] keysArray = keys.toArray(new String[keys.size()]);
        redisUtils.del(keysArray);
        log.info("购物车清楚记录开始结束");
    }

    @Transactional(rollbackFor = Exception.class)
    public void countStock(String str) {
        String startTime = "";
        String endTime = "";
        if (!"today".equals(str)) {
            startTime = str + " 00:00:00";
            endTime = str + " 23:59:59";
        } else {
            startTime = DateUtil.getStrTime(DateUtil.getBeginDayOfYesterday());
            endTime = DateUtil.getStrTime(DateUtil.getEndDayOfYesterday());
            str = DateUtil.getYMDTime(DateUtil.getBeginDayOfYesterday());
        }
        log.info("记录" + str + " 库存损耗开始");
        List<StockCountDTO> stockCountDTOS = stockCountRepository.countStock(startTime, endTime);
        String finalStr = str;
        stockCountDTOS.forEach(s->{
            TbProductStockDetail productStockDetail = new TbProductStockDetail();
            productStockDetail.setCreatedAt(System.currentTimeMillis());
            productStockDetail.setUpdatedAt(System.currentTimeMillis());
            productStockDetail.setShopId(s.getShopId().toString());
            productStockDetail.setProductId(s.getProId().toString());
            productStockDetail.setProductName(s.getProName());
//            productStockDetail.setSkuId(s.getSkuId().toString());
            productStockDetail.setIsStock(s.getIsStock());//是否开启库存
            productStockDetail.setLeftNumber(s.getStockNumber()+s.getStockCount());//原库存
//            productStockDetail.setSpecSnap(s.getSkuName());
            productStockDetail.setUnitName(s.getUnitName());
            productStockDetail.setStockNumber(-Double.valueOf(s.getStockCount()));
            productStockDetail.setSourcePath("NORMAL");
            productStockDetail.setType("other-out");
            productStockDetail.setType(finalStr +"日售出记录");
            productStockDetail.setRemark(finalStr +"日统计库存");
            productStockDetail.setSubType(-1);
            entityManager.persist(productStockDetail);
        });
        log.info("记录当日库存损耗结束");
    }
}
