package com.lcrx.selector.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.lcrx.selector.constant.RedisKey;
import com.lcrx.selector.entity.PO.QuantityMappingPO;
import com.lcrx.selector.entity.PO.TotalQuantityMappingPO;
import com.lcrx.selector.entity.PO.VariantTablePO;
import com.lcrx.selector.utils.RedisHelper;
import com.lcrx.selector.utils.StringHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author leafinsight
 */
@Service
public class SelectorCacheService {
    private final RedisHelper redisHelper;

    @Autowired
    public SelectorCacheService(RedisHelper redisHelper) {
        this.redisHelper = redisHelper;
    }

    /**
     * @return VariantTable
     */
    public List<VariantTablePO> getVariantTable(String systemCode, String productGroupCode, String materialCode) {
        /* 第一层是VT#，第二层是Line#，第三层是特征#，第四层是特征值# */
        List<VariantTablePO> variantTablePOList = null;

        try {
            String str = redisHelper.get(RedisKey.getVariantTableKey(systemCode, productGroupCode, materialCode));
            if (!StringHelper.isNullOrEmpty(str)) {
                variantTablePOList = JSON.parseObject(str, new TypeReference<List<VariantTablePO>>() {
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return variantTablePOList;
    }

    /**
     * @return 数量型特征的主从映射关系
     */
    List<QuantityMappingPO> getQuantityMapping(String systemCode) {
        List<QuantityMappingPO> quantityMappingPOList = new ArrayList<>();

        try {
            String str = redisHelper.get(RedisKey.getQuantityMappingKey(systemCode));
            if (!StringHelper.isNullOrEmpty(str)) {
                quantityMappingPOList = JSON.parseObject(str, new TypeReference<List<QuantityMappingPO>>() {
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return quantityMappingPOList;
    }

    /**
     * @return 数量型特征和total汇总特征的关系
     */
    List<TotalQuantityMappingPO> getTotalQuantityMapping(String systemCode) {
        List<TotalQuantityMappingPO> totalQuantityMappingPOList = new ArrayList<>();

        try {
            String str = redisHelper.get(RedisKey.getTotalQuantityMappingKey(systemCode));
            if (!StringHelper.isNullOrEmpty(str)) {
                totalQuantityMappingPOList = JSON.parseObject(str, new TypeReference<List<TotalQuantityMappingPO>>() {
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return totalQuantityMappingPOList;
    }
}
