package com.srs.web.controller.common;

import com.srs.common.config.SrsConfig;
import com.srs.common.core.controller.BaseController;
import com.srs.common.core.domain.AjaxResult;
import com.srs.common.utils.sign.ImageSignUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Base64;

/**
 * 受保护图片接口
 * 提供签名URL的图片访问
 */
@RestController
@RequestMapping("/common/stamp")
@Api(value = "受保护图片管理", tags = "受保护图片管理")
public class StampController extends BaseController {

    /**
     * 获取印章图片的Base64编码（需要登录验证）
     */
    @GetMapping("/base64")
    @ApiOperation("获取印章图片Base64编码")
    public AjaxResult getStampBase64() {
        String stampPath = SrsConfig.getProfile() + "/stamp/stamp.jpg";
        File file = new File(stampPath);
        
        if (!file.exists()) {
            return error("印章图片不存在");
        }
        
        try (FileInputStream fis = new FileInputStream(file)) {
            byte[] bytes = new byte[(int) file.length()];
            fis.read(bytes);
            String base64 = Base64.getEncoder().encodeToString(bytes);
            String dataUrl = "data:image/jpeg;base64," + base64;
            return success(dataUrl);
        } catch (IOException e) {
            return error("读取印章图片失败");
        }
    }
    
    /**
     * 获取印章图片的Base64编码（指定文件名）
     */
    @GetMapping("/base64/{fileName}")
    @ApiOperation("获取印章图片Base64编码")
    public AjaxResult getStampBase64ByName(@PathVariable String fileName) {
        String stampPath = SrsConfig.getProfile() + "/stamp/" + fileName;
        File file = new File(stampPath);
        
        if (!file.exists()) {
            return error("印章图片不存在");
        }
        
        try (FileInputStream fis = new FileInputStream(file)) {
            byte[] bytes = new byte[(int) file.length()];
            fis.read(bytes);
            String base64 = Base64.getEncoder().encodeToString(bytes);
            String mimeType = fileName.toLowerCase().endsWith(".png") ? "image/png" : "image/jpeg";
            String dataUrl = "data:" + mimeType + ";base64," + base64;
            return success(dataUrl);
        } catch (IOException e) {
            return error("读取印章图片失败");
        }
    }
}
