package com.nokia.tsl_data.service;

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

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.nokia.tsl_data.dao.AreaInfoDao;
import com.nokia.tsl_data.dao.HighQualityCountDao;

/**
 * 处理客户端统计数据
 */
@Service
public class HighQualityCountService {

    @Autowired
    private HighQualityCountDao highQualityCountDao;

    @Autowired
    private AreaInfoDao areaInfoDao;

    /**
     * 根据日期查询当月从1日起每天每个地市的客户端统计数据
     * 
     * @param day
     * @return
     */
    public Map<String, int[]> getComplaintsForDay(String day) {
        // 预处理时间
        String monthId = day.substring(0, 6);
        int dayIndex = Integer.parseInt(day.substring(6));

        List<String> allCityName = areaInfoDao.getAllCityName();
        Map<String, int[]> result = new HashMap<>();
        // 每个地市一个数组，数组保存dayIndex天数据
        for (String areaName : allCityName) {
            result.put(areaName, new int[dayIndex + 1]);
        }
        // 全省
        result.put("全省", new int[dayIndex + 1]);

        for (int i = 1; i <= dayIndex; i++) {
            // 拼接一个表示天的字符串，天如果小于10要补0
            String newDay = i >= 10 ? monthId + i : monthId + "0" + i;
            // 这里有一个查询操作
            List<Map<String, Object>> totalComplaintsForDay = highQualityCountDao
                    .selectTotalComplaintsForDay(newDay);
            int provinceAll = 0;
            for (Map<String, Object> map : totalComplaintsForDay) {
                String city = map.get("businoareaname").toString();
                // 这里雄安新区需要特殊处理一下
                city = city.equals("雄安新区") ? "雄安" : city;
                int[] arr = result.get(city);
                arr[i - 1] = Integer.parseInt(map.get("total_complaints").toString());
                provinceAll += arr[i - 1];
                if (i == dayIndex) {
                    arr[dayIndex] = arr[dayIndex - 1];
                }
            }
            result.get("全省")[i - 1] = provinceAll;
            if (i == dayIndex) {
                result.get("全省")[dayIndex] = provinceAll;
            }
        }

        // 以上得到的result是每天累加，需要计算一下每天的增量
        for (int[] arr : result.values()) {
            for (int i = dayIndex - 1; i >= 1; i--) {
                arr[i] = arr[i] - arr[i - 1];
            }
        }
        return result;
    }
}
