package com.sckw.file.service;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.StrUtil;
import com.sckw.core.common.enums.StringConstant;
import com.sckw.core.config.ProjectConfig;
import com.sckw.core.exception.BusinessException;
import com.sckw.core.model.constant.NumberConstant;
import com.sckw.core.utils.FileUploadUtils;
import com.sckw.core.utils.FileUtils;
import com.sckw.core.utils.IdWorker;
import com.sckw.core.utils.StringUtils;
import com.sckw.core.web.context.LoginUserHolder;
import com.sckw.core.web.response.HttpResult;
import com.sckw.file.api.dto.FileInfoVO;
import com.sckw.file.dao.KwsFileInfoDao;
import com.sckw.file.model.kwfFileInfo;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;

/**
 * @author xucaiqin
 * @date 2026-05-07 13:39:43
 */
@Service
@Slf4j
public class FileInfoService {
    @Resource
    private KwsFileInfoDao kwsFileInfoDao;
    @Resource
    private ProjectConfig projectConfig;

    @Resource
    private FileService fileService;

    @Value("${file.upload.oss-enabled:true}")
    private boolean ossEnabled;

    @Transactional(rollbackFor = Exception.class)
    public FileInfoVO uploadFile(MultipartFile file) {
        // 打开，调用FileService走OSS上传
        if (ossEnabled) {
            log.info("oss文件上传!");
            com.sckw.core.model.vo.FileInfoVO fileInfoVO = fileService.uploadFileInfoV2(file);
            log.info("OSS文件上传成功，文件访问URL: {}", fileInfoVO.getFileAbsolutePath());

            FileInfoVO infoVO = new FileInfoVO();
            infoVO.setType(fileInfoVO.getType());
            infoVO.setFileOriginalName(fileInfoVO.getFileOriginalName());
            infoVO.setFileMd5(fileInfoVO.getFileMd5());
            infoVO.setFileName(fileInfoVO.getFileName());
            infoVO.setFileSuffix(fileInfoVO.getFileSuffix());
            infoVO.setFileSize(fileInfoVO.getFileSize());
            infoVO.setFilePath(fileInfoVO.getFilePath());
            infoVO.setFileAbsolutePath(fileInfoVO.getFileAbsolutePath());
            return infoVO;
        }

        // 关闭，走本地上传
        boolean isEmpty = file.isEmpty();
        if (isEmpty) {
            throw new BusinessException("文件不能为空");
        }
        String filePath = projectConfig.getProfile();

        String fileName, md5;
        try {
            fileName = FileUploadUtils.upload(filePath, file);
            md5 = DigestUtils.md5Hex(file.getInputStream());
        } catch (IOException e) {
            log.error("文件上传异常 {}", e.getMessage());
            throw new BusinessException(e.getMessage());
        }

        String oFileName = file.getOriginalFilename();
        BigDecimal fileSize = FileUtils.getFileSize(file, StringConstant.KB);
        kwfFileInfo fileInfo = new kwfFileInfo();
        fileInfo.setId(new IdWorker(1).nextId());
        fileInfo.setOriginalName(oFileName);
        fileInfo.setFileSuffix(FilenameUtils.getExtension(oFileName));
        fileInfo.setFileSize(StringUtils.isBlank(fileSize) ? new BigDecimal(NumberConstant.ZERO) : fileSize);
        fileInfo.setType("LOCAL");
        fileInfo.setFileName(FileNameUtil.getName(fileName));
        fileInfo.setMd5(md5);
        fileInfo.setFilePath(fileName);
        fileInfo.setCreateTime(new Date());
        fileInfo.setUpdateTime(new Date());
        fileInfo.setStatus(0);
        fileInfo.setDelFlag(0);
        fileInfo.setCreateBy(LoginUserHolder.getUserId());
        fileInfo.setUpdateBy(LoginUserHolder.getUserId());
        kwsFileInfoDao.insert(fileInfo);

        FileInfoVO fileInfoVO = new FileInfoVO();
        fileInfoVO.setType(fileInfo.getType());
        fileInfoVO.setFileOriginalName(fileInfo.getOriginalName());
        fileInfoVO.setFileMd5(fileInfo.getMd5());
        fileInfoVO.setFileName(fileInfo.getFileName());
        fileInfoVO.setFileSuffix(fileInfo.getFileSuffix());
        fileInfoVO.setFileSize(fileInfo.getFileSize());
        fileInfoVO.setFilePath(fileName);
        fileInfoVO.setFileAbsolutePath(StrUtil.removeSuffix(projectConfig.getDomain(), "/") + "/" + StrUtil.removePrefix(fileName, "/"));
        return fileInfoVO;
    }
}
