package org.springblade.openapi.wps;

import com.alibaba.fastjson2.JSON;
import io.swagger.v3.oas.annotations.Hidden;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springblade.common.utils.ObsUtil;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.file.feign.IFileClient;
import org.springblade.file.pojo.vo.AttachmentDetailVO;
import org.springblade.openapi.wps.convert.WpsFileConvert;
import org.springblade.openapi.wps.api.IApi4Wps;
import org.springblade.openapi.wps.constant.WpsConstant;
import org.springblade.openapi.wps.exception.Api4WpsException;
import org.springblade.openapi.wps.pojo.dto.Api4WpsFileInfoDTO;
import org.springblade.openapi.wps.pojo.enums.Api4WpsError;
import org.springblade.openapi.wps.util.TokenUtils;
import org.springblade.openapi.wps.pojo.vo.*;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.Locale;

/**
 * @author bfhuange
 * @date 2024/10/30
 */
@Slf4j
@Hidden
@AllArgsConstructor
@RestController
public class Api4Wps implements IApi4Wps {

    /**
     *  图片扩展名列表
     */
    private static final List<String> IMAGE_EXT = List.of("bmp", "jpeg", "jpg", "png", "gif");

    private final IFileClient fileClient;
    private final WpsFileConvert convert;

    @Override
    public Api4WpsFileInfoVO getFileInfo(String fileId, String token, Api4WpsFileInfoDTO param) {
        log.info("wps回调查询文件信息 参数 fileId：{} token：{} param：{}", fileId, token, JSON.toJSONString(param));
        long id = Func.toLong(fileId);
        if (id <= 0L) {
            throw new Api4WpsException(Api4WpsError.NOT_EXISTS);
        }
        if (token == null) {
            throw new Api4WpsException(Api4WpsError.PERMISSION_DENIED);
        }
        R<AttachmentDetailVO> result = fileClient.getAttachmentDetail(id);
        if (result == null || !result.isSuccess() || result.getData() == null || result.getData().getId() == null) {
            log.warn("wps回调查询文件信息 查询附件失败 ：{}", JSON.toJSONString(result));
            throw new Api4WpsException(Api4WpsError.NOT_EXISTS);
        }
        // 附件
        AttachmentDetailVO attachment = result.getData();
        Api4WpsFileVO fileVO = convert.attachment2file(attachment);
        // 用户信息
        Api4WpsUserVO user = TokenUtils.getWpsUser(token);
        if (user == null) {
            // 用户信息为空，token过期了
            throw new Api4WpsException(Api4WpsError.SESSION_EXPIRED);
        }

        // 用户不为空，添加水印
        boolean isImage = isImage(attachment.getAttachmentName());
        log.info("附件名：{} 是否图片：{}", attachment.getAttachmentName(), isImage);
        if (!isImage) {
            // 不是图片才加水印
            Api4WpsWatermarkVO watermark = new Api4WpsWatermarkVO();
            watermark.setType(WpsConstant.YES);
            watermark.setValue(user.getName());
            watermark.setHorizontal(100);
            watermark.setVertical(200);
            fileVO.setWatermark(watermark);
        }
        Api4WpsFileInfoVO fileInfoVO = new Api4WpsFileInfoVO();
        fileInfoVO.setUser(user);
        fileInfoVO.setFile(fileVO);
        // 缓存时间
        fileInfoVO.setAttrs(new Api4WpsAttrsVO(WpsConstant.FILE_INFO_DEFAULT_CACHE_TIME));
        log.info("wps回调查询文件信息 返回结果：{}", JSON.toJSONString(fileInfoVO));
        return fileInfoVO;
    }

    @Override
    public Api4WpsFileInfoVO getFileSave(String fileId, String saveType, String token, MultipartFile file, Api4WpsFileInfoDTO param) {
        try {
            log.info("wps回调-上传文件新版本 参数 fileId：{} token：{} param：{}", fileId, token, JSON.toJSONString(param));
            long id = Func.toLong(fileId);
            if (id == 0L) {
                return null;
            }
            R<AttachmentDetailVO> result = fileClient.getAttachmentDetail(id);
            if (result == null || !result.isSuccess()) {
                log.warn("wps回调-上传文件新版本 查询附件失败 ：{}", JSON.toJSONString(result));
                return null;
            }
            // 附件
            AttachmentDetailVO attachment = result.getData();
            Api4WpsFileVO fileVO = convert.attachment2file(attachment);
            fileVO.setVersion(2);
            ObsUtil.putObject(attachment.getObjectKey(), file.getInputStream());

            Api4WpsFileInfoVO fileInfoVO = new Api4WpsFileInfoVO();
            fileInfoVO.setFile(fileVO);

            return fileInfoVO;
        }catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     *  是否图片类型
     * @param fileName
     * @return
     */
    public boolean isImage(String fileName) {
        if (fileName == null) {
            return false;
        }
        int index = fileName.lastIndexOf(".");
        if (index < 0 || index +1 >= fileName.length() ) {
            return false;
        }
        String extName = fileName.substring(index + 1).toLowerCase(Locale.getDefault());
        return IMAGE_EXT.contains(extName);
    }
}
