package cn.edu.whu.boot.statistics.service;

import cn.edu.whu.boot.statistics.mapper.ProgressStatMapper;
import cn.edu.whu.boot.xml.xmlreader.XmlTemplateReader;
import cn.edu.whu.boot.xml.xmlreader.bean.Config;
import cn.edu.whu.boot.xml.xmlreader.bean.Table;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class ProgressStatService {

    @Autowired
    ProgressStatMapper progressStatMapper;

    @Value("#{'${XmlFilePath}' + '/'}")
    private String XML_FOLDER;

    private static final DecimalFormat DOUBLE_FORMAT = new DecimalFormat("#.000");

    public String getTasks() {
        JSONArray result = new JSONArray();
        result.addAll(progressStatMapper.getTasks());
        return result.toJSONString();
    }

    public String getTables(String tskName) {

        String fileName = progressStatMapper.getTaskXmlName(tskName);
        String path = XML_FOLDER + fileName + ".xml";
        Config config = XmlTemplateReader.read(path);
        Map<String, Table> Tbls =  config.getRootTables();
//        Map<String, Table> Tbls =  config.getTables();
        JSONObject result = new JSONObject(true);
        Tbls.forEach((k, v)->{
            result.put(k, v.getName());
        });

        return result.toJSONString();

    }
    public String getAllTables(String tskName) {

        String fileName = progressStatMapper.getTaskXmlName(tskName);
        String path = XML_FOLDER + fileName + ".xml";
        Config config = XmlTemplateReader.read(path);
        Map<String, Table> Tbls =  config.getTables();
        JSONObject result = new JSONObject(true);
        Tbls.forEach((k, v)->{
            result.put(k, v.getName());
        });

        return result.toJSONString();

    }


    public String stat(String operation, String tskName, String tblName, String startTime, String endTime ) {

        String taskDBName = progressStatMapper.getTaskDBName(tskName);
        tblName = '"' + taskDBName + '"' + "." + '"' + tblName + '"';

        //拼写起始时间和结束时间
        //这里是无奈的写法，如果使用通配符，传入数据类型应该是 LocalDateTime
        //但目前系统没有统一日期格式，所以暂时使用字符串拼接传入日期
        startTime = "'" + startTime + "'";
        endTime = "'" + endTime + "'";

        //本表中记录总数
        int count = progressStatMapper.getCount(tblName);

        //在查询时间内的总数
        int countInAPeriod = progressStatMapper.getCountInAPeriod(tblName, startTime, endTime);

        JSONObject jsonResult = new JSONObject(true);
        jsonResult.put("total", countInAPeriod);

        List<HashMap<String, Long>> statData = null;
        if ("day".equals(operation)) {
            statData = progressStatMapper.statDaily(tblName, startTime, endTime);
        } else {
            statData = progressStatMapper.statMonthly(tblName, startTime, endTime);
        }

        JSONArray ratioArray = new JSONArray();
        for (int i = 0; i < statData.size(); i++) {
            HashMap<String, Long> record = statData.get(i);
            JSONObject ratio = new JSONObject(true);
            ratio.put("date", record.get("date"));
            ratio.put("ratio", DOUBLE_FORMAT.format(record.get("count")/(double)count));
            ratioArray.add(ratio);
        }

        jsonResult.put("data", statData);
        jsonResult.put("ratio", ratioArray);
        return jsonResult.toJSONString();
    }


}
