package com.bcxin.ins.supply.business;

import com.bcxin.ins.supply.SupplyType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.annotation.Annotation;
import java.util.HashMap;
import java.util.Map;

/**
 * 供应商业务注解策略工厂
 * @author hzp
 * @date 2018/06/12
 */
@Component
public class BizStrategyFactory {

    private Map<String, BizStrategy> contextStrategy = new HashMap<String,BizStrategy>();

    public Map<String, BizStrategy> getContextStrategy() {
        return contextStrategy;
    }

    /**
     * 将Autowired放在set上
     * 由于这边要重构key值，所以不直接放在成员变量上(默认是以类型作为key)
     * @param contextStrategy
     */
    @Autowired
    public void setContextStrategy(Map<String, BizStrategy> contextStrategy) {
        Map<String, BizStrategy> newMap=new HashMap<String, BizStrategy>();
        for(String key : contextStrategy.keySet()){
            BizStrategy biz=contextStrategy.get(key);

            //获取该策略的注解
            SupplyType supplyTypeAnno = handleAnnotation(biz);
            //根据类别判断是否该注解
            if(supplyTypeAnno!=null){
                newMap.put(supplyTypeAnno.type().getKey(),biz);
            }
        }
        this.contextStrategy = newMap;
    }

    public BizStrategy getStrategy(String type){
        BizStrategy businessStrategy= this.contextStrategy.get(type);
        if(businessStrategy==null){
            throw new RuntimeException("策略获得失败");
        }
        return businessStrategy;
    }

    /**
     * 处理注解，我们传入一个策略类，返回它的注解
     */
    private SupplyType handleAnnotation(BizStrategy clazz) {
        Annotation[] annotations = clazz.getClass().getDeclaredAnnotations();
        if (annotations == null || annotations.length == 0) {
            return null;
        }
        for (int i = 0; i < annotations.length; i++) {
            if (annotations[i] instanceof SupplyType) {
                return (SupplyType) annotations[i];
            }
        }
        return null;
    }
}
