package com.bawei.mall.car.utils;

import com.alibaba.fastjson.JSON;
import com.bawei.common.redis.service.RedisService;
import com.bawei.mall.car.domain.Car;
import com.bawei.mall.car.domain.CarBySku;
import com.bawei.mall.car.domain.ProductSkuInfo;
import com.bawei.mall.car.mapper.CarMapper;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import static com.fasterxml.jackson.databind.type.LogicalType.Collection;

/**
 * @program: mall_cloud
 * @ClassName: RedisTiming
 * @author: Gyc
 * @create: 2024-05-08 15:12
 **/
@Component
@Log4j2
public class RedisTiming {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    @Autowired
    private CarMapper carMapper;
    //定时存
    @Scheduled(cron = "0 0/30 * * *  ?")
    public void timingSave() {
        //编写一个定时任务，将redis的购物车信息，更新到mysql数据库
        List<String> car = redisTemplate.opsForList().range("car", 0, -1);
       List<ProductSkuInfo> productSkuInfos = car.stream()
                .map(carProductInfo -> JSON.parseObject(carProductInfo,ProductSkuInfo.class))
                .collect(Collectors.toList());

        if (productSkuInfos.size() == 0){
            return;
        }else {
            productSkuInfos.forEach(productSkuInfo -> {
                carMapper.delCarBySkuIdInfo(Math.toIntExact(productSkuInfo.getSkuId()), productSkuInfo.getCarId());
                carMapper.addCarBySkuId(Math.toIntExact(productSkuInfo.getSkuId()), productSkuInfo.getCarId(), 0L);
            });
        }

    }

    //定时取
    @Scheduled(cron = "0 0/15 * * * ? ")
    public void timingGet() {
        if (redisTemplate.hasKey("car")){
            redisTemplate.delete("car");
        }
        //编写一个定时任务，将mysql数据库的购物车信息，更新到redis
        List<ProductSkuInfo> productSkuInfos = carMapper.ProductBySkuIdList();
        productSkuInfos.forEach(productSkuInfo -> {
            redisTemplate.opsForList().rightPushAll("car",JSON.toJSONString(productSkuInfo));
        });

    }







}
