package cn.ysk.cashier.controller.shop;

import cn.hutool.core.map.MapProxy;
import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import cn.ysk.cashier.exception.BadRequestException;
import cn.ysk.cashier.system.enums.ParamsEnum;
import cn.ysk.cashier.system.service.ParamsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.Charset;
import java.util.Map;

/**
 * 店铺支付相关接口
 *
 * @author tankaikai
 * @since 2024-09-24 16:56
 */
@Slf4j
@RestController
@RequiredArgsConstructor
@Api(tags = "店铺支付相关接口")
@RequestMapping(value = {"/api/shop-pay-api", "/api/shopPayApi"})
public class ShopPayApiController {

    private final ParamsService paramsService;

    @GetMapping("getOrderPayUrl")
    @ApiOperation("获取店铺订单支付URL")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "orderId", value = "订单id", paramType = "query", required = true, dataType = "String"),
            @ApiImplicitParam(name = "shopId", value = "店铺id", paramType = "query", required = true, dataType = "String"),
    })
    public ResponseEntity url(@RequestParam Map<String, Object> params) {
        MapProxy mapProxy = MapProxy.create(params);
        String shopId = mapProxy.getStr("shopId");
        String orderId = mapProxy.getStr("orderId");
        try {
            if (StrUtil.isBlank(shopId)) {
                throw new BadRequestException("店铺id不能为空");
            }
            if (StrUtil.isBlank(orderId)) {
                throw new BadRequestException("订单id不能为空");
            }
            String baseUrl = paramsService.getValue(ParamsEnum.SHOP_ORDER_PAY_BASE_URL.name());
            String buildUrl = URLUtil.buildQuery(params, Charset.defaultCharset());
            String fullUrl = baseUrl.concat("?").concat(buildUrl);
            return ResponseEntity.ok().body(fullUrl);
        } catch (BadRequestException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        } catch (Exception e) {
            log.error("获取店铺订单支付URL异常", e);
            return ResponseEntity.ok().body("获取店铺订单支付URL异常");
        }
    }
}
