package com.sy.coinage.workshop.service.impl;

import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sy.coinage.core.constants.CacheKey;
import com.sy.coinage.core.constants.Constants;
import com.sy.coinage.core.exception.RetException;
import com.sy.coinage.core.redis.RedisService;
import com.sy.coinage.workshop.dao.ProductPlanDao;
import com.sy.coinage.workshop.model.BaseInfo;
import com.sy.coinage.workshop.model.Product;
import com.sy.coinage.workshop.model.ProductPlan;
import com.sy.coinage.workshop.service.IProductPlanService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * -产品计划表ServiceImpl
 */
@Service
public class ProductPlanServiceImpl extends ServiceImpl<ProductPlanDao, ProductPlan> implements IProductPlanService {

    @Autowired
    private RedisService redisService;

    @Override
    public ProductPlan getMaxBySecurities(String securities) {
        LambdaQueryWrapper<ProductPlan> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ProductPlan::getSecurities, securities);
        queryWrapper.orderByDesc(ProductPlan::getId);
        Page<ProductPlan> page = new Page<>(1, 1);
        List<ProductPlan> resp = this.list(page, queryWrapper);
        if (resp == null || resp.size() == 0) {
            throw new RetException(
                    "产品计划不存在，securities=" + securities);
        }
        return resp.get(0);
    }

    @Override
    public List<ProductPlan> cacheList() {
        List<ProductPlan> resp = null;
        String key = "Product_Plan";
        if (redisService.hasKey(key)) {
            String json = redisService.get(key);
            resp = JSON.parseArray(json, ProductPlan.class);
        } else {
            LambdaQueryWrapper<ProductPlan> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(ProductPlan::getStatus, Constants.STATUS_USABLE);
            queryWrapper.orderByAsc(ProductPlan::getSecurities);
            resp = this.list(queryWrapper);
            if (resp != null && resp.size() > 0) {
                this.redisService.set(key, JSON.toJSONString(resp), CacheKey.EXPIRED_ONE_DAY);
            }
        }
        return resp;

    }

}
