package com.reyun.taskexecute;

import com.reyun.context.AppUtils;
import com.reyun.model.App;
import com.reyun.service.ReportService;
import com.reyun.service.impl.ComplicatedEventsServiceImpl;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;

/**
 * Created by mxq on 2017/11/1.
 */
public class EventReportCallable implements Callable<Map<String, List>> {

    protected static Logger logger = LoggerFactory.getLogger(EventReportCallable.class);
    private ComplicatedEventsServiceImpl eventStatsService = AppUtils.getApplicationContext().getBean(ComplicatedEventsServiceImpl.class);
    private ReportService reportService = AppUtils.getApplicationContext().getBean(ReportService.class);

    private Map<String, String> conditions;
    private List<JSONObject> selectList;
    private JSONArray groupJsonArray;

    private App app;
    private Long accountid;
    private String startDate;
    private String endDate;
    private String eventCondition;
    private String viewType;

    private Map<String, List> result;

    public EventReportCallable(Map<String, String> conditions, List<JSONObject> selectList, JSONArray groupJsonArray, App app, Long accountid, String startDate, String endDate, String eventCondition, String viewType) {
        this.conditions = conditions;
        this.selectList = selectList;
        this.groupJsonArray = groupJsonArray;
        this.app = app;
        this.accountid = accountid;
        this.startDate = startDate;
        this.endDate = endDate;
        this.eventCondition = eventCondition;
        this.viewType = viewType;
    }

    @Override
    public Map<String, List> call() throws Exception {

        if(null != conditions){
            Map<String, List> responseJson = reportService.reportBySql(conditions);
            //获取时间范围内按照时间粒度的所有日期
            Map<String, String> dateStringMap = eventStatsService.getDateMapByViewFlag(startDate, endDate, viewType);
            //格式化数据
            result = eventStatsService.formatComplicatedEventResponse(app, accountid, responseJson, dateStringMap, groupJsonArray, selectList);
        }else{
            //查询合计
            List<JSONObject> totalValue = eventStatsService.queryDistinctTotalData(app.getId(), accountid, startDate, endDate, eventCondition, viewType);
            result = new HashMap<>();
            result.put("totalval",totalValue);
        }
        return result;
    }
}
