package com.bofeng.wx.controller;

import com.bofeng.entity.Order;
import com.bofeng.entity.ParseCurrentOpenId;
import com.bofeng.entity.StatisticsOrder;
import com.bofeng.entity.User;
import com.bofeng.service.OrderService;
import com.bofeng.service.UserService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.google.common.collect.Maps;
import com.yvan.Model;
import com.yvan.PageDb;
import com.yvan.platform.JsonWapper;
import com.yvan.platform.YvanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;
import java.util.Map;

@RestController
public class CustHistoryController {

    @Autowired
    private UserService userService;

    @Autowired
    private OrderService orderService;

    @GetMapping("/cust/history.html")
    public ModelAndView history(ModelMap model) throws JsonProcessingException {
        //获取当前微信用户
        ParseCurrentOpenId wxToken = userService.currentWxUser();
        if (wxToken.isError()) return wxToken.getErrorResult();

        User currentUser = wxToken.getUser();

        model.put("user", new JsonWapper(currentUser));

        Map<String, Object> queryParam = Maps.newLinkedHashMap();
        queryParam.put("userId", currentUser.getUserId());
        queryParam.put("statistics", "M");
        List<StatisticsOrder> statisticsOrderList = orderService.groupByStatistics(queryParam);

        model.put("orderList", statisticsOrderList);
        model.put("orderList_json", YvanUtil.toJsonPretty(statisticsOrderList));
        model.put("user", new JsonWapper(currentUser));

        return new ModelAndView("/cust/history.ftl", model);
    }

    @GetMapping("/cust/history.json")
    public Model<List<Order>> getHistory(PageDb pageDb,
                                         @RequestParam(name = "userId", required = false, defaultValue = "") String userId,
                                         @RequestParam(name = "userType", required = false, defaultValue = "") String userType,
                                         @RequestParam(name = "timeMonth", required = false, defaultValue = "") String timeMonth) {
        Map<String, Object> param = Maps.newLinkedHashMap();
        param.put("userId", userId);
        param.put("userType", userType);
        param.put("timeMonth", timeMonth);
        List<Order> orderList = orderService.selectByTime(pageDb, param);
        return Model.newSuccess(pageDb, orderList);

    }

}
