package com.ruoyi.system.service.webOfficeImpl;


import cn.ljserver.tool.weboffice.v3.exception.FileNotExist;
import cn.ljserver.tool.weboffice.v3.model.FileInfo;
import cn.ljserver.tool.weboffice.v3.model.FileUploadSinglePhase;
import cn.ljserver.tool.weboffice.v3.service.SinglePhaseFileStorageService;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.system.domain.loan.LoanApplicationFj;
import com.ruoyi.system.domain.webOffice.WebofficeFj;
import com.ruoyi.system.service.webService.WebofficeFjServiceImpl;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 单阶段文件保存接口
 * <p>
 * <a href="https://solution.wps.cn/docs/callback/save.html#%E5%8D%95%E9%98%B6%E6%AE%B5%E6%8F%90%E4%BA%A4">详见wps web office官网</a>
 */
@Service
public class SinglePhaseFileStorageServiceImpl implements SinglePhaseFileStorageService {

    @Autowired
    private WebofficeFjServiceImpl webofficeFjServiceImpl;

    @Autowired
    private RedisCache redisCache;

    /**
     * 上传文件
     *
     * @param request 上传文件请求
     * @return 文件信息
     * <p>
     * <a href="https://solution.wps.cn/docs/callback/save.html#%E5%8D%95%E9%98%B6%E6%AE%B5%E6%8F%90%E4%BA%A4">详见wps web office官网</a>
     */
    @SneakyThrows
    @Override
    public FileInfo uploadFile(FileUploadSinglePhase.Request request) {
        // 获取用户信息 -> 这个方法点进去看看 ？？！！
        SysUser user = SecurityUtils.getLoginUser().getUser();

        //从redis取文件信息
        LoanApplicationFj cacheObject = redisCache.getCacheObject(request.getFileId() + "info");
        if (cacheObject == null) {
            throw new FileNotExist();
        }
        // 上传文件路径
        String filePath = RuoYiConfig.getUploadPath();
        // 上传并返回新文件名称
        String fileName = FileUploadUtils.uploadLoanApplicationNumber(filePath, request.getFile(), cacheObject.getLoanApplicationNumber(), request.getName());
        //String url = serverConfig.getUrl() + fileName;
        //将文件存入在线编辑预存表
        WebofficeFj webofficeFj = webofficeFjServiceImpl.fetchFile(request.getFileId());
        webofficeFj.setVersion(webofficeFj.getVersion() + 1);
        webofficeFj.setCreateTime(LocalDateTime.now());
        webofficeFj.setUpdateTime(LocalDateTime.now());
        webofficeFj.setSize(Long.valueOf(request.getSize()));
        webofficeFj.setName(request.getName());
        webofficeFj.setCreateBy(user.getNickName());
        webofficeFj.setCreatorId(String.valueOf(user.getUserId()));
        webofficeFj.setModifierId(String.valueOf(user.getUserId()));
        webofficeFjServiceImpl.insertWebofficeFj(webofficeFj);
        // 返回文件信息
        return webofficeFj.toFileInfo();
    }
}
