package com.huatek.busi.service.impl.report;

import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import com.alibaba.dubbo.config.annotation.Service;
import com.google.common.collect.Maps;
import com.huatek.busi.service.impl.report.helper.ReportImpl;
import com.huatek.busi.service.report.BusiCommonReportService;
import com.huatek.busi.service.report.BusiExportReportService;
import com.huatek.torch.frame.exception.OwlException;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
@Service(interfaceClass = BusiExportReportService.class)
@Transactional(rollbackFor = Exception.class)
public class BusiExportReportServiceImpl implements BusiExportReportService, ApplicationContextAware {
    /** 实现类缓存 */
    private final Map<String, BusiCommonReportService> IMPLS = Maps.newConcurrentMap();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        Map<String, Object> configOptionImplMap = applicationContext.getBeansWithAnnotation(ReportImpl.class);
        if (CollectionUtils.isEmpty(configOptionImplMap)) {
            log.debug("impls is empty!");
            return;
        }
        for (Entry<String, Object> entry : configOptionImplMap.entrySet()) {
            ReportImpl annotation = applicationContext.findAnnotationOnBean(entry.getKey(), ReportImpl.class);
            if (annotation == null) {
                log.debug("this is not my dish");
                continue;
            }
            BusiCommonReportService service = (BusiCommonReportService)entry.getValue();
            for (String type : annotation.exportTypes()) {
                log.debug("报告实现类{}：{}", type, service);
                IMPLS.put(type, service);
            }
        }
    }

    private BusiCommonReportService serviceImpl(String reprotType) {
        BusiCommonReportService service = IMPLS.get(reprotType);
        if (service == null) {
            throw new OwlException("找不到实现类：" + reprotType);
        }
        return service;
    }

    @Override
    public Map<String, Object> buildExportData(String exportType, List<String> sernsors, String exportTime, String startTime,String endTime) {
        return serviceImpl(exportType).buildExportData(exportType, sernsors, exportTime,startTime,endTime);
    }
}