package com.fs.store.strategy;

import cn.hutool.core.util.ObjectUtil;
import com.fs.store.domain.FsShippingTemplates;
import com.fs.store.domain.FsShippingTemplatesFree;
import com.fs.store.domain.FsShippingTemplatesRegion;
import com.fs.store.enums.ShippingTempEnum;
import com.fs.store.service.IFsShippingTemplatesFreeService;
import com.fs.store.service.IFsShippingTemplatesRegionService;
import com.fs.store.service.IFsShippingTemplatesService;
import com.fs.store.strategy.impl.CountBasedStrategy;
import com.fs.store.strategy.impl.WeightBasedStrategy;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.ObjectUtils;
import org.apache.http.util.Asserts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 运费模板管理器
 */
@Slf4j
@Service
public class ShippingTemplateManager {
    @Autowired
    private IFsShippingTemplatesService fsShippingTemplatesService;
    @Autowired
    private IFsShippingTemplatesRegionService fsShippingTemplatesRegionService;
    @Autowired
    private IFsShippingTemplatesFreeService fsShippingTemplatesFreeService;

    private final Map<Long, ShippingTemplate> TEMPLATES = new ConcurrentHashMap<>();

    private static final Map<Integer, String> TEMPLATE_TYPE_MAP = new ConcurrentHashMap<>();
    static {
        TEMPLATE_TYPE_MAP.put(1,"count");
        TEMPLATE_TYPE_MAP.put(2,"weight");
        TEMPLATE_TYPE_MAP.put(3,"volume");
    }

    @PostConstruct
    public void init(){
        log.info("正在初始化运费模板管理器...");
        // 查询运费模板
        List<FsShippingTemplates> fsShippingTemplates = fsShippingTemplatesService.listAllTemplate();
        for (FsShippingTemplates template : fsShippingTemplates) {
            String type = TEMPLATE_TYPE_MAP.get(template.getType());
            Asserts.notNull(type,"不支持的模板类型");

            ShippingTemplate shippingTemplate = new ShippingTemplate(template.getId(),type);

            log.info("正在加载模板配送区域及运费");
            List<FsShippingTemplatesRegion> fsShippingTemplatesRegions = fsShippingTemplatesRegionService.selectTempRegionByTempIdAndCityId(template.getId());
            for (FsShippingTemplatesRegion templatesRegion : fsShippingTemplatesRegions) {
                Region region = new Region();
                region.setCityId(templatesRegion.getCityId());
                // 如果是按重量
                if(ObjectUtil.equal(templatesRegion.getType(), ShippingTempEnum.TYPE_2.getValue())){
                    region.setFirstWeight(templatesRegion.getFirst());
                    region.setFirstWeightFee(templatesRegion.getFirstPrice());
                    region.setAdditionalWeight(templatesRegion.getContinues());
                    region.setAdditionalWeightFee(templatesRegion.getContinuePrice());
                } else if(ObjectUtil.equal(templatesRegion.getType(),ShippingTempEnum.TYPE_1.getValue())){
                    region.setFirstItem(templatesRegion.getFirst());
                    region.setFirstItemFee(templatesRegion.getFirst());
                    region.setAdditionalItemFee(templatesRegion.getFirstPrice());
                } else if(ObjectUtil.equal(templatesRegion.getType(), ShippingTempEnum.TYPE_3.getValue())){
                    region.setFirstVolume(templatesRegion.getFirst());
                    region.setFirstVolumeFee(templatesRegion.getFirstPrice());
                    region.setAdditionalVolume(templatesRegion.getContinues());
                    region.setAdditionalVolumeFee(templatesRegion.getContinuePrice());
                }
                shippingTemplate.addRegion(region);
            }


            log.info("模板加载区域完成: {}个", fsShippingTemplatesRegions.size());

            log.info("正在加载模板包邮规则");
            List<FsShippingTemplatesFree> freeShippingRules = fsShippingTemplatesFreeService.selectFreeShippingRuleByTempId(template.getId());
            for (FsShippingTemplatesFree freeShippingRule : freeShippingRules) {
                FreeShippingRule rule = new FreeShippingRule();
                rule.setRegion(freeShippingRule.getCityId());

                if(ObjectUtil.equal(freeShippingRule.getType(), ShippingTempEnum.TYPE_2.getValue())){
                    rule.setMinWeight(freeShippingRule.getNumber());
                    rule.setMinAmount(freeShippingRule.getPrice());
                } else if(ObjectUtil.equal(freeShippingRule.getType(),ShippingTempEnum.TYPE_1.getValue())){
                    rule.setMinCount(freeShippingRule.getNumber());
                    rule.setMinAmount(freeShippingRule.getPrice());
                } else if(ObjectUtil.equal(freeShippingRule.getType(), ShippingTempEnum.TYPE_3.getValue())){
                    rule.setMinVolume(freeShippingRule.getNumber());
                    rule.setMinAmount(freeShippingRule.getPrice());
                }

                shippingTemplate.addFreeShippingRule(rule);
            }
            log.info("模板包邮规则加载完成: {} 个", freeShippingRules);

            this.addTemplate(shippingTemplate);
        }
        log.info("运费模板管理器初始化完成: {}个", fsShippingTemplates.size());
    }

    public void addTemplate(ShippingTemplate template) {
        TEMPLATES.put(template.getId(), template);
    }

    public ShippingTemplate getTemplate(Long templateId) {
        return TEMPLATES.get(templateId);
    }

    public BigDecimal calculateShippingFee(Long templateId, ShippingOrder order) {
        ShippingTemplate template = TEMPLATES.get(templateId);
        if (template == null) {
            throw new IllegalArgumentException("找不到运费模板: " + templateId);
        }
        return template.calculateShippingFee(order);
    }
}

