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.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;

    public static String PREFIX_CATEGORY_COUNT = "CATEGORY_COUNT_";


    @Override
    public int equipCategoryStatistics(String bizOrgCode, SourceTypeEnum sourceType, String categoryCode, boolean isRoot) {
        // 计算处通用code,用来上下级匹配如12001010000->1200101
        String treeCode = subStringZero(categoryCode);
        if (!isRoot && treeCode.length() % 2 != 0) {
            treeCode = treeCode + "0";
        }
        Set<String> keys = redisUtil.getKeys(buildPattenKey(bizOrgCode, sourceType.getCode(), treeCode));
        if (!keys.isEmpty()) {
            //求和
            return this.sumNumber(keys);
        } else {
            return 0;
        }
    }

    /**
     * 系统初始化时调用刷新缓存
     * @param sourceType 缓存类型
     */
    @Override
    public void initAllCategoryStatisticsData(SourceTypeEnum sourceType) {
        //按照类型插入缓存
        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());
                }
            }
        }
    }

    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 buildPattenKey(String bizOrgCode, String sourceType, String treeCode) {
        return PREFIX_CATEGORY_COUNT + bizOrgCode + "*_" + sourceType + "_" + treeCode + "*";
    }

}
