package com.yeejoin.equipmanage.service.impl;

import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.equipmanage.common.enums.SourceTypeEnum;
import com.yeejoin.equipmanage.service.ICarService;
import com.yeejoin.equipmanage.service.IEquipmentDetailService;
import com.yeejoin.equipmanage.service.ISourceStatistics;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.typroject.tyboot.core.foundation.context.SpringContextHelper;

import java.lang.reflect.Method;
import java.util.Set;

/**
 * @author DELL
 */
@Service
public class SourcesStatisticsImpl implements ISourceStatistics {

    @Autowired
    private RedisUtils redisUtil;


    @Override
    public int equipCategoryStatistics(String bizOrgCode, SourceTypeEnum sourceType, String categoryCode) {
        // 计算处通用code,用来上下级匹配如12001010000->1200101
        String treeCode = subStringZero(categoryCode);
        Set<String> keys = redisUtil.getKeys(buildKey(bizOrgCode, sourceType.getCode(), treeCode));
        if (keys.size() > 0) {
            //求和
            return this.sumNumber(keys);
        } else {
            //按照类型插入缓存
            Object bean = SpringContextHelper.getBean(sourceType.getBeanName());
            Method[] methods = bean.getClass().getDeclaredMethods();
            for (Method method : methods) {
                if (method.getName().equals(sourceType.getMethodName())) {
                    try {
                        method.invoke(bean);
                    } catch (Exception e) {
                        throw new RuntimeException("更新redis数据失败" + e.getMessage());
                    }
                }
            }
            return this.sumNumber(keys);
        }
    }

    private int sumNumber(Set<String> keys) {
        return keys.stream().filter(k -> redisUtil.get(k) != null).mapToInt(k -> Integer.parseInt(redisUtil.get(k).toString())).sum();
    }

    private String subStringZero(String categoryCode) {
        String reverse = new StringBuffer(categoryCode).reverse().toString();
        int noZero = Integer.parseInt(reverse);
        return new StringBuffer(String.valueOf(noZero)).reverse().toString();
    }

    private String buildKey(String bizOrgCode, String sourceType, String treeCode) {
        return bizOrgCode + "*_" + sourceType + "_" + treeCode + "*";
    }
}
