package com.tashow.cloud.pay.controller.app.order;

import com.tashow.cloud.common.pojo.CommonResult;
import com.tashow.cloud.common.util.object.BeanUtils;
import com.tashow.cloud.pay.controller.admin.order.vo.PayOrderRespVO;
import com.tashow.cloud.pay.controller.admin.order.vo.PayOrderSubmitRespVO;
import com.tashow.cloud.pay.controller.app.order.vo.AppPayOrderSubmitReqVO;
import com.tashow.cloud.pay.controller.app.order.vo.AppPayOrderSubmitRespVO;
import com.tashow.cloud.pay.convert.order.PayOrderConvert;
import com.tashow.cloud.pay.dal.dataobject.order.PayOrderDO;
import com.tashow.cloud.pay.service.order.PayOrderService;
import com.tashow.cloud.payapi.enums.order.PayOrderStatusEnum;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import static com.tashow.cloud.common.pojo.CommonResult.success;
import static com.tashow.cloud.common.util.servlet.ServletUtils.getClientIP;


/**
 * 用户 APP - 支付订单
 */
@RestController
@RequestMapping("/pay/order")
@Validated
@Slf4j
public class AppPayOrderController {

    @Resource
    private PayOrderService payOrderService;

    /**
     * 获得支付订单
     * @param id 编号
     * @param sync 是否同步
     * @return
     */
    @GetMapping("/get")
    public CommonResult<PayOrderRespVO> getOrder(@RequestParam("id") Long id,
                                                 @RequestParam(value = "sync", required = false) Boolean sync) {
        PayOrderDO order = payOrderService.getOrder(id);
        // sync 仅在等待支付
        if (Boolean.TRUE.equals(sync) && PayOrderStatusEnum.isWaiting(order.getStatus())) {
            payOrderService.syncOrderQuietly(order.getId());
            // 重新查询，因为同步后，可能会有变化
            order = payOrderService.getOrder(id);
        }
        return success(BeanUtils.toBean(order, PayOrderRespVO.class));
    }

    /**
     * 提交支付订单
     * @param reqVO
     * @return
     */
    @PostMapping("/submit")
    public CommonResult<AppPayOrderSubmitRespVO> submitPayOrder(@RequestBody AppPayOrderSubmitReqVO reqVO) {
        // 1. 钱包支付事，需要额外传 user_id 和 user_type
//        if (Objects.equals(reqVO.getChannelCode(), PayChannelEnum.WALLET.getCode())) {
//            Map<String, String> channelExtras = reqVO.getChannelExtras() == null ?
//                    Maps.newHashMapWithExpectedSize(2) : reqVO.getChannelExtras();
//            channelExtras.put(WalletPayClient.USER_ID_KEY, String.valueOf(getLoginUserId()));
//            channelExtras.put(WalletPayClient.USER_TYPE_KEY, String.valueOf(getLoginUserType()));
//            reqVO.setChannelExtras(channelExtras);
//        }

        // 2. 提交支付
        PayOrderSubmitRespVO respVO = payOrderService.submitOrder(reqVO, getClientIP());
        return success(PayOrderConvert.INSTANCE.convert3(respVO));
    }

}
