package org.springblade.modules.api.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springblade.common.base.BaseEntity;
import org.springblade.common.constant.CommonConstant;
import org.springblade.common.enums.AfterSalesTypeEnum;
import org.springblade.common.enums.GrouponSourceEnum;
import org.springblade.common.enums.OrderStateEnum;
import org.springblade.common.enums.OrderTypeEnum;
import org.springblade.common.utils.SpringUtils;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.log.annotation.ApiLog;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.secure.utils.AuthUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.StringUtil;
import org.springblade.modules.api.request.GroupOrderRequest;
import org.springblade.modules.api.request.SubmitOrderRequest;
import org.springblade.modules.api.response.GrouponOrderResponse;
import org.springblade.modules.api.response.SubmitOrderResponse;
import org.springblade.modules.api.response.UserOrderDetailResponse;
import org.springblade.modules.api.response.UserOrderResponse;
import org.springblade.modules.api.service.SubmitOrderService;
import org.springblade.modules.api.service.impl.GrouponOrderServiceImpl;
import org.springblade.modules.finance.entity.AfterSalesReason;
import org.springblade.modules.finance.entity.ConfirmOrder;
import org.springblade.modules.finance.entity.Order;
import org.springblade.modules.finance.service.*;
import org.springblade.modules.finance.entity.OrderGrouponGoods;
import org.springblade.modules.groupon.vo.GrouponVO;
import org.springblade.modules.system.entity.UserApp;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

/**
 * Author pangqijun
 * Date 2023/6/6
 * Description
 */
@RestController
@RequestMapping(CommonConstant.API_URL + "/order")
@Api(value = "订单接口", tags = "05.订单接口")
public class ApiOrderController extends BladeController {

    @Resource
    private GrouponOrderServiceImpl grouponOrderService;
    @Resource
    private IOrderService orderService;
    @Resource
    private IConfirmOrderService confirmOrderService;
    @Resource
    private IOrderGrouponService orderGrouponService;
    @Resource
    private IAfterSalesService afterSalesService;


    @ApiLog("通用下单")
    @PostMapping("/submit")
    @ApiOperationSupport(order = 1)
    @ApiOperation(value = "通用下单")
    public R<SubmitOrderResponse> submitOrder(@Valid @RequestBody SubmitOrderRequest request) {
        if (StringUtil.isEmpty(request.getDistributeMode())) {
            request.setDistributeMode(1);
        }
        request.setUserId(AuthUtil.getUserId());
        SubmitOrderService submitOrderService = SpringUtils.getBean(OrderTypeEnum.getInstanceByValue(request.getOrderType()));
        Assert.notNull(submitOrderService, "获取实现类失败");
        String orderNo = submitOrderService.submitOrder(request);
        return data(new SubmitOrderResponse(orderNo));
    }

    @PostMapping("/groupon")
    @ApiOperationSupport(order = 2)
    @ApiOperation(value = "获取拼团下单数据", notes = "传入groupon")
    public R<GrouponOrderResponse> getGroupOrderData(@Valid @RequestBody GroupOrderRequest request) {
        return R.data(grouponOrderService.getGroupOrderData(request));
    }


    @GetMapping("/user")
    @ApiOperationSupport(order = 3)
    @ApiOperation(value = "获取用户订单")
    public R<IPage<UserOrderResponse>> getUserOrder(Query query, Integer orderState) {
        return R.data(orderService.getUserOrder(Condition.getPage(query), AuthUtil.getUserId(), orderState));
    }

    @GetMapping("/user/detail")
    @ApiOperationSupport(order = 4)
    @ApiOperation(value = "获取用户订单详情")
    public R<UserOrderDetailResponse> getUserOrderDetail(Long orderId, @RequestParam(required = false) Long afterSalesId,
                                                         @ApiParam("经度") Double longitude, @ApiParam("纬度") Double latitude) {
        return R.data(orderService.getUserOrderDetail(orderId, afterSalesId, longitude, latitude));
    }

    @PostMapping("cancel")
    @ApiOperationSupport(order = 5)
    @ApiOperation(value = "取消订单", notes = "传入订单号")
    public R orderCancel(Long orderId) {
        orderService.orderCancel(orderId);
        return R.success("订单已取消");
    }

    @PostMapping("confirmOrder")
    @ApiOperation(value = "取货核销", notes = "通过取货码进行核销")
    public R confirmOrder(@ApiParam("取货码") String pickupCode){
        grouponOrderService.confirmOrder(pickupCode, AuthUtil.getUserId());
        return R.success("取货核销成功");
    }

    @PostMapping("getConfirmOrderList")
    @ApiOperation(value = "获取核销记录")
    public R<List<ConfirmOrder>> getConfirmOrderList(@RequestBody  Query query){
        IPage<ConfirmOrder> page = confirmOrderService.page(Condition.getPage(query), Wrappers.lambdaQuery(ConfirmOrder.class)
                .eq(BaseEntity::getCreateUserId, AuthUtil.getUserId())
                .orderByDesc(BaseEntity::getCreateTime));
        return R.data(page.getRecords());
    }

    @PostMapping("getOrderGoodsList")
    @ApiOperation(value = "获取核销订单商品")
    public R<List<OrderGrouponGoods>> getOrderGoodsList(Long orderId){
        return R.data(grouponOrderService.getGroupGoodsList(orderId));
    }

    @PostMapping("/refund")
    @ApiOperationSupport(order = 8)
    @ApiOperation(value = "申请退款", notes = "传入订单号")
    public R orderRefund(Long orderId) {
        orderService.orderRefund(orderId);
        return success("操作成功");
    }

    @GetMapping("/commander")
    @ApiOperationSupport(order = 9)
    @ApiOperation(value = "获取团长团购订单")
    public R<IPage<GrouponVO>> getCommanderOrder(Query query, Integer grouponState) {
        return R.data(orderGrouponService.getCommanderOrder(Condition.getPage(query), AuthUtil.getUserId(), grouponState));
    }

    @GetMapping("/commander/detail")
    @ApiOperationSupport(order = 10)
    @ApiOperation(value = "获取团长团购订单详情")
    public R<GrouponVO> getCommanderOrderDetail(@ApiParam("团购ID") Long grouponId, @ApiParam("查询类型 1-网点订单  2-全部订单") Integer queryType,
                                                @ApiParam("团购ID") Integer state) {
        return R.data(orderGrouponService.getCommanderOrderDetail(grouponId, queryType, AuthUtil.getUserId(), state));
    }

    @PostMapping("/modifySelfTake")
    @ApiOperationSupport(order = 11)
    @ApiOperation(value = "更换自提点", notes = "传入订单号")
    public R modifySelfTake(@RequestParam("orderId") Long orderId, @RequestParam("selfTakeId") Long selfTakeId) {
        orderService.modifySelfTake(orderId, selfTakeId);
        return success("操作成功");
    }

    @Transactional(rollbackFor = Exception.class)
    @PostMapping("/return-goods")
    @ApiOperationSupport(order = 12)
    @ApiOperation(value = "申请退货", notes = "传入订单号")
    public R afterSales(@RequestParam("orderId")Long orderId,
                        @RequestParam("reason") String reason) {
        Order order = orderService.getById(orderId);
        Assert.notNull(order, "订单数据不存在");
        afterSalesService.add(orderId, reason, AfterSalesTypeEnum.RETURN_GOODS);

        order.setOrderState(OrderStateEnum.AFTER_SALES.getValue());
        orderService.updateById(order);
        return success("操作成功");
    }
}
