/*
 * Copyright (c) 2018-2999 广州亚米信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.platform.controller;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yami.shop.bean.enums.DvyType;
import com.yami.shop.bean.enums.OrderStatus;
import com.yami.shop.bean.model.Order;
import com.yami.shop.bean.model.OrderItem;
import com.yami.shop.bean.model.User;
import com.yami.shop.bean.model.UserAddrOrder;
import com.yami.shop.bean.param.BackendOrderParam;
import com.yami.shop.bean.param.DeliveryOrderParam;
import com.yami.shop.bean.param.OrderParam;
import com.yami.shop.bean.param.OrderPayParam;
import com.yami.shop.common.exception.GlobalException;
import com.yami.shop.common.util.PageParam;
import com.yami.shop.common.util.R;
import com.yami.shop.service.*;
import com.yami.shop.utils.CullenUtils;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 订单信息管理实现
 *
 * @author lgh
 * @version 1.0.0
 * @since 2018-09-15
 */
@RestController
@RequestMapping("/platform/order")
@AllArgsConstructor
public class OrderController {

    private final OrderService orderService;
    private final OrderItemService orderItemService;
    private final UserAddrOrderService userAddrOrderService;
    private final ProductService productService;
    private final SkuService skuService;
    private final UserService userService;


    /**
     * 分页获取
     */
    @GetMapping("/page")
//    @PreAuthorize("@pms.hasPermission('platform:order:page')")
    public R<IPage<Order>> page(OrderParam orderParam, PageParam<Order> page) {
        IPage<Order> orderIPage = orderService.pageOrdersDetialByOrderParam(page, orderParam);
        return R.SUCCESS(orderIPage);
    }

    @GetMapping("/deliverList")
    @ApiOperation("后管端-快递订单列表")
    public R<IPage<Order>> deliverList(BackendOrderParam orderParam, PageParam<Order> page) {
        IPage<Order> orderIPage = orderService.deliverList(page, orderParam);
        return R.SUCCESS(orderIPage);
    }

    @GetMapping("/deliverListStatusNum")
    @ApiOperation("后管端-快递订单列表-订单状态数量")
    public R<Map<String,Integer>> deliverListStatusNum() {
        return R.SUCCESS(orderService.deliverListStatusNum());
    }

    /**
     * 根据商家获取支付信息
     */
    @GetMapping("/orderPayByShopId")
    @ApiOperation(value = "根据商家id获取支付信息")
    public R<OrderPayParam> orderPayByShopId(@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")@RequestParam("startTime") Date startTime,
                                             @DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")@RequestParam("endTime") Date endTime) {
        OrderPayParam actualTotal = orderService.getPayUserCountByshopId(null,startTime,endTime);
        return R.SUCCESS(actualTotal);
    }

    /**
     * 获取信息
     */
    @GetMapping("/orderInfo/{orderNumber}")
//    @PreAuthorize("@pms.hasPermission('platform:order:info')")
    public R<Order> info(@PathVariable("orderNumber") String orderNumber) {
        Order order = orderService.getOne(new LambdaUpdateWrapper<Order>().eq(Order::getOrderNumber, orderNumber));
        if (order == null) {
            throw new GlobalException("未找到所在的订单");
        }
        UserAddrOrder userAddrOrder = userAddrOrderService.getById(order.getAddrOrderId());
        order.setUserAddrOrder(userAddrOrder);
        List<OrderItem> orderItems = orderItemService.getOrderItemsByOrderNumber(orderNumber);
        if (!orderItems.isEmpty()){
            orderItems.forEach(c->{
                c.setRefundIngCount(orderItemService.refundIngCount(c.getOrderItemId()));
                c.setRefundSuccessCount(orderItemService.refundSuccessCount(c.getOrderItemId()));
            });
        }
        order.setOrderItems(orderItems);
        User user = userService.getById(order.getUserId());
        if (user!=null) {
            order.setNickName(user.getNickName());
            order.setUserMobile(user.getUserMobile());
        }
        return R.SUCCESS(order);
    }


    /**
     * 已销售订单
     *
     * @param orderParam
     */
    @GetMapping("/soldExcel")
    @PreAuthorize("@pms.hasPermission('platform:order:exportExcel')")
    public void soldExcel(OrderParam orderParam, HttpServletResponse response) {
//        orderParam.setIsPayed(1);
        orderService.soldExcel(orderParam,response);
//
    }

    @ApiOperation("发货")
    @PutMapping("/delivery")
    @Transactional(rollbackFor = Exception.class)
    public ResponseEntity<Void> delivery(@RequestBody DeliveryOrderParam deliveryOrderParam) {
        Order order = orderService.getOne(new LambdaUpdateWrapper<Order>().eq(Order::getOrderNumber, deliveryOrderParam.getOrderNumber()));
        if (!Objects.equals(order.getHbOrderStatus(), OrderStatus.PADYED.value()) && Objects.equals(order.getDvyType(), DvyType.FETCH.value())){
            throw new GlobalException("订单不处于待入库状态，无法进行入库");
        }else if (!Objects.equals(order.getHbOrderStatus(), OrderStatus.PADYED.value())){
            throw new GlobalException("订单不处于待发货状态，无法进行发货");
        }

        List<OrderItem> orderItems = orderItemService.getOrderItemsByOrderNumber(deliveryOrderParam.getOrderNumber());
        if (!orderItems.isEmpty()) {
            orderItems.forEach(orderItem->
                    CullenUtils.validateDataThrowException(orderItemService.refundIngCount(orderItem.getOrderItemId())!=0,"该订单存在售后中商品，请处理后发货..."));
        }

        Order orderParam = new Order();
        orderParam.setOrderId(order.getOrderId());
        if (!Objects.equals(order.getDvyType(), DvyType.FETCH.value()) || !Objects.equals(order.getDvyType(), DvyType.NOT_DELIVERY.value())){
            orderParam.setDvyId(deliveryOrderParam.getDvyId());
            orderParam.setDvyFlowId(deliveryOrderParam.getDvyFlowId());
        }
        orderParam.setDvyTime(new Date());
        orderParam.setUpdateTime(new Date());
        orderParam.setHbOrderStatus(OrderStatus.CONSIGNMENT.value());
        orderParam.setUserId(order.getUserId());

        orderService.delivery(orderParam);

        for (OrderItem orderItem : orderItems) {
            productService.removeProductCacheByProdId(orderItem.getProdId());
            skuService.removeSkuCacheBySkuId(orderItem.getSkuId(),orderItem.getProdId());
        }
        return ResponseEntity.ok().build();
    }

}
