package cn.com.countrygarden.bi.main.controller;

import cn.com.countrygarden.bi.main.repository.ResourceCommNumRepository;
import cn.com.countrygarden.bi.main.util.RedisUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import org.smartframework.common.utils.ExDateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.io.IOException;
import java.util.*;

@Controller("resourceDataController")
@RequestMapping("/api/biapp/data/resource")
public class ResourceDataController {

    private String hkeyPrefix = "bgywybi-";// redis 的大KEY的前缀

    @Autowired
    private ResourceCommNumRepository resourceCommNumRepository;

    /**
     * 传入小key ，获取redis 中的值
     *
     * @param field
     * @return
     */
    private String hgetFromRedis(String field) {
        String hkeySuffix = ExDateUtils.format(new Date(), "yyyyMMdd");
        String HKEY = hkeyPrefix + hkeySuffix;
        // String HKEY = hkeyPrefix + "20170623";
        String getmapdatalistJson = RedisUtils.hget(HKEY, field);
        return getmapdatalistJson;
    }

    /**
     * 项目分布
     *
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/overview", produces = "application/json;charset=utf-8", method = RequestMethod.GET)
    public Object distribution() throws IOException {
        Map<String, Object> resultMap = new HashMap<String, Object>();
        List<Map<String, Object>> mapDataList;

        // 从 redis 读取
        String distJson = hgetFromRedis("getmapdatalist");
        if (distJson != null && !"".equals(distJson)) {
            mapDataList = JSON.parseObject(distJson, new TypeReference<List<Map<String, Object>>>() {
            });
        } else {
            mapDataList = resourceCommNumRepository.queryProNumAndBuildArea(null);
        }

        List<Map<String, Object>> distData = new ArrayList<>();


        for (int i = 0; i < mapDataList.size(); i++) {
            Map<String, Object> map = mapDataList.get(i);

            Map<String, Object> item = new HashMap<>();
            item.put("ProvinceName", map.get("Province"));
            item.put("Communitys", map.get("CommNum"));
            item.put("Area", map.get("BuildArea"));

            distData.add(item);
        }

        resultMap.put("resultCode", 0);
        resultMap.put("resultMsg", "OK");
        resultMap.put("data", distData);

        return resultMap;
    }
}
