package com.bofeng.controller;

import com.bofeng.Consts;
import com.bofeng.JwtHelper;
import com.bofeng.entity.Settle;
import com.bofeng.entity.User;
import com.bofeng.service.CashierService;
import com.bofeng.service.OrderService;
import com.bofeng.service.UserService;
import com.google.common.collect.Maps;
import com.yvan.Model;
import com.yvan.ModelOps;
import com.yvan.PageDb;
import com.yvan.mvc.Pd;
import com.yvan.platform.Conv;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

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

@RestController
@RequiresPermissions(Consts.USER_TYPE_CASHIER)
public class CashierAccountsController {
    @Autowired
    private CashierService cashierService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private UserService userService;

    @GetMapping("/cashier/settle.html")
    public ModelAndView settle() {
        return new ModelAndView("/cashier/settle.ftl");
    }

    @GetMapping("/cashier/settle.json")
    public Model<List<Settle>> getSettleOrder(PageDb pageDb,
                                              @Pd(name = "saleName", required = false, defaultValue = "") String saleName,
                                              @Pd(name = "orderStartAt", required = false, defaultValue = "") String orderStartAt,
                                              @Pd(name = "orderEndAt", required = false, defaultValue = "") String orderEndAt) {
        Map<String, Object> queryParam = Maps.newLinkedHashMap();
        queryParam.put("saleName", saleName);
        queryParam.put("orderStartAt", orderStartAt);
        queryParam.put("orderEndAt", orderEndAt);
        User currentUser = userService.getUserById(Conv.NL(JwtHelper.getUserId()));
        queryParam.put("placeId", currentUser.getPlaceId());

        return Model.newSuccess(pageDb, cashierService.getSettleOrder(pageDb, queryParam));
    }

    @PostMapping("/cashier/order_settle.json")
    public ModelOps ordersSettle(@Pd(name = "orderStartAt", required = false, defaultValue = "") String orderStartAt,
                                 @Pd(name = "orderEndAt", required = false, defaultValue = "") String orderEndAt,
                                 @RequestBody List<Long> saleIdList) {


        User currentUser = userService.getUserById(Conv.NL(JwtHelper.getUserId()));
        Long placeId = currentUser.getPlaceId();
        for (int i = 0; i < saleIdList.size(); i++) {
            orderService.ordersSettle(orderStartAt, orderEndAt, saleIdList.get(i), placeId);
        }
        return ModelOps.newSuccess(saleIdList.size());
    }

}
