package com.fzm.mall.server.front.redis;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fzm.mall.server.front.asset.model.po.OrderDetailPO;
import com.fzm.mall.server.front.asset.model.po.OrderPO;
import com.fzm.mall.server.front.asset.model.properties.IntervalProperties;
import com.fzm.mall.server.front.order.model.Order;
import com.fzm.mall.server.front.order.model.OrderDetail;
import com.fzm.mall.server.front.repository.RedisRepository;
import com.fzm.mall.server.front.constant.cache.GoodCache;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author tdz
 * @date 2021/02/22 11:26
 */
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class OrderRedis {
    private final RedisRepository redisRepository;
    private final IntervalProperties intervalProperties;

    public void setListOrderDetail(String oid, List<OrderDetail> listOrderDetail) {
        redisRepository.setObj(GoodCache.GOOD_ORDER_DETAIL + oid, listOrderDetail, 7, TimeUnit.HOURS);
    }

    public List<OrderDetail> getListOrderDetail(String oid) {
        try {
            Object obj = redisRepository.getObj(GoodCache.GOOD_ORDER_DETAIL + oid);
            if (obj != null) {
                return JSON.parseArray(JSON.toJSONString(obj), OrderDetail.class);
            }
        } catch (Exception e) {
            // 缓存中获取的数据转换发生错误，重置缓存
            delListOrderDetail(oid);
        }
        return null;
    }

    public void delListOrderDetail(String oid) {
        redisRepository.delObj(GoodCache.GOOD_ORDER_DETAIL + oid);
    }

    public void setOrder(String oid, Order order) {
        redisRepository.setObj(GoodCache.GOOD_ORDER + oid, order, 7, TimeUnit.HOURS);
    }

    public Order getOrder(String oid) {
        try {
            Object obj = redisRepository.getObj(GoodCache.GOOD_ORDER + oid);
            if (obj != null) {
                return JSON.parseObject(JSON.toJSONString(obj), Order.class);
            }
        } catch (Exception e) {
            // 缓存中获取的数据转换发生错误，重置缓存
            delOrder(oid);
        }
        return null;
    }

    public void delOrder(String oid) {
        redisRepository.delObj(GoodCache.GOOD_ORDER + oid);
    }

    public void setOrderTime(String oid, String gid) {
        redisRepository.setStr(GoodCache.GOOD_ORDER_TIME + oid, gid, Long.parseLong(intervalProperties.getOrder()), TimeUnit.MILLISECONDS);
    }

    public String getOrderTime(String oid) {
        return redisRepository.getStr(GoodCache.GOOD_ORDER_TIME + oid);
    }

}
