package com.zhentao.controller;

import com.github.binarywang.wxpay.exception.WxPayException;
import com.zhentao.common.Result;
import com.zhentao.dto.VipPayOrderRequest;
import com.zhentao.service.VipService;
import com.zhentao.vo.UserVipInfoVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * VIP控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/vip")
public class VipController {


    @Autowired
    private VipService vipService;

    /**
     * 获取VIP信息和套餐列表
     * @param userId 用户ID（可选，不传则默认为1）
     * @return VIP信息
     */
    @GetMapping("/info")
    public Result<UserVipInfoVO> getVipInfo(@RequestParam(required = false) Long userId) {
        try {
            // 如果没有传userId，默认使用1
            if (userId == null) {
                userId = 1L;
            }

            UserVipInfoVO vo = vipService.getVipInfo(userId);
            return Result.success(vo);
        } catch (Exception e) {
            return Result.error("获取VIP信息失败: " + e.getMessage());
         }
    }

    /**
     * 购买VIP
     * @param userId 用户ID
     * @param packageId 套餐ID
     * @return 购买结果
     */
    @PostMapping("/purchase")
    public Result<String> purchaseVip(@RequestBody VipPayOrderRequest payOrderRequest) {
        try {
            Map<String, Object> stringObjectMap = vipService.purchaseVip(payOrderRequest.getUserId(), payOrderRequest.getPackageId());
            if (stringObjectMap != null) {
                return Result.success("VIP开通成功！", stringObjectMap);
            } else {
                return Result.error("VIP开通失败");
            }
        } catch (RuntimeException e) {
            return Result.error(e.getMessage());
        } catch (Exception e) {
            log.error(e.getMessage());
            return Result.error("VIP开通失败");
        }
    }

    /**
     * 微信支付V2回调接口（需配置为外网可访问）
     */
    @PostMapping("/notify")
    public String handleWxPayNotify(@RequestBody String notifyData) {
        log.info("收到微信支付回调：{}", notifyData);
        try {
            return vipService.handlePayNotify(notifyData);
        } catch (WxPayException e) {
            log.error("处理支付回调失败", e);
            return "处理支付回调失败";
        }
    }
}


