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

import cn.com.countrygarden.bi.main.core.ResultGenerator;
import cn.com.countrygarden.bi.main.repository.ManageTopicRepository;
import cn.com.countrygarden.bi.main.util.RedisUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.microsoft.sqlserver.jdbc.SQLServerException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.smartframework.common.utils.ExDateUtils;
import org.smartframework.common.utils.ExRequestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.CannotGetJdbcConnectionException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.*;

@Controller("operationDataController")
@RequestMapping("/api/biapp/data/opetation")
public class OperationDataController {

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

    @Autowired
    private ManageTopicRepository manageTopicRepository;

    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 = "/chargeRate", produces = "application/json;charset=utf-8", method = RequestMethod.GET)
    public @ResponseBody
    Object chargeRate(HttpServletRequest request) throws IOException {
        List<Map<String, Object>> multiRateList = getMultiChargeRage(request);
        return ResultGenerator.genSuccessResult(multiRateList);
    }

    /**
     * 基础数据
     *
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/overview/realtime", produces = "application/json;charset=utf-8", method = RequestMethod.GET)
    public @ResponseBody
    Object overviewWithRealtime(HttpServletRequest request) throws IOException {
        Map<String, Object> paramMap = ExRequestUtils.buildParametersMap(request);
        Map<String, Object> dataMap = new HashMap<>();

        Object overviewData = null;
        Map<String, Object> resultData;
        String commonDataJson = hgetFromRedis("getcommondatalist");
        if (commonDataJson != null && !"".equals(commonDataJson)) {
            resultData = JSON.parseObject(commonDataJson, new TypeReference<Map<String, Object>>() {
            });
            overviewData = resultData.get("jyzt");
        } else {
            List<Map<String, Object>> manageTopicCommDataList = manageTopicRepository.queryManageTopicCommData(paramMap);
            if (manageTopicCommDataList != null && manageTopicCommDataList.size() > 0) {
                overviewData = manageTopicCommDataList.get(0);
            }
        }

        List<Map<String, Object>> realtimes = new ArrayList<>();
        Map<String, Object> realtime = new HashMap<>();
        try {
            realtimes = manageTopicRepository.queryBrssZrzjZrcwsrData(paramMap);
        } catch (CannotGetJdbcConnectionException | SQLServerException e) {
            e.printStackTrace();
        }
        if (realtimes != null && realtimes.size() == 1) {
            realtime = realtimes.get(0);
        }

        List<Map<String, Object>> multiRateList = getMultiChargeRage(request);

        dataMap.put("realtime", realtime);
        dataMap.put("overview", overviewData);
        dataMap.put("rate", multiRateList);

        return ResultGenerator.genSuccessResult(dataMap);
    }

    /**
     * 基础数据
     *
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/overview", produces = "application/json;charset=utf-8", method = RequestMethod.GET)
    public @ResponseBody
    Object overview(HttpServletRequest request) throws IOException {
        Map<String, Object> paramMap = ExRequestUtils.buildParametersMap(request);
        Map<String, Object> dataMap = new HashMap<>();

        Map<String, Object> overviewData = new HashMap<>();
        List<Map<String, Object>> manageTopicCommDataList = manageTopicRepository.queryManageTopicCommData(paramMap);
        if (manageTopicCommDataList != null && manageTopicCommDataList.size() > 0) {
            overviewData = manageTopicCommDataList.get(0);
        }
        dataMap.put("overview", overviewData);

        List<Map<String, Object>> multiRateList = getMultiChargeRage(request);
        dataMap.put("rate", multiRateList);

        return ResultGenerator.genSuccessResult(dataMap);
    }

    /**
     * 物业业态饼图信息
     *
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/property", produces = "application/json;charset=utf-8", method = RequestMethod.GET)
    public @ResponseBody
    Object property(HttpServletRequest request) throws IOException {
        Map<String, Object> data = getPieChartsData(request);

        return ResultGenerator.genSuccessResult(data.get("wyyt"));
    }

    /**
     * 收款方式饼图信息
     *
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/payment", produces = "application/json;charset=utf-8", method = RequestMethod.GET)
    public @ResponseBody
    Object payment(HttpServletRequest request) throws IOException {
        Map<String, Object> data = getPieChartsData(request);
        return ResultGenerator.genSuccessResult(data.get("skfs"));
    }

    /**
     * 开发主体饼图信息
     *
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/developer", produces = "application/json;charset=utf-8", method = RequestMethod.GET)
    public @ResponseBody
    Object developer(HttpServletRequest request) throws IOException {
        Map<String, Object> data = getPieChartsData(request);

        return ResultGenerator.genSuccessResult(data.get("kfzt"));
    }

    /**
     * 获取饼图信息
     *
     * @param request
     * @return
     * @throws IOException
     */
    private Map<String, Object> getPieChartsData(HttpServletRequest request) throws IOException {
        Map<String, Object> paramMap = ExRequestUtils.buildParametersMap(request);
        Map<String, Object> data;
        String jsonData = hgetFromRedis("queryThreePieCharts");
        if (jsonData != null && !"".equals(jsonData)) {
            data = JSON.parseObject(jsonData, new TypeReference<Map<String, Object>>() {
            });
        } else {
            data = manageTopicRepository.queryThreePieCharts(paramMap);
        }
        return data;
    }

    /**
     * 查询本年累计追缴率,本年综合收费率,本年欠费追缴率
     *
     * @return
     * @throws IOException
     */
    private List<Map<String, Object>> getMultiChargeRage(HttpServletRequest request) throws IOException {
        Map<String, Object> paramMap = ExRequestUtils.buildParametersMap(request);

        List<Map<String, Object>> data = new ArrayList<>();
        String jsonData = hgetFromRedis("queryMultiRate");
        if (jsonData != null && !"".equals(jsonData)) {
            /* 将JSON文件转换成List */
            JavaType javaType = getCollectionType(ArrayList.class, Map.class);
            try {
                data = mapper.readValue(jsonData, javaType);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            data = manageTopicRepository.queryMultiRate(paramMap);
        }

        return data;
    }
}
