package com.ruoyi.web.modules.order.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.web.modules.account.support.MemberContext;
import com.ruoyi.web.modules.order.dto.OrderAppListQueryDTO;
import com.ruoyi.web.modules.order.service.IOrderAppService;

/**
 * C 端订单（须会员 Token）
 */
@RestController
@RequestMapping("/api/order")
public class OrderAppController extends BaseController
{
    @Autowired
    private IOrderAppService orderAppService;

    @GetMapping("/badges")
    public AjaxResult badges()
    {
        return success(orderAppService.getBadges(requireMemberId()));
    }

    @GetMapping("/list")
    public TableDataInfo list(OrderAppListQueryDTO query)
    {
        startPage();
        return getDataTable(orderAppService.list(requireMemberId(), query));
    }

    @GetMapping("/{orderId}")
    public AjaxResult detail(@PathVariable("orderId") Long orderId)
    {
        return success(orderAppService.getDetail(requireMemberId(), orderId));
    }

    @PostMapping("/{orderId}/pay")
    public AjaxResult pay(@PathVariable("orderId") Long orderId)
    {
        return success(orderAppService.createPay(requireMemberId(), orderId));
    }

    @PostMapping("/{orderId}/pay/cancel")
    public AjaxResult cancelPay(@PathVariable("orderId") Long orderId)
    {
        orderAppService.cancelPay(requireMemberId(), orderId);
        return success();
    }

    @PostMapping("/{orderId}/confirm-receive")
    public AjaxResult confirmReceive(@PathVariable("orderId") Long orderId)
    {
        orderAppService.confirmReceive(requireMemberId(), orderId);
        return success();
    }

    private Long requireMemberId()
    {
        Long memberId = MemberContext.getMemberId();
        if (memberId == null)
        {
            throw new ServiceException("请先登录", 401);
        }
        return memberId;
    }
}
