package com.bofeng.wx.controller;

import com.bofeng.entity.Order;
import com.bofeng.entity.ParseCurrentOpenId;
import com.bofeng.service.OrderService;
import com.bofeng.service.UserOpenService;
import com.bofeng.service.UserService;
import com.fasterxml.jackson.core.JsonProcessingException;
import lombok.val;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
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.RestController;
import org.springframework.web.servlet.ModelAndView;

import java.math.BigDecimal;
import java.util.Collections;
import java.util.List;

@RestController
public class CustCommissionController {
    @Autowired
    private WxMpService mpService;

    @Autowired
    private UserOpenService userOpenService;

    @Autowired
    private UserService userService;

    @Autowired
    private OrderService orderService;

    @GetMapping("/cust/commission.html")
    public ModelAndView commission(ModelMap model) throws WxErrorException, JsonProcessingException {

        ParseCurrentOpenId wxToken = userService.currentWxUser();
        if (wxToken.isError()) return wxToken.getErrorResult();

        val currentUser = wxToken.getUser();

        List<Order> orderList = orderService.getCmsByUser(currentUser.getUserId());
        Collections.sort(orderList, (a, b) -> {
            return a.getPayAt().compareTo(b.getPayAt());
        });
        model.put("cmsList", orderList);
        BigDecimal amount = new BigDecimal(0);
        for (val order : orderList) {
            amount = amount.add(order.getCmsAmount());
        }
        model.put("amount", amount);
        /*
        model.put("cmsList_json", YvanUtil.toJson(orderList));
        model.put("user", new JsonWapper(currentUser));
        */

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