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

import cn.com.countrygarden.bi.main.core.Result;
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.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.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.text.SimpleDateFormat;
import java.util.*;

@Controller("rankingDataController")
@RequestMapping("/api/biapp/data/ranking")
public class RankingDataController {

    private String hkeyPrefix = "bgywybi-";// redis 的大KEY的前缀
    private String TW_ERP_UPLOADFILES_PREFIX = "http://218.13.58.36:8008/HM/M_Main";

    @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 = "/charge", produces = "application/json;charset=utf-8", method = RequestMethod.GET)
    public @ResponseBody
    Result chargeRate(HttpServletRequest request) throws IOException {
        Map<String, Object> paramMap = ExRequestUtils.buildParametersMap(request);
        List<Map<String, Object>> chargeRateList = new ArrayList<>();
        String queryChargeRateJson = hgetFromRedis("queryChargeRate");
        if (queryChargeRateJson != null && !"".equals(queryChargeRateJson)) {
            /* 将JSON文件转换成List */
            JavaType javaType = getCollectionType(ArrayList.class, Map.class);
            try {
                chargeRateList = mapper.readValue(queryChargeRateJson, javaType);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            chargeRateList = manageTopicRepository.queryChargeRate(paramMap);
        }
        /* 获取昨天的数据 */
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        String yesterday_hkeySuffix = new SimpleDateFormat("yyyyMMdd").format(cal.getTime());
        String yesterday_HKEY = hkeyPrefix + yesterday_hkeySuffix;
        String getYesterdayJson = RedisUtils.hget(yesterday_HKEY, "queryChargeRate");
        List<Map<String, Object>> yesterdayResultData = JSON.parseObject(getYesterdayJson,
                new TypeReference<List<Map<String, Object>>>() {
                });
		/* 将今天跟昨天的数据进行对比 */
        if (yesterdayResultData != null) {
            for (int i = 0; i < chargeRateList.size(); i++) {
                for (int j = 0; j < yesterdayResultData.size(); j++) {
                    Map<String, Object> ymap = yesterdayResultData.get(j);
                    Map<String, Object> tmap = chargeRateList.get(i);
                    if (String.valueOf(tmap.get("organname")).equals(String.valueOf(ymap.get("organname")))) {
                        String photo = tmap.get("photo").toString();
                        tmap.put("photo", TW_ERP_UPLOADFILES_PREFIX + photo.substring(2));

                        int tindex = 0;
                        float tzhnum = 0f;
                        int yindex = 0;
                        float yzhnum = 0f;
                        try {
                            tindex = Integer.parseInt(tmap.get("ROWINDEX").toString());
                            tzhnum = Float.parseFloat(tmap.get("zh").toString());
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                        }
                        try {
                            yindex = Integer.parseInt(ymap.get("ROWINDEX").toString());
                            yzhnum = Float.parseFloat(ymap.get("zh").toString());
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                        }
                        float upnum = tindex - yindex;
                        float upzhnum = tzhnum - yzhnum;
                        tmap.put("upnum", upnum);
                        tmap.put("upzhnum", upzhnum);
                    }
                }
            }
        }

        return ResultGenerator.genSuccessResult(chargeRateList);
    }

    /**
     * 查询各区域追缴率排行
     *
     * @return
     */
    @RequestMapping(value = "/recovered", produces = "application/json;charset=utf-8", method = RequestMethod.GET)
    public @ResponseBody
    Result recovered(HttpServletRequest request) throws IOException {
        Map<String, Object> paramMap = ExRequestUtils.buildParametersMap(request);
        List<Map<String, Object>> chaseRateList = new ArrayList<>();
        String queryChaseRateJson = hgetFromRedis("queryChaseRate");
        if (queryChaseRateJson != null && !"".equals(queryChaseRateJson)) {
			/* 将JSON文件转换成List */
            JavaType javaType = getCollectionType(ArrayList.class, Map.class);
            try {
                chaseRateList = mapper.readValue(queryChaseRateJson, javaType);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            chaseRateList = manageTopicRepository.queryChaseRate(paramMap);
        }
		/* 获取昨天的数据 */
        Calendar cal = Calendar.getInstance();
        cal.add(Calendar.DATE, -1);
        String yesterday_hkeySuffix = new SimpleDateFormat("yyyyMMdd").format(cal.getTime());
        String yesterday_HKEY = hkeyPrefix + yesterday_hkeySuffix;
        String getYesterdayJson = RedisUtils.hget(yesterday_HKEY, "queryChaseRate");
        List<Map<String, Object>> yesterdayResultData = JSON.parseObject(getYesterdayJson,
                new TypeReference<List<Map<String, Object>>>() {
                });
		/* 将今天跟昨天的数据进行对比 */
        if (yesterdayResultData != null) {
            for (int i = 0; i < chaseRateList.size(); i++) {
                for (int j = 0; j < yesterdayResultData.size(); j++) {
                    Map<String, Object> ymap = yesterdayResultData.get(j);
                    Map<String, Object> tmap = chaseRateList.get(i);
                    if (String.valueOf(tmap.get("organname")).equals(String.valueOf(ymap.get("organname")))) {
                        String photo = tmap.get("photo").toString();
                        tmap.put("photo", TW_ERP_UPLOADFILES_PREFIX + photo.substring(2));

                        int tindex = 0;
                        float tzhnum = 0f;
                        int yindex = 0;
                        float yzhnum = 0f;
                        try {
                            tindex = Integer.parseInt(tmap.get("ROWINDEX").toString());
                            tzhnum = Float.parseFloat(tmap.get("zh").toString());
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                        }
                        try {
                            yindex = Integer.parseInt(ymap.get("ROWINDEX").toString());
                            yzhnum = Float.parseFloat(ymap.get("zh").toString());
                        } catch (NumberFormatException e) {
                            e.printStackTrace();
                        }
                        int upnum = tindex - yindex;
                        float upzhnum = tzhnum - yzhnum;
                        tmap.put("upnum", upnum);
                        tmap.put("upzhnum", upzhnum);
                    }
                }
            }
        }

        return ResultGenerator.genSuccessResult(chaseRateList);
    }

    /**
     * 各区域累计实收排行
     *
     * @param request
     * @return
     * @throws IOException
     */
    @RequestMapping(value = "/totalCharge", produces = "application/json;charset=utf-8", method = RequestMethod.GET)
    public @ResponseBody
    Result totalCharge(HttpServletRequest request) throws IOException {
        Map<String, Object> paramMap = ExRequestUtils.buildParametersMap(request);
        List<Map<String, Object>> realCollectMoneyList = new ArrayList<Map<String, Object>>();
        String queryRealCollectMoneyJson = hgetFromRedis("queryRealCollectMoney");
        if (queryRealCollectMoneyJson != null && !"".equals(queryRealCollectMoneyJson)) {
			/* 将JSON文件转换成List */
            JavaType javaType = getCollectionType(ArrayList.class, Map.class);
            try {
                realCollectMoneyList = mapper.readValue(queryRealCollectMoneyJson,
                        javaType);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            realCollectMoneyList = manageTopicRepository.queryRealCollectMoney(paramMap);
        }

        return ResultGenerator.genSuccessResult(realCollectMoneyList);
    }
}
