package com.ruoyi.iit.service.impl;

import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.utils.CommonAsyncManager;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.LibreOfficeConvertUtil;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.iit.domain.IitFileImage;
import com.ruoyi.iit.domain.IitFileInfo;
import com.ruoyi.iit.domain.IitMyselfFile;
import com.ruoyi.iit.mapper.IitFileImageMapper;
import com.ruoyi.iit.mapper.IitFileInfoMapper;
import com.ruoyi.iit.mapper.IitMyselfFileMapper;
import com.ruoyi.iit.service.IIitFileInfoService;
import org.jodconverter.office.OfficeManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.TimerTask;
import java.util.stream.Collectors;

/**
 * 文件管理Service业务层处理
 *
 * @author Hao Li
 * @date 2025-04-11
 */
@Service
public class IitFileInfoServiceImpl implements IIitFileInfoService {
    @Autowired
    private IitFileInfoMapper iitFileInfoMapper;

    @Autowired
    private IitMyselfFileMapper iitMyselfFileMapper;

    @Autowired
    private IitFileImageMapper iitFileImageMapper;

    @Value("${ruoyi.profile}")
    private String profile;

    @Autowired
    private OfficeManager officeManager;


    /**
     * 查询文件管理
     *
     * @param id 文件管理主键
     * @return 文件管理
     */
    @Override
    public IitFileInfo selectIitFileInfoById(Long id)
    {
        return iitFileInfoMapper.selectIitFileInfoById(id);
    }

    /**
     * 查询文件管理列表
     *
     * @param iitFileInfo 文件管理
     * @return 文件管理
     */
    @Override
    @DataScope(deptAlias = "u", userAlias = "u")
    public List<IitFileInfo> selectIitFileInfoList(IitFileInfo iitFileInfo)
    {
        return iitFileInfoMapper.selectIitFileInfoList(iitFileInfo);
    }

    @Override
    public List<IitFileInfo> selectMyselfList(IitFileInfo iitFileInfo) {
        // 获取当前登录用户的id
        Long userId = SecurityUtils.getUserId();
        iitFileInfo.setUserId(userId);
        return iitFileInfoMapper.selectMyselfList(iitFileInfo);
    }

    @Override
    public List<String> getFileImage(Long id) {
        IitFileImage queryParam = new IitFileImage();
        queryParam.setFileId(id);
        List<IitFileImage> fileImageList = iitFileImageMapper.selectIitFileImageList(queryParam);
        if (CollectionUtils.isEmpty(fileImageList)) {
            return new ArrayList<>();
        }
        return fileImageList.stream().map(IitFileImage::getImageUrl).collect(Collectors.toList());
    }

    /**
     * 新增文件管理
     *
     * @param iitFileInfo 文件管理
     * @return 结果
     */
    @Override
    public int insertIitFileInfo(IitFileInfo iitFileInfo)
    {
        iitFileInfo.setCreateTime(DateUtils.getNowDate());
        // fileUrl : /profile/upload/2025/04/11/e1_代码项目交接.xlsx_20250411101820A001.xlsx
        String filePath = profile + iitFileInfo.getFileUrl().replace("/profile", "");
        // filePath : /home/inspur/iit/uploadPath/upload/2025/04/11/e1_代码项目交接.xlsx_20250411101820A001.xlsx
        iitFileInfo.setFilePath(filePath);
        String newFileName = filePath.substring(filePath.lastIndexOf("/") + 1);
        // newFileName : e1_代码项目交接.xlsx_20250411101820A001.xlsx
        String oldFileName = newFileName.substring(0, newFileName.lastIndexOf("_"));
        iitFileInfo.setFileName(oldFileName);
        // 获取文件大小
        iitFileInfo.setFileSize(getFileSize(filePath));
        // userId
        iitFileInfo.setUserId(SecurityUtils.getUserId());
        // deptId
        iitFileInfo.setDeptId(SecurityUtils.getDeptId());
        // userName
        iitFileInfo.setUserName(SecurityUtils.getLoginUser().getUser().getNickName());

        iitFileInfo.setPushTimes(0);

        // 文件新增以后，保存至我的文件表
        int insertResult = iitFileInfoMapper.insertIitFileInfo(iitFileInfo);
        IitMyselfFile iitMyselfFile = new IitMyselfFile();
        iitMyselfFile.setFileId(iitFileInfo.getId());
        iitMyselfFile.setUserId(SecurityUtils.getUserId());
        iitMyselfFile.setCreateTime(DateUtils.getNowDate());
        iitMyselfFileMapper.insertIitMyselfFile(iitMyselfFile);

        // 文件转换成图片 并保存数据库
        CommonAsyncManager.me().execute(fileToImage(filePath, filePath + Constants.PDF, officeManager,
                iitFileInfo, iitFileImageMapper));

        return insertResult;
    }

    /**
     * 操作日志记录
     *
     * @param sourceFile 源文件
     * @param tarPdfFile 目标文件
     * @return 任务task
     */
    public static TimerTask fileToImage(final String sourceFile, final String tarPdfFile, OfficeManager officeManage,
                                        IitFileInfo iitFileInfo, IitFileImageMapper iitFileImageMapper) {
        return new TimerTask() {
            @Override
            public void run() {
                try {
                    String pdfFile = LibreOfficeConvertUtil.convertToPdf(sourceFile, tarPdfFile, officeManage);
                    long timeMillis = System.currentTimeMillis();
                    int pageSize = LibreOfficeConvertUtil.convertToImage(pdfFile, timeMillis);
                    String pdfFileName = pdfFile.substring(pdfFile.lastIndexOf("/") + 1);
                    Long fileId = iitFileInfo.getId();
                    Date nowDate = DateUtils.getNowDate();
                    for (int i = 0; i < pageSize; i++) {
                        IitFileImage iitFileImage = new IitFileImage();
                        // String filePath = pdfFile + "." + i + ".png";
                        String imgPath = pdfFile.replace(pdfFileName, String.valueOf(timeMillis)) + "." + i + ".png";
                        String fileUrl = imgPath.replace("/home/inspur/iit/uploadPath", "/profile");
                        iitFileImage.setFileId(fileId);
                        iitFileImage.setImageUrl(fileUrl);
                        iitFileImage.setCreateTime(nowDate);
                        iitFileImageMapper.insertIitFileImage(iitFileImage);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
        };
    }

    private Long getFileSize(String filePath) {
        File file = new File(filePath);
        // 转换成KB
        return file.length() / 1024;
    }

    /**
     * 修改文件管理
     *
     * @param iitFileInfo 文件管理
     * @return 结果
     */
    @Override
    public int updateIitFileInfo(IitFileInfo iitFileInfo)
    {
        return iitFileInfoMapper.updateIitFileInfo(iitFileInfo);
    }

    /**
     * 批量删除文件管理
     *
     * @param ids 需要删除的文件管理主键
     * @return 结果
     */
    @Override
    public int deleteIitFileInfoByIds(Long[] ids)
    {
        return iitFileInfoMapper.deleteIitFileInfoByIds(ids);
    }

    /**
     * 删除文件管理信息
     *
     * @param id 文件管理主键
     * @return 结果
     */
    @Override
    public int deleteIitFileInfoById(Long id)
    {
        return iitFileInfoMapper.deleteIitFileInfoById(id);
    }
}
