package com.seer.teach.pay.app.pay.controller;


import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.dev33.satoken.stp.StpUtil;
import com.seer.teach.common.ResultBean;
import com.seer.teach.common.annotation.DecryptionAnnotation;
import com.seer.teach.common.annotation.EncryptionAnnotation;
import com.seer.teach.common.annotation.RepeatSubmit;
import com.seer.teach.pay.app.pay.controller.req.OrderPayReq;
import com.seer.teach.pay.app.client.dto.PayOrderRespDTO;
import com.seer.teach.pay.app.pay.controller.resp.AppPayOrderResp;
import com.seer.teach.pay.app.pay.service.IAppPayOrderService;
import com.seer.teach.pay.app.pay.controller.resp.AppPayOrderStatusResp;
import com.seer.teach.pay.app.pay.convert.AppPayOrderConvert;
import com.seer.teach.pay.entity.PayOrderEntity;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@Tag(name = "用户 APP - 支付订单")
@Validated
@RequiredArgsConstructor
@RequestMapping("/app/order")
@SaCheckLogin(type = StpUtil.TYPE)
@EncryptionAnnotation
@DecryptionAnnotation
public class AppPayOrderController {

    private final IAppPayOrderService appPayOrderService;

    @RepeatSubmit(
            interval = 3000,
            keyType = RepeatSubmit.KeyType.TOKEN,
            message = "订单支付中，请稍后"
    )
    @Operation(summary = "支付订单")
    @PostMapping("/pay")
    @SaCheckPermission("app:order:pay")
    public ResultBean<AppPayOrderResp> payOrder(@RequestBody @Validated OrderPayReq orderPayReq) {
        return ResultBean.success(appPayOrderService.payOrder(orderPayReq));
    }
    
    @Operation(summary = "查询支付状态")
    @GetMapping("/status/{orderSn}")
    @SaCheckPermission("app:order:status")
    public ResultBean<AppPayOrderStatusResp> queryPayStatus(
            @Parameter(description = "订单号") @PathVariable("orderSn") String orderSn) {
        PayOrderEntity payOrder = appPayOrderService.queryPayStatus(orderSn);
        AppPayOrderStatusResp result = AppPayOrderConvert.INSTANCE.convertOne(payOrder);
        return ResultBean.success(result);
    }


    @Operation(summary = "关闭支付订单")
    @PostMapping("/close/{orderSn}")
    @SaCheckPermission("app:order:close")
    public ResultBean<Boolean> closePayOrder(
            @Parameter(description = "订单号", required = true) @PathVariable("orderSn") String orderSn) {
        Boolean result = appPayOrderService.closePayOrder(orderSn);
        return ResultBean.success(result);
    }
}