package com.ruoyi.app.flashdelivery.controller;

import com.ruoyi.app.flashdelivery.dto.FlashDeliveryProofRequest;
import com.ruoyi.app.flashdelivery.dto.FlashDeliveryDeliverRequest;
import com.ruoyi.app.flashdelivery.service.FlashDeliveryApplicationService;
import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.system.utils.Auth;
import com.ruoyi.system.utils.JwtUtil;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;

/** 骑手端闪送接口；仅 userType=2 的 token 可执行接单和履约操作。 */
@RestController
@RequestMapping("/system/flashDelivery/rider")
@Anonymous
public class FlashDeliveryRiderController extends BaseController {
    private final FlashDeliveryApplicationService service;
    public FlashDeliveryRiderController(FlashDeliveryApplicationService service) { this.service = service; }

    /** 按外卖订单同名页签查询可抢任务或当前骑手自己的任务。 */
    @GetMapping("/orders")
    @Auth
    public AjaxResult orders(@RequestHeader String token,
                             @RequestParam(defaultValue = "1") int page,
                             @RequestParam(defaultValue = "10") int size,
                             @RequestParam(defaultValue = "newTask") String tab,
                             @RequestParam(required = false) BigDecimal longitude,
                             @RequestParam(required = false) BigDecimal latitude) {
        return success(service.riderOrders(userId(token), page, size, tab, longitude, latitude));
    }

    /** 接单前隐藏敏感字段；接单后仅中单骑手可见完整履约信息。 */
    @GetMapping("/orders/{id}")
    @Auth
    public AjaxResult detail(@RequestHeader String token, @PathVariable Long id) {
        return success(service.riderDetail(userId(token), id));
    }

    /** 原子抢单；同一订单只能由一个骑手成功接取。 */
    @PostMapping("/orders/{id}/accept")
    @Auth
    public AjaxResult accept(@RequestHeader String token, @PathVariable Long id) {
        return success(service.accept(userId(token), id));
    }

    /** 上传取件凭证并将已接单订单推进为已取件。 */
    @PostMapping("/orders/{id}/pickup")
    @Auth
    public AjaxResult pickup(@RequestHeader String token, @PathVariable Long id,
                             @RequestBody FlashDeliveryProofRequest request) {
        service.pickup(userId(token), id, request);
        return success();
    }

    /** 上传送达凭证并将已取件订单推进为已送达。 */
    @PostMapping("/orders/{id}/deliver")
    @Auth
    public AjaxResult deliver(@RequestHeader String token, @PathVariable Long id,
                              @RequestBody FlashDeliveryDeliverRequest request) {
        service.deliver(userId(token), id, request);
        return success();
    }

    private Long userId(String token) { return Long.valueOf(new JwtUtil().getusid(token)); }
}
