package com.kym.admin.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.util.RandomUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kym.common.R;
import com.kym.common.annotation.SysLog;
import com.kym.common.utils.OssUtil;
import com.kym.common.utils.wx.WxMaQrCodeUtil;
import com.kym.entity.RechargePromotion;
import com.kym.entity.queryParams.CommonQueryParam;
import com.kym.service.RechargePromotionService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.FileOutputStream;
import java.util.UUID;

/**
 * 专属充值优惠活动管理
 *
 * @author skyline
 * @since 2026-06-03
 */
@RestController
@RequestMapping("/rechargePromotion")
public class PromotionController {

    private static final Logger log = LoggerFactory.getLogger(PromotionController.class);

    private final RechargePromotionService rechargePromotionService;

    public PromotionController(RechargePromotionService rechargePromotionService) {
        this.rechargePromotionService = rechargePromotionService;
    }

    @SaCheckPermission("promotion.list")
    @GetMapping("/list")
    R<?> list(@ModelAttribute CommonQueryParam params) {
        var page = rechargePromotionService.lambdaQuery()
                .orderByDesc(RechargePromotion::getCreateTime)
                .page(new Page<>(params.getPageNum(), params.getPageSize()));
        return R.success(page);
    }

    @GetMapping("/detail/{id}")
    R<?> detail(@PathVariable Long id) {
        return R.success(rechargePromotionService.getById(id));
    }

    @SaCheckPermission("promotion.add")
    @SysLog("新增专属优惠活动")
    @PostMapping("/add")
    R<?> add(@RequestBody RechargePromotion promotion) {
        // 自动生成唯一token
        String token;
        int retry = 0;
        do {
            token = RandomUtil.randomString(16);
            if (rechargePromotionService.lambdaQuery()
                    .eq(RechargePromotion::getToken, token).one() == null) {
                break;
            }
            retry++;
        } while (retry < 5);
        promotion.setToken(token);
        rechargePromotionService.save(promotion);
        return R.success();
    }

    @SaCheckPermission("promotion.modify")
    @SysLog("修改专属优惠活动")
    @PostMapping("/modify")
    R<?> modify(@RequestBody RechargePromotion promotion) {
        rechargePromotionService.updateById(promotion);
        return R.success();
    }

    @SaCheckPermission("promotion.remove")
    @SysLog("删除专属优惠活动")
    @GetMapping("/remove/{id}")
    R<?> remove(@PathVariable Long id) {
        rechargePromotionService.removeById(id);
        return R.success();
    }

    @SaCheckPermission("promotion.list")
    @SysLog("生成优惠活动二维码")
    @GetMapping("/generateQR/{id}")
    R<?> generateQR(@PathVariable Long id) {
        var promotion = rechargePromotionService.getById(id);
        if (promotion == null) {
            return R.failed(-1, "活动不存在");
        }

        // 如果已有二维码且未强制刷新，直接返回
        if (promotion.getQrCodeUrl() != null && !promotion.getQrCodeUrl().isBlank()) {
            return R.success(promotion.getQrCodeUrl());
        }

        try {
            byte[] qrCodeBytes = WxMaQrCodeUtil.generateUnlimitedQrCode(
                    promotion.getToken(), "pages-user/wallet/promotion");

            // 写入临时文件并上传到OSS
            String ossKey = "promotion_qr/" + UUID.randomUUID().toString() + ".jpg";
            File tempFile = File.createTempFile("promotion_qr_", ".jpg");
            try (FileOutputStream fos = new FileOutputStream(tempFile)) {
                fos.write(qrCodeBytes);
            }

            OssUtil.upload(ossKey, tempFile);
            tempFile.delete();

            String qrCodeUrl = "http://static.kuaiyuman.cn/" + ossKey;
            promotion.setQrCodeUrl(qrCodeUrl);
            rechargePromotionService.updateById(promotion);

            return R.success(qrCodeUrl);
        } catch (Exception e) {
            log.error("生成二维码失败: id={}", id, e);
            return R.failed(-1, "生成二维码失败: " + e.getMessage());
        }
    }
}
