/**
 * Description: CmProductStat控制器
 * Copyright:   Copyright (c)2016
 * Company:     江苏三六五网络股份有限公司
 *
 * @author: 江苏三六五网络股份有限公司
 * @version: 1.0
 * Create at:   2016-03-16 下午 17:11:49
 * <p/>
 * Modification History:
 * Date         Author      Version     Description
 * ------------------------------------------------------------------
 * 2016-03-16   江苏三六五网络股份有限公司   1.0         Initial
 */
package com.house365.web.controller;

import com.alibaba.dubbo.common.json.JSON;
import com.house365.beans.entity.CmProductStatEntity;
import com.house365.beans.entity.KlfCityEntity;
import com.house365.beans.system.Page;
import com.house365.web.system.controller.BaseController;
import com.house365.web.util.CityUtil;
import com.house365.web.util.ExcelUtil;
import com.house365.ws.beans.request.CmProductStatListRequest;
import com.house365.ws.beans.response.CmProductStatListResponse;
import com.house365.ws.beans.response.CmProductStatResponse;
import com.house365.ws.interfaces.server.ICmProductStat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
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.ResponseBody;
import org.springside.modules.web.Servlets;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;

/**
 * CmProductStat控制器<br>
 *
 * @author 江苏三六五网络股份有限公司
 * @version 1.0, 2016-03-16
 * @see
 * @since 1.0
 */
@Controller
@RequestMapping("/cmproductstat")
public class CmProductStatController extends BaseController {

    /**
     * 自动注入CmProductStatWS实现
     */
    @Autowired
    private ICmProductStat cmProductStat;

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

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

    /**
     * 查询CmProductStat
     *
     * @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_");
        Page page = new Page();
        if (null != number) {
            page.setCurrentPage(number);
        }

        List<KlfCityEntity> cityList = CityUtil.getCityList();
        CmProductStatListRequest listRequest = new CmProductStatListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        CmProductStatListResponse response = cmProductStat.getCmProductStatList(listRequest);
        model.addAttribute("page", response.getPaging());
        model.addAttribute("cityList", cityList);
        model.addAttribute("cmProductStats", response.getObjectList());
        model.addAttribute("searchParams", Servlets.encodeParameterStringWithPrefix(searchParams, "search_"));
        return getAutoUrl();
    }

    @RequestMapping(value = "chart", method = RequestMethod.GET)
    public String chart(Model model, HttpServletRequest request) {

        List<CmProductStatEntity> productStatEntities = cmProductStat.statByCity();
        Set<String> cityName = new HashSet<>();
        List<Map<String, String>> list = new ArrayList<>();

        for (CmProductStatEntity product : productStatEntities) {
            Map<String, String> map = new HashMap<>();
            map.put("name", product.getCityName());
            map.put("value", String.valueOf(product.getId()));
            list.add(map);
            cityName.add(product.getCityName());
        }

        String json = "";
        String cityJson = "";

        try {
            json = JSON.json(list);
            cityJson = JSON.json(cityName);
        } catch (IOException e) {
            e.printStackTrace();
        }

        model.addAttribute("cityStat", json);
        model.addAttribute("cityJson", cityJson);

        return getAutoUrl();
    }

    @RequestMapping(value = "/getCityStatByMonth", method = {RequestMethod.POST})
    @ResponseBody
    public String getCityStatByMonth(Model model, HttpServletRequest request) {
        String cityName = String.valueOf(request.getParameter("cityName"));
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MONTH, -1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        //        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        //        String date = sdf.format(calendar.getTime());

        List<CmProductStatEntity> list = cmProductStat.statByDate(cityName);

        List<String> dateList = new ArrayList<>();
        List<String> productCountList = new ArrayList<>();
        for (CmProductStatEntity stat : list) {
            dateList.add(stat.getStatDate());
            productCountList.add(String.valueOf(stat.getEndStock()));
        }

        Map<String, String> map = new LinkedHashMap<>();
        String result = "";
        try {
            map.put("date", JSON.json(dateList));
            map.put("productCount", JSON.json(productCountList));
            result = JSON.json(map);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return result;
    }

    @RequestMapping(value = "exportExcel", method = RequestMethod.GET)
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) {
        // 获取查询条件
        Map<String, Object> searchParams = Servlets.getParametersStartingWith(request, "search_");
        Page page = new Page();
        page.setCurrentPage(1);
        page.setPageSize(Integer.MAX_VALUE);
        final String[] excelTitles = {"编号", "商品ID", "商品名", "期初库存", "期末库存", "日期", "商品类型", "城市", "是否秒杀"};
        CmProductStatListRequest listRequest = new CmProductStatListRequest();
        listRequest.setPaging(page);
        listRequest.setSearchParams(searchParams);
        CmProductStatListResponse listResponse = cmProductStat.getCmProductStatList(listRequest);
        List<List<Object>> recordList = new ArrayList<>();
        for (CmProductStatEntity entity : listResponse.getObjectList()) {
            List<Object> record = new ArrayList<>();
            record.add(entity.getId());
            record.add(entity.getProductId());
            record.add(entity.getProductName());
            record.add(entity.getBeginStock());
            record.add(entity.getEndStock());
            record.add(entity.getStatDate());
            record.add(entity.getProductType() == 1 ? "虚拟" : "实物");
            record.add(entity.getCityName());
            record.add(entity.getIsSeckill() == 1 ? "秒杀商品" : "普通商品");
            recordList.add(record);
        }
        ExcelUtil.exportExcel("上架商品统计.xlsx", "上架商品统计", excelTitles, recordList, response);
    }

}
