package com.yingpai.miniapp.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import com.yingpai.miniapp.domain.bo.PaymentConfigBo;
import com.yingpai.miniapp.domain.vo.PaymentConfigVo;
import com.yingpai.miniapp.service.IPaymentConfigService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.dromara.common.core.domain.R;
import org.dromara.common.log.annotation.Log;
import org.dromara.common.log.enums.BusinessType;
import org.dromara.common.web.core.BaseController;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 支付配置管理
 */
@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/miniapp/paymentConfig")
public class PaymentConfigController extends BaseController {

    private final IPaymentConfigService paymentConfigService;

    /**
     * 获取支付配置
     */
    @SaCheckPermission("miniapp:paymentConfig:list")
    @GetMapping("/list")
    public R<PaymentConfigVo> list() {
        return R.ok(paymentConfigService.getConfig());
    }

    /**
     * 更新支付配置（全量）
     */
    @SaCheckPermission("miniapp:paymentConfig:edit")
    @Log(title = "支付配置", businessType = BusinessType.UPDATE)
    @PutMapping
    public R<Void> edit(@Validated @RequestBody PaymentConfigBo bo) {
        return toAjax(paymentConfigService.updateConfig(bo));
    }

    /**
     * 更新微信支付配置
     */
    @SaCheckPermission("miniapp:paymentConfig:edit")
    @Log(title = "微信支付配置", businessType = BusinessType.UPDATE)
    @PutMapping("/wxpay")
    public R<Void> editWxpay(@Validated @RequestBody PaymentConfigBo bo) {
        // 只更新微信支付相关字段
        PaymentConfigBo wxpayBo = new PaymentConfigBo();
        wxpayBo.setMchId(bo.getMchId());
        wxpayBo.setApiV3Key(bo.getApiV3Key());
        wxpayBo.setNotifyUrl(bo.getNotifyUrl());
        wxpayBo.setPublicKeyId(bo.getPublicKeyId());
        return toAjax(paymentConfigService.updateConfig(wxpayBo));
    }

    /**
     * 更新订阅价格配置
     */
    @SaCheckPermission("miniapp:paymentConfig:edit")
    @Log(title = "订阅价格配置", businessType = BusinessType.UPDATE)
    @PutMapping("/subscription")
    public R<Void> editSubscription(@Validated @RequestBody PaymentConfigBo bo) {
        // 只更新订阅价格相关字段
        PaymentConfigBo subBo = new PaymentConfigBo();
        subBo.setShortPrice(bo.getShortPrice());
        subBo.setStrongPrice(bo.getStrongPrice());
        return toAjax(paymentConfigService.updateConfig(subBo));
    }
    
    /**
     * 上传商户私钥文件
     */
    @SaCheckPermission("miniapp:paymentConfig:edit")
    @Log(title = "支付配置-上传私钥", businessType = BusinessType.UPDATE)
    @PostMapping("/uploadPrivateKey")
    public R<Void> uploadPrivateKey(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return R.fail("文件不能为空");
            }
            String filename = file.getOriginalFilename();
            if (filename == null || !filename.endsWith(".pem")) {
                return R.fail("请上传.pem格式的私钥文件");
            }
            return toAjax(paymentConfigService.savePrivateKey(file));
        } catch (Exception e) {
            log.error("上传私钥失败", e);
            return R.fail("上传失败：" + e.getMessage());
        }
    }

    /**
     * 上传支付证书文件
     */
    @SaCheckPermission("miniapp:paymentConfig:edit")
    @Log(title = "支付配置-上传证书", businessType = BusinessType.UPDATE)
    @PostMapping("/uploadCert")
    public R<Void> uploadCert(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return R.fail("文件不能为空");
            }
            String filename = file.getOriginalFilename();
            if (filename == null || !filename.endsWith(".pem")) {
                return R.fail("请上传.pem格式的证书文件");
            }
            return toAjax(paymentConfigService.saveCert(file));
        } catch (Exception e) {
            log.error("上传证书失败", e);
            return R.fail("上传失败：" + e.getMessage());
        }
    }

    /**
     * 上传微信支付公钥文件
     */
    @SaCheckPermission("miniapp:paymentConfig:edit")
    @Log(title = "支付配置-上传公钥", businessType = BusinessType.UPDATE)
    @PostMapping("/uploadPublicKey")
    public R<Void> uploadPublicKey(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return R.fail("文件不能为空");
            }
            String filename = file.getOriginalFilename();
            if (filename == null || !filename.endsWith(".pem")) {
                return R.fail("请上传.pem格式的公钥文件");
            }
            return toAjax(paymentConfigService.savePublicKey(file));
        } catch (Exception e) {
            log.error("上传公钥失败", e);
            return R.fail("上传失败：" + e.getMessage());
        }
    }
}
