package com.bcxin.ins.coninsweb.order.stragegy.order;

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 zxf
 * @date 2018/08/30
 * @说明 策略方案提议及案例提供人：hzp 2018/06/12
 */
@Component
public class OrderSupplyStragegyFactory {
    private static Map<String, OrderSupplyStrategy> contextStrategy;
    public Map<String, OrderSupplyStrategy> getContextStrategy() {
        return contextStrategy;
    }

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

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

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

    /**
     * 处理注解，我们传入一个策略类，返回它的注解
     */
    private OrderSupplyType handleAnnotation(OrderSupplyStrategy 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 OrderSupplyType) {
                return (OrderSupplyType) annotations[i];
            }
        }
        return null;
    }

}
