package org.springblade.modules.api.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.http.ContentType;
import cn.hutool.json.JSONUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springblade.common.aspect.VendingFlag;
import org.springblade.common.constant.CommonConstant;
import org.springblade.modules.api.request.VendingOrderReq;
import org.springblade.modules.api.response.VendingOrderRes;
import org.springblade.modules.api.service.VendingOrderService;
import org.springblade.modules.finance.vo.OrderGoodsVO;
import org.springblade.modules.finance.vo.OrderVO;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 售货机硬件对接接口
 */
@RestController
@AllArgsConstructor
@RequestMapping(CommonConstant.API_URL + "/vending")
@Api(value = "售货机硬件对接接口", tags = "售货机硬件对接接口")
public class ApiVendingController {

    private final VendingOrderService vendingOrderService;


    @VendingFlag
    @ApiOperation(value = "查询订单信息", notes = "传入售货机编号")
    @PostMapping("/getOrder")
    public void getOrder(@Valid @RequestBody VendingOrderReq vendingOrderReq, HttpServletResponse response) throws IOException {
        List<OrderGoodsVO> vendingOrderVOs = vendingOrderService.getVendingOrder(vendingOrderReq);

        //封装返回
        VendingOrderRes vendingOrderRes = new VendingOrderRes();
        vendingOrderRes.setMachine_id(vendingOrderReq.getMachine_id());
        if (CollectionUtil.isEmpty(vendingOrderVOs)) {
            vendingOrderRes.setSaleSn("");
            vendingOrderRes.setChannelNum("0");
            vendingOrderRes.setSaledata(new HashMap<>());
            this.notifyReturn(response, vendingOrderRes);
        } else {
            //一次只返回一个订单
            //按订单分组
            Map<Long, List<OrderGoodsVO>> vendingOrderGoodMap = vendingOrderVOs.stream().collect(Collectors.groupingBy(OrderGoodsVO::getOrderId));
            OrderVO backOrder = vendingOrderService.getBackOrder(vendingOrderReq);
            List<OrderGoodsVO> orderGoodsVOS = vendingOrderGoodMap.get(backOrder.getId());
            vendingOrderRes.setSaleSn(backOrder.getId() + "");
            vendingOrderRes.setChannelNum(orderGoodsVOS.size() + "");

            Map<String, String> saledataMap = new HashMap<>();

            //按货道分组
            Map<String, List<OrderGoodsVO>> orderGoodsMap = orderGoodsVOS.stream().collect(Collectors.groupingBy(OrderGoodsVO::getCargoWayNo));
            for (Map.Entry<String, List<OrderGoodsVO>> rderGoodsEntry : orderGoodsMap.entrySet()) {
                saledataMap.put(rderGoodsEntry.getKey(), rderGoodsEntry.getValue().size() + "");
            }

            vendingOrderRes.setSaledata(saledataMap);
            this.notifyReturn(response, vendingOrderRes);
        }

    }

    @ApiOperation(value = "出货成功回调", notes = "出货成功回调")
    @PostMapping("callback")
    public void callback() {

    }

    /**
     * 硬件接口通用响应
     *
     * @param response        HttpServletResponse
     * @param vendingOrderRes 返值
     */
    private void notifyReturn(HttpServletResponse response, VendingOrderRes vendingOrderRes) throws IOException {
        Map<String, Object> map = BeanUtil.beanToMap(vendingOrderRes);
        response.setHeader("Content-type", ContentType.JSON.toString());
        response.getOutputStream().write(JSONUtil.toJsonStr(map).getBytes(StandardCharsets.UTF_8));
        response.flushBuffer();
    }

}
