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

import cn.com.countrygarden.bi.main.core.ResultGenerator;
import cn.com.countrygarden.bi.main.repository.ResourceRepository;
import cn.com.countrygarden.bi.main.repository.RoomStateRepository;
import cn.com.countrygarden.bi.main.util.RedisUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import org.smartframework.common.utils.ExDateUtils;
import org.smartframework.common.utils.ExRequestUtils;
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.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

@Controller("houseDataController")
@RequestMapping("/api/biapp/data/house")
public class HouseDataController {

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

    @Autowired
    private RoomStateRepository roomStateRepository;
    @Autowired
    private ResourceRepository resourceRepository;


    public final static ObjectMapper mapper = new ObjectMapper();

    /**
     * 传入小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;
    }

    /**
     * 获取泛型的Collection Type
     *
     * @param collectionClass 泛型的Collection
     * @param elementClasses  元素类
     * @return JavaType Java类型
     * @since 1.0
     */
    public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
        return mapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
    }

    /**
     * 查询接管面积
     *
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/distribution", produces = "application/json;charset=utf-8")
    public @ResponseBody
    Object distribution(HttpServletRequest request) throws IOException {
        Map<String, Object> paramMap = ExRequestUtils.buildParametersMap(request);
        Map<String, Object> dataMap = new HashMap<>();
        Map<String, Object> areaMap = new HashMap<>();
        List<Map<String, Object>> roomStateList;
        String queryRoomStateJson = hgetFromRedis("queryRoomState");
        if (queryRoomStateJson != null && !"".equals(queryRoomStateJson)) {
            JavaType javaType = getCollectionType(ArrayList.class, Map.class);
            roomStateList = mapper.readValue(queryRoomStateJson, javaType);
        } else {
            roomStateList = roomStateRepository.queryRoomState(paramMap);
        }

        Map<String, Object> resourceSummary = getResourceSummary();
        if (!resourceSummary.isEmpty()) {
            areaMap.put("BasementArea", resourceSummary.get("BasementArea"));
            areaMap.put("BusinessArea", resourceSummary.get("BusinessArea"));
            areaMap.put("GardenArea", resourceSummary.get("GardenArea"));
            areaMap.put("ShareArea", resourceSummary.get("ShareArea"));
            areaMap.put("InnerArea", resourceSummary.get("InnerArea"));
        }

        dataMap.put("roomState", roomStateList);
        dataMap.put("area", areaMap);

        return ResultGenerator.genSuccessResult(dataMap);
    }

    /**
     * 获取房屋基础数据
     *
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/summary", produces = "application/json;charset=utf-8")
    public @ResponseBody
    Object summary(@RequestParam(value = "CommID", defaultValue = "") String commID,
                   @RequestParam(value = "OrganCode", defaultValue = "") String organCode) throws IOException {
        Map<String, Object> resultMap = new HashMap<>();
        Map<String, Object> data = getResourceSummary();

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

    private Map<String, Object> getResourceSummary() {
        Map<String, Object> data = new HashMap<>();

        String jsonData = hgetFromRedis("resource:summary");
        if (jsonData != null && !"".equals(jsonData)) {
            data = JSON.parseObject(jsonData, new TypeReference<Map<String, Object>>() {
            });
        } else {
            Map<String, Object> resources = resourceRepository.queryResourceSummary();
            if (!resources.isEmpty()) {
                Object value;
                for (String key : resources.keySet()) {
                    value = resources.get(key);
                    String[] keys = key.split("_");

                    Map<String, String> item = new HashMap<>();
                    item.put("CNName", keys[0]);
                    item.put("data", value.toString());

                    data.put(keys[1], item);
                }
                String HKEY = hkeyPrefix + ExDateUtils.format(new Date(), "yyyyMMdd");
                RedisUtils.hset(HKEY, "resource:summary", JSONObject.toJSONString(data));
            }
        }

        return data;
    }
}
