package com.ruoyi.jarvis.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.ruoyi.common.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.jarvis.domain.ProductJdConfig;
import com.ruoyi.jarvis.service.IProductJdConfigService;

/**
 * 产品京东配置Service业务层处理
 * 
 * @author ruoyi
 */
@Service
public class ProductJdConfigServiceImpl implements IProductJdConfigService 
{
    @Autowired
    private RedisCache redisCache;

    /**
     * Redis key前缀
     */
    private static final String PRODUCT_JD_CONFIG_KEY = "product:jd:config:";

    /**
     * 初始化默认数据
     */
    @Override
    public void initDefaultData() {
        // 检查是否已经初始化
        if (redisCache.hasKey(PRODUCT_JD_CONFIG_KEY + "ZQD110F-EB031")) {
            return;
        }

        // 初始化原有的数据
        insertProductJdConfig(new ProductJdConfig("ZQD110F-EB031", "https://u.jd.com/0gGPOZX", BigDecimal.ZERO));
        insertProductJdConfig(new ProductJdConfig("ZQD130F-EB130", "https://u.jd.com/0OGTvHh", BigDecimal.ZERO));
        insertProductJdConfig(new ProductJdConfig("ZQD130F-EB130B", "https://u.jd.com/0GGWEOR", BigDecimal.ZERO));
        insertProductJdConfig(new ProductJdConfig("ZQD150F-EB150", "https://u.jd.com/0O8BYjb", BigDecimal.ZERO));
        insertProductJdConfig(new ProductJdConfig("ZQD180F-EB200", "https://u.jd.com/0gGSoiN", BigDecimal.ZERO));
        insertProductJdConfig(new ProductJdConfig("ZQD115F-12LCS", "https://u.jd.com/0DGSFcH", BigDecimal.ZERO));
        insertProductJdConfig(new ProductJdConfig("CXW-298-IQ92DPRO", "https://u.jd.com/0OG04su", BigDecimal.ZERO));
        insertProductJdConfig(new ProductJdConfig("CXW-358-EC970", "https://u.jd.com/0g8BB3a", BigDecimal.ZERO));
    }

    /**
     * 查询产品京东配置列表
     * 
     * @return 产品京东配置
     */
    @Override
    public List<ProductJdConfig> selectProductJdConfigList()
    {
        List<ProductJdConfig> list = new ArrayList<>();
        @SuppressWarnings("unchecked")
        Set<String> keys = (Set<String>) redisTemplate().keys(PRODUCT_JD_CONFIG_KEY + "*");
        if (keys != null && !keys.isEmpty()) {
            for (String key : keys) {
                ProductJdConfig config = mapToConfig(key);
                if (config != null) {
                    list.add(config);
                }
            }
        }
        return list;
    }

    /**
     * 从Redis Map转换为ProductJdConfig对象
     */
    private ProductJdConfig mapToConfig(String key) {
        Map<String, Object> map = redisCache.getCacheMap(key);
        if (map != null && !map.isEmpty()) {
            ProductJdConfig config = new ProductJdConfig();
            config.setProductModel((String) map.get("productModel"));
            config.setJdUrl((String) map.get("jdUrl"));
            
            // 处理旧的佣金字段（兼容）
            Object commissionObj = map.get("commission");
            if (commissionObj != null) {
                if (commissionObj instanceof BigDecimal) {
                    config.setCommission((BigDecimal) commissionObj);
                } else if (commissionObj instanceof Number) {
                    config.setCommission(new BigDecimal(commissionObj.toString()));
                } else {
                    config.setCommission(new BigDecimal(commissionObj.toString()));
                }
            }
            
            // 处理佣金（收取）
            Object commissionReceiveObj = map.get("commissionReceive");
            if (commissionReceiveObj != null) {
                if (commissionReceiveObj instanceof BigDecimal) {
                    config.setCommissionReceive((BigDecimal) commissionReceiveObj);
                } else if (commissionReceiveObj instanceof Number) {
                    config.setCommissionReceive(new BigDecimal(commissionReceiveObj.toString()));
                } else {
                    config.setCommissionReceive(new BigDecimal(commissionReceiveObj.toString()));
                }
            }
            
            // 处理佣金（支付）
            Object commissionPayObj = map.get("commissionPay");
            if (commissionPayObj != null) {
                if (commissionPayObj instanceof BigDecimal) {
                    config.setCommissionPay((BigDecimal) commissionPayObj);
                } else if (commissionPayObj instanceof Number) {
                    config.setCommissionPay(new BigDecimal(commissionPayObj.toString()));
                } else {
                    config.setCommissionPay(new BigDecimal(commissionPayObj.toString()));
                }
            }

            Object spd = map.get("sellingPriceDirect");
            if (spd != null) {
                config.setSellingPriceDirect(spd instanceof BigDecimal ? (BigDecimal) spd : new BigDecimal(spd.toString()));
            }
            Object spx = map.get("sellingPriceXianyu");
            if (spx != null) {
                config.setSellingPriceXianyu(spx instanceof BigDecimal ? (BigDecimal) spx : new BigDecimal(spx.toString()));
            }

            return config;
        }
        return null;
    }

    /**
     * 查询产品京东配置
     * 
     * @param productModel 产品型号
     * @return 产品京东配置
     */
    @Override
    public ProductJdConfig selectProductJdConfigByModel(String productModel)
    {
        return mapToConfig(PRODUCT_JD_CONFIG_KEY + productModel);
    }

    /**
     * 新增产品京东配置
     * 
     * @param productJdConfig 产品京东配置
     * @return 结果
     */
    @Override
    public int insertProductJdConfig(ProductJdConfig productJdConfig)
    {
        if (StringUtils.isEmpty(productJdConfig.getProductModel())) {
            return 0;
        }
        String redisKey = PRODUCT_JD_CONFIG_KEY + productJdConfig.getProductModel();
        Map<String, Object> map = new java.util.HashMap<>();
        Map<String, Object> old = redisCache.getCacheMap(redisKey);
        if (old != null && !old.isEmpty()) {
            map.putAll(old);
        }
        map.put("productModel", productJdConfig.getProductModel());
        map.put("jdUrl", productJdConfig.getJdUrl());
        map.put("commission", productJdConfig.getCommission() != null ? productJdConfig.getCommission() : BigDecimal.ZERO);
        map.put("commissionReceive", productJdConfig.getCommissionReceive() != null ? productJdConfig.getCommissionReceive() : BigDecimal.ZERO);
        map.put("commissionPay", productJdConfig.getCommissionPay() != null ? productJdConfig.getCommissionPay() : BigDecimal.ZERO);
        if (productJdConfig.getSellingPriceDirect() != null) {
            map.put("sellingPriceDirect", productJdConfig.getSellingPriceDirect());
        } else {
            map.remove("sellingPriceDirect");
        }
        if (productJdConfig.getSellingPriceXianyu() != null) {
            map.put("sellingPriceXianyu", productJdConfig.getSellingPriceXianyu());
        } else {
            map.remove("sellingPriceXianyu");
        }
        redisCache.setCacheMap(redisKey, map);
        return 1;
    }

    /**
     * 修改产品京东配置
     * 
     * @param productJdConfig 产品京东配置
     * @return 结果
     */
    @Override
    public int updateProductJdConfig(ProductJdConfig productJdConfig)
    {
        return insertProductJdConfig(productJdConfig);
    }

    /**
     * 批量删除产品京东配置
     * 
     * @param productModels 需要删除的产品型号
     * @return 结果
     */
    @Override
    public int deleteProductJdConfigByModels(String[] productModels)
    {
        int count = 0;
        for (String productModel : productModels) {
            if (redisCache.deleteObject(PRODUCT_JD_CONFIG_KEY + productModel)) {
                count++;
            }
        }
        return count;
    }

    /**
     * 删除产品京东配置信息
     * 
     * @param productModel 产品型号
     * @return 结果
     */
    @Override
    public int deleteProductJdConfigByModel(String productModel)
    {
        return redisCache.deleteObject(PRODUCT_JD_CONFIG_KEY + productModel) ? 1 : 0;
    }

    /**
     * 根据产品型号获取京东链接
     * 
     * @param productModel 产品型号
     * @return 京东链接
     */
    @Override
    public String getJdUrlByProductModel(String productModel)
    {
        ProductJdConfig config = selectProductJdConfigByModel(productModel);
        return config != null ? config.getJdUrl() : null;
    }

    /**
     * 获取RedisTemplate
     */
    @SuppressWarnings("rawtypes")
    private org.springframework.data.redis.core.RedisTemplate redisTemplate() {
        return redisCache.redisTemplate;
    }
}

