/**
 * Description: CmCreditRecord控制器
 * Copyright:   Copyright (c)2015
 * Company:     江苏三六五网络股份有限公司
 *
 * @author: 江苏三六五网络股份有限公司
 * @version: 1.0
 * Create at:   2015-08-14 上午 09:30:51
 * <p/>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2015-08-14   江苏三六五网络股份有限公司   1.0         Initial
 */
package com.house365.web.controller;

import com.google.common.base.Strings;
import com.house365.beans.entity.CmCreditRecordEntity;
import com.house365.beans.entity.KlfCityEntity;
import com.house365.beans.system.Page;
import com.house365.beans.vo.CmCreditRecordVo;
import com.house365.rest.context.CmConstant;
import com.house365.web.cached.RedisUtilsInterface;
import com.house365.web.system.controller.BaseController;
import com.house365.web.util.*;
import com.house365.ws.beans.request.CmCreditRecordListRequest;
import com.house365.ws.beans.request.CmCreditRecordRequest;
import com.house365.ws.beans.response.CmCreditRecordListResponse;
import com.house365.ws.beans.response.CmCreditRecordResponse;
import com.house365.ws.interfaces.server.ICmCreditRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.Servlets;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * CmCreditRecord控制器<br>
 *
 * @author 江苏三六五网络股份有限公司
 * @version 1.0, 2015-08-14
 * @see
 * @since 1.0
 */
@Controller
@RequestMapping("/cmcreditrecord")
public class CmCreditRecordController extends BaseController {

    /**
     * 自动注入CmCreditRecordWS实现
     */
    @Autowired
    private ICmCreditRecord cmCreditRecord;

    /**
     * Excel表字段名称
     */
    private final static String[] excelTitles = {"编号", "用户昵称", "用户手机号", "事件名称", "积分数量", "城市", "时间"};

    /**
     * 去新增CmCreditRecord
     *
     * @return 结果视图
     */
    @RequestMapping(value = "", params = "action=create")
    public String createForm(Model model) {
        model.addAttribute("action", "create");
        return getAutoUrl("form");
    }

    /**
     * 新增CmCreditRecord
     *
     * @param result 表单验证数据
     * @return 结果视图
     */
    @RequestMapping(value = "", method = {RequestMethod.POST})
    public String createCmCreditRecord(
            @Valid CmCreditRecordVo vo, BindingResult result, RedirectAttributes redirectAttributes, Model model
    ) {
        CmCreditRecordEntity entity = vo.getEntity();
        model.addAttribute("entity", entity);
        // subValidation(result, entity);
        // 表单验证无误,进行提交
        if (result.hasErrors()) {
            model.addAttribute("action", "create");
            addErrorMessage(model, result.getFieldError().getDefaultMessage());
            return getAutoUrl("form");
        } else {
            try {
                CmCreditRecordRequest request = new CmCreditRecordRequest();
                request.setEntity(entity);
                CmCreditRecordResponse response = cmCreditRecord.addCmCreditRecord(request);
                Integer id = response.getEntity().getId();
                return "redirect:/cmcreditrecord/" + id;
            } catch (Exception ex) {
                addErrorMessage(model, ex.getMessage());
                model.addAttribute("action", "create");
                return getAutoUrl("form");
            }
        }
    }

    /**
     * 删除CmCreditRecord
     *
     * @param id CmCreditRecord页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.DELETE})
    @ResponseStatus(HttpStatus.OK)
    public void delete(@PathVariable String id) {
        if (!StringUtils.isEmpty(id)) {
            if (id.contains(",")) {
                String[] ids = id.split(",");
                for (int i = 0; i < ids.length; i++) {
                    cmCreditRecord.deleteCmCreditRecordById(Integer.valueOf(ids[i]));
                }
            } else {
                cmCreditRecord.deleteCmCreditRecordById(Integer.valueOf(id));
            }
        }
    }

    /**
     * 去查看CmCreditRecord
     *
     * @param id CmCreditRecord页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.GET})
    public String showForm(@PathVariable(value = "id") Integer id, Model model) {
        CmCreditRecordResponse response = cmCreditRecord.getCmCreditRecordById(id);
        model.addAttribute("entity", response.getEntity());
        return getAutoUrl("form");
    }

    /**
     * 去修改CmCreditRecord
     *
     * @param id CmCreditRecord页面表单对象唯一标识
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.GET}, params = "action=edit")
    public String updateForm(@PathVariable(value = "id") Integer id, Model model) {
        CmCreditRecordResponse response = cmCreditRecord.getCmCreditRecordById(id);
        model.addAttribute("entity", response.getEntity());
        model.addAttribute("action", "edit");
        return getAutoUrl("form");
    }

    /**
     * 修改CmCreditRecord
     *
     * @param result 表单验证数据
     * @return 结果视图
     */
    @RequestMapping(value = "/{id}", method = {RequestMethod.POST})
    public String updateCmCreditRecord(
            @Valid CmCreditRecordVo vo, BindingResult result, @PathVariable Integer id,
            RedirectAttributes redirectAttributes, Model model
    ) {
        CmCreditRecordEntity entity = vo.getEntity();
        model.addAttribute("entity", entity);
        // subValidation(result, entity);
        // 表单验证无误,进行提交
        if (result.hasErrors()) {
            model.addAttribute("action", "create");
            addErrorMessage(model, result.getFieldError().getDefaultMessage());
            return getAutoUrl("form");
        } else {
            try {
                CmCreditRecordRequest request = new CmCreditRecordRequest();
                request.setEntity(entity);
                cmCreditRecord.updateCmCreditRecord(request);
                redirectAttributes.addAttribute("message", "更新成功");
                return "redirect:/cmcreditrecord/" + entity.getId();
            } catch (Exception ex) {
                addErrorMessage(model, ex.getMessage());
                model.addAttribute("action", "edit");
                return getAutoUrl("form");
            }
        }
    }

    /**
     * 查询CmCreditRecord
     *
     * @param request 请求对象
     * @return 结果视图
     */
    @RequestMapping(value = "", method = RequestMethod.GET)
    public String list(Integer number, Model model, HttpServletRequest request) {
        // 获取查询条件
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
        if (searchParams.get("EQ_cityId") == null || org.apache.commons.lang3.StringUtils.isBlank(searchParams.get("EQ_cityId").toString())) {
            String cityKey = (String) request.getSession().getAttribute(CmConstant.CITY_KEY);
            searchParams.put("EQ_cityId", cityKey);
        }
        Page page = new Page(Page.TWENTY_PAGE_SIZE);
        if (null != number) {
            page.setCurrentPage(number);
        }

        //search_GTE_happenTime  search_LTE_andHappenTime
        if (!searchParams.containsKey("GTE_happenTime")) {
            Date d1 = DateTimeUtils.getDaysAgo(new Date(), 1);
            String d1s = DateTimeUtils.getDateString(d1, DateTimeUtils.DEFAULT_DATE_FORMAT_PATTERN_SHORT);

            searchParams.put("GTE_happenTime", d1s);
        }
        if (!searchParams.containsKey("LTE_andHappenTime")) {
            Date d1 = DateTimeUtils.getDaysAgo(new Date(), 1);
            String d1s = DateTimeUtils.getDateString(d1, DateTimeUtils.DEFAULT_DATE_FORMAT_PATTERN_SHORT);
            searchParams.put("LTE_andHappenTime", d1s);
        }

        CmCreditRecordListRequest listRequest = new CmCreditRecordListRequest();
        listRequest.setPaging(page);
        //内层SQL已排序，外层sql无须排序，否则全表扫描，优化查询效率
        listRequest.setOrderColumn(null);
        listRequest.setSearchParams(searchParams);

        StringBuilder cache = new StringBuilder("");
        for (Map.Entry entry : searchParams.entrySet()) {
            cache.append(entry.getKey()).append(":").append(entry.getValue()).append(",");
        }

        String creditsCountCacheKey = "creditsCount_" + cache + "_" + page.getCurrentPage() + "_" + page.getPageSize() + "_cache";
        String userCountCacheKey = "userCount_" + cache + "_" + page.getCurrentPage() + "_" + page.getPageSize() + "_cache";

        Integer creditsCount = 0;
        Integer userCount = 0;

        RedisUtilsInterface redisUtils = (RedisUtilsInterface) SpringContextUtil.getBean("redisUtils");
        if (!Strings.isNullOrEmpty(creditsCountCacheKey) && redisUtils.getValByKeyNew(
                creditsCountCacheKey) != null && !Strings.isNullOrEmpty(
                redisUtils.getValByKeyNew(creditsCountCacheKey)) && !"null".equalsIgnoreCase(
                redisUtils.getValByKeyNew(creditsCountCacheKey))) {
            creditsCount = Integer.valueOf(redisUtils.getValByKeyNew(creditsCountCacheKey).trim());
        } else {
            creditsCount = cmCreditRecord.getTotalCreditsByCondition(listRequest);

            redisUtils.setValueExpireNew(creditsCountCacheKey, "" + creditsCount, 10, TimeUnit.MINUTES);
        }

        if (!Strings.isNullOrEmpty(userCountCacheKey) && redisUtils.getValByKeyNew(
                userCountCacheKey) != null && !Strings.isNullOrEmpty(
                redisUtils.getValByKeyNew(userCountCacheKey)) && !"null".equalsIgnoreCase(
                redisUtils.getValByKeyNew(userCountCacheKey))) {
            userCount = Integer.valueOf(redisUtils.getValByKeyNew(userCountCacheKey).trim());
        } else {
            userCount = cmCreditRecord.getDistinctUserCount(listRequest);

            redisUtils.setValueExpireNew(userCountCacheKey, "" + userCount, 10, TimeUnit.MINUTES);
        }

        CmCreditRecordListResponse response = cmCreditRecord.getCmCreditRecordListWithCity(listRequest);
//        List<KlfCityEntity> cityList = CityUtil.getCityList();
        //调用新接口，查询用户城市信息
        String userName = String.valueOf(request.getSession().getAttribute(CmConstant.USER_NAME));
        List<KlfCityEntity> cityList = CityUtil.getCityListNew(userName);
        model.addAttribute("cityList", cityList);
        model.addAttribute("creditsCount", creditsCount);
        model.addAttribute("userCount", userCount);
        model.addAttribute("page", response.getPaging());
        model.addAttribute("cmCreditRecords", response.getObjectList());
        model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
        return getAutoUrl();
    }

    @RequestMapping(value = "exportExcel", method = RequestMethod.GET)
    public void exportExcel(Integer number, Model model, HttpServletRequest request, HttpServletResponse response) {
        // 获取查询条件
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
        Page page = new Page(Integer.MAX_VALUE);
        if (null != number) {
            page.setCurrentPage(number);
        }
        List<KlfCityEntity> cityList = CityUtil.getCityList();
        CmCreditRecordListRequest listRequest = new CmCreditRecordListRequest();
        listRequest.setPaging(page);
        //内层SQL已排序，外层sql无须排序，否则全表扫描，优化查询效率
        listRequest.setOrderColumn(null);
        listRequest.setSearchParams(searchParams);

        CmCreditRecordListResponse resultList = cmCreditRecord.getCmCreditRecordListWithCity(listRequest);

        List<List<Object>> recordList = new ArrayList<List<Object>>();
        List<Object> record = null;
        for (CmCreditRecordEntity entity : resultList.getObjectList()) {
            for (KlfCityEntity city : cityList) {
                if (entity.getCityName() != null && city.getCode() != null && city.getCode().equals(
                        entity.getCityName())) {
                    entity.setCityName(city.getName());
                }
            }
            record = new ArrayList<Object>();
            record.add(entity.getId());
            record.add(entity.getUserName());
            record.add(entity.getUserPhone());
            record.add(entity.getRuleName());
            record.add(entity.getAmount());
            record.add(entity.getCityName());
            record.add(entity.getHappenTime());
            recordList.add(record);
        }
        ExcelUtil.exportExcel("积分明细列表.xlsx", "积分明细列表", 10000, excelTitles, recordList, response);
    }

    @RequestMapping(value = "statistics", method = RequestMethod.GET)
    public String statistics(Integer number, Model model, HttpServletRequest request) {
        // 获取查询条件
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
        Page page = new Page(Page.TWENTY_PAGE_SIZE);
        if (null != number) {
            page.setCurrentPage(number);
        }

        CmCreditRecordListRequest listRequest = new CmCreditRecordListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        listRequest.setOrderColumn(null);
        listRequest.setOrderMode(null);
        Integer creditsCount = cmCreditRecord.statisticsByPageCount(listRequest);
        CmCreditRecordListResponse response = cmCreditRecord.statisticsByPage(listRequest);
        response.getPaging().setRecords(creditsCount);

        model.addAttribute("creditsCount", creditsCount);
        model.addAttribute("page", response.getPaging());
        model.addAttribute("cmCreditRecords", response.getObjectList());
        model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
        return getAutoUrl("statistics");
    }

}
