package com.sonic.lion.controller.api;

import com.sonic.common.auth.IgnoreAuth;
import com.sonic.common.rpc.Result;
import com.sonic.lion.domain.entity.AccountBuff;
import com.sonic.lion.domain.entity.PayTrade;
import com.sonic.lion.domain.enums.SystemUser;
import com.sonic.lion.domain.input.PlatformGiftInput;
import com.sonic.lion.domain.input.PrePaymentInput;
import com.sonic.lion.domain.output.PrePaymentOutput;
import com.sonic.lion.domain.req.*;
import com.sonic.lion.domain.resp.BuffCheckoutResp;
import com.sonic.lion.domain.resp.PrePaymentResp;
import com.sonic.lion.domain.resp.QueryResp;
import com.sonic.lion.enums.PayChannel;
import com.sonic.lion.enums.ToastResultCode;
import com.sonic.lion.lib.input.GetAccountBuffInput;
import com.sonic.lion.lib.output.AccountBuffOutput;
import com.sonic.lion.service.BuffTransferService;
import com.sonic.lion.service.CheckOutService;
import com.sonic.lion.service.PayTradeService;
import com.sonic.sdk.api.annotation.InternalRpc;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.time.ZoneOffset;

/**
 * @author: code
 * @date: 2025/05/11
 * @Description:
 * @version: 1.0.0
 */
@InternalRpc(path = "/api/**")
@RestController
public class PayTradeApi {

    @Autowired
    private PayTradeService payTradeService;
    @Autowired
    private BuffTransferService buffTransferService;
    @Autowired
    private CheckOutService checkOutService;

    @ApiOperation(value = "创建账号钱包", tags = "API-接口")
    @IgnoreAuth
    @PostMapping("/api/pay/trade/create-account-buff")
    public Result<Void> createAccountBuff(@RequestBody GetAccountBuffInput input) {
        //创建账号钱包
        buffTransferService.getAndInitAccount(input.getUid());
        return Result.success();
    }

    @ApiOperation(value = "获取用户余额", tags = "API-接口")
    @IgnoreAuth
    @PostMapping("/api/pay/trade/get-account-buff")
    public Result<AccountBuffOutput> getAccountBuff(@RequestBody GetAccountBuffInput input) {
        AccountBuffOutput output = new AccountBuffOutput();
        AccountBuff accountBuff = buffTransferService.getAndInitAccount(input.getUid());
        BeanUtils.copyProperties(accountBuff, output);
        return Result.success(output);
    }


    @ApiOperation(value = "预下单", tags = "API-接口")
    @IgnoreAuth
    @PostMapping("/api/pay/trade/pre-payment")
    public Result prePayment(@RequestBody @Validated PrePaymentReq req) {
        ToastResultCode.PARAM_ERROR.check(req.getDesAccountId() == null);
        PrePaymentInput input = PrePaymentInput.builder()
                .platform(req.getPlatform())
                .platformFee(req.getPlatformFee())
                .outTradeNo(req.getOutTradeNo())
                .outTradeNoRelationNo(req.getOutTradeNoRelationNo())
                .bizType(req.getBizType())
                .name(req.getName())
                .srcAccountId(req.getSrcAccountId())
                .desAccountNo(req.getDesAccountId().toString())
                .productAmount(req.getProductAmount())
                .promoAmount(req.getPromoAmount())
                .remark(req.getRemark())
                .srcAccountName("")
                .closeTime(req.getCloseTime())
                .resourceKey(req.getResourceKey())
                .resourceNum(req.getResourceNum())
                .extend(req.getExtend())
                .payChannel(PayChannel.STRIPE)
                .ip(req.getIp())
                .build();
        PrePaymentOutput output = payTradeService.prePayment(input);
        PrePaymentResp resp = PrePaymentResp.builder()
                .tradeNo(output.getTradeNo())
                .outTradeNo(output.getOutTradeNo())
                .outTradeNoRelationNo(output.getOutTradeNoRelationNo())
                .tradeStatus(output.getTradeStatus())
                .build();
        return Result.success(resp);
    }

    @ApiOperation(value = "查询交易结果", tags = "API-接口")
    @IgnoreAuth
    @PostMapping("/api/pay/trade/query")
    public Result query(@RequestBody @Validated QueryReq req) {
        PayTrade payTrade = payTradeService.getByPlatformAndOuterTradeNo(req.getPlatform(), req.getOutTradeNo());
        if (payTrade == null) {
            return Result.success();
        }
        QueryResp resp = new QueryResp();
        BeanUtils.copyProperties(payTrade, resp);
        if (payTrade.getPayTime() != null) {
            resp.setPayTime(payTrade.getPayTime().toInstant(ZoneOffset.of("+8")).toEpochMilli());
        }
        return Result.success(resp);
    }

    @ApiOperation(value = "退款", tags = "API-接口")
    @IgnoreAuth
    @PostMapping("/api/pay/trade/refund")
    public Result refund(@RequestBody @Validated RefundReq req) {
        payTradeService.refund(req);
        return Result.success();
    }

    @ApiOperation(value = "完成交易", tags = "API-接口")
    @IgnoreAuth
    @PostMapping("/api/pay/trade/complete-trade")
    public Result completeSecuredTrade(@RequestBody @Validated CompleteSecuredTradeReq req) {
        payTradeService.completeSecuredTrade(req.getPlatform(), req.getOutTradeNo());
        return Result.success();
    }

    @ApiOperation(value = "关闭交易", tags = "API-接口")
    @IgnoreAuth
    @PostMapping("/api/pay/trade/close-trade")
    public Result closeTrade(@RequestBody @Validated CloseTradeReq req) {
        payTradeService.closeTrade(req.getPlatform(), req.getOutTradeNo());
        return Result.success();
    }

    @ApiOperation(value = "结账给用户", tags = "API-接口")
    @IgnoreAuth
    @PostMapping("/api/pay/trade/checkoutToUser")
    public Result<BuffCheckoutResp> checkoutToUser(@RequestBody @Validated PrePaymentReq req) {
        return Result.success(checkOutService.checkout(req));
    }

    @ApiOperation(value = "结账给平台", tags = "API-接口")
    @IgnoreAuth
    @PostMapping("/api/pay/trade/checkoutToB")
    public Result<BuffCheckoutResp> checkoutToB(@RequestBody @Validated PrePaymentReq req) {
        //结账给系统用户
        req.setDesAccountId(SystemUser.SYSTEM_USER_1.getValue());
        return Result.success(checkOutService.checkout(req));
    }

    @ApiOperation(value = "平台赠送", tags = "API-接口")
    @IgnoreAuth
    @PostMapping("/api/pay/trade/systemGift")
    public Result<Long> systemGift(@RequestBody @Validated PlatformGiftInput req) {
        PayTrade payTrade = payTradeService.platformGift(req);
        Long amount = payTrade == null ? 0L : payTrade.getAmount();
        return Result.success(amount);
    }

}
