package com.ruoyi.system.service.webService;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import cn.ljserver.tool.weboffice.v3.exception.FileNotExist;
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.DateUtils;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.system.domain.loan.LoanApplicationFj;
import com.ruoyi.system.domain.webOffice.WebofficeFj;
import com.ruoyi.system.mapper.LoanApplicationFjMapper;
import com.ruoyi.system.mapper.SysUserMapper;
import com.ruoyi.system.mapper.WebofficeFjMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

/**
 * webOffice附件记录Service业务层处理
 *
 * @author boman
 * @date 2024-05-20
 */
@Service
public class WebofficeFjServiceImpl implements IWebofficeFjService
{
    @Autowired
    private WebofficeFjMapper webofficeFjMapper;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private SysUserMapper userMapper;

    @Autowired
    private LoanApplicationFjMapper loanApplicationFjMapper;

    /**
     * 查询webOffice附件记录
     *
     * @param webofficeId webOffice附件记录主键
     * @return webOffice附件记录
     */
    @Override
    public WebofficeFj selectWebofficeFjByWebofficeId(Long webofficeId)
    {
        return webofficeFjMapper.selectWebofficeFjByWebofficeId(webofficeId);
    }

    /**
     * 查询webOffice附件记录列表
     *
     * @param webofficeFj webOffice附件记录
     * @return webOffice附件记录
     */
    @Override
    public List<WebofficeFj> selectWebofficeFjList(WebofficeFj webofficeFj)
    {
        return webofficeFjMapper.selectWebofficeFjList(webofficeFj);
    }

    /**
     * 新增webOffice附件记录
     *
     * @param webofficeFj webOffice附件记录
     * @return 结果
     */
    @Override
    public int insertWebofficeFj(WebofficeFj webofficeFj)
    {
        webofficeFj.setCreateTime(LocalDateTime.now());
        return webofficeFjMapper.insertWebofficeFj(webofficeFj);
    }

    /**
     * 修改webOffice附件记录
     *
     * @param webofficeFj webOffice附件记录
     * @return 结果
     */
    @Override
    public int updateWebofficeFj(WebofficeFj webofficeFj)
    {
        webofficeFj.setUpdateTime(LocalDateTime.now());
        return webofficeFjMapper.updateWebofficeFj(webofficeFj);
    }

    /**
     * 批量删除webOffice附件记录
     *
     * @param webofficeIds 需要删除的webOffice附件记录主键
     * @return 结果
     */
    @Override
    public int deleteWebofficeFjByWebofficeIds(Long[] webofficeIds)
    {
        return webofficeFjMapper.deleteWebofficeFjByWebofficeIds(webofficeIds);
    }

    /**
     * 删除webOffice附件记录信息
     *
     * @param webofficeId webOffice附件记录主键
     * @return 结果
     */
    @Override
    public int deleteWebofficeFjByWebofficeId(Long webofficeId)
    {
        return webofficeFjMapper.deleteWebofficeFjByWebofficeId(webofficeId);
    }

    @Override
    public String upload(MultipartFile file) {
        return null;
    }

    @SneakyThrows
    @Override
    public String upload(String fileId, byte[] content, String suffix, HttpServletRequest request) {
        //SysUser user = SecurityUtils.getLoginUser().getUser();
        //从redis取文件信息
        LoanApplicationFj cacheObject = redisCache.getCacheObject(fileId + "info");
        if (cacheObject == null) {
            throw new FileNotExist();
        }
        String userId  = request.getHeader("X-WPS-USERID");
        if(StringUtils.isEmpty(userId)){
            return "参数错误";
        }
        SysUser user = userMapper.selectUserById(Long.valueOf(userId));
        MultipartFile file = new MockMultipartFile(cacheObject.getName(), cacheObject.getName(), suffix, content);
        // 上传文件路径
        String filePath = RuoYiConfig.getUploadPath();
        String fileName = redisCache.getCacheObject(fileId + "fileName");
        if(StringUtils.isEmpty(fileName)){
            //已经存在文件，文件名不变
            if(cacheObject.getFjId()!=null && cacheObject.getFjId()!=0L){
                fileName = FileUploadUtils.uploadLoanApplicationNumberOldName(filePath, file, cacheObject.getLoanApplicationNumber(), file.getOriginalFilename());
            }else{
                // 上传并返回新文件名称
                fileName = FileUploadUtils.uploadLoanApplicationNumber(filePath, file, cacheObject.getLoanApplicationNumber(), file.getOriginalFilename());
            }
        }else{
            String name = FileUtils.getName(fileName);
            fileName = FileUploadUtils.uploadLoanApplicationNumberOldName(filePath, file, cacheObject.getLoanApplicationNumber(), name);
        }
        redisCache.setCacheObject(fileId + "fileName",fileName,1, TimeUnit.HOURS);
        //String url = serverConfig.getUrl() + fileName;
        //将文件存入在线编辑预存表
        /*WebofficeFj webofficeFj = new WebofficeFj();
        webofficeFj.setFjId(fileId);
        webofficeFj.setVersion(webofficeFj.getVersion() + 1);
        webofficeFj.setUrl(fileName);
        webofficeFj.setCreateTime(LocalDateTime.now());
        webofficeFj.setUpdateTime(LocalDateTime.now());
        webofficeFj.setSize(file.getSize());
        webofficeFj.setName(file.getName());
        webofficeFj.setCreateBy(user.getNickName());
        webofficeFj.setCreatorId(String.valueOf(user.getUserId()));
        webofficeFj.setModifierId(String.valueOf(user.getUserId()));
        webofficeFjMapper.insertWebofficeFj(webofficeFj);
        System.out.println(webofficeFj.toString()+"6666666666666666666666666");
        if(cacheObject.getFjId()==null || cacheObject.getFjId()==0L){
            if(cacheObject.getLoanApplicationId()!=null && cacheObject.getLoanApplicationId()!=0L){
                //将文件存入loan_application_fj表
                LoanApplicationFj loanApplicationFj = new LoanApplicationFj();
                loanApplicationFj.setLoanApplicationId(cacheObject.getLoanApplicationId());
                loanApplicationFj.setLoanApplicationNumber(cacheObject.getLoanApplicationNumber());
                loanApplicationFj.setOldName(cacheObject.getName());
                loanApplicationFj.setName(cacheObject.getName());
                loanApplicationFj.setUrl(fileName);
                loanApplicationFj.setBigType(cacheObject.getBigType());
                loanApplicationFj.setType(cacheObject.getType());
                loanApplicationFj.setCreateBy(user.getNickName());
                loanApplicationFj.setCreateTime(DateUtils.getNowDate());
                loanApplicationFjMapper.insertLoanApplicationFj(loanApplicationFj);
                System.out.println(loanApplicationFj.toString()+"888888888888888888888888888888");
            }
        }*/

        return fileName;
    }

    public List<WebofficeFj> selectWebofficeFjList(String fileId)
    {
        List<WebofficeFj> webofficeFjList = new ArrayList<>();
        WebofficeFj webofficeFj = new WebofficeFj();
        SysUser user = SecurityUtils.getLoginUser().getUser();
        webofficeFj.setFjId(fileId);
        LoanApplicationFj cacheObject = redisCache.getCacheObject(fileId + "info");
        webofficeFj.setName(cacheObject.getName());
        webofficeFj.setSize(102400L);
        webofficeFj.setUpdateTime(LocalDateTime.now());
        webofficeFj.setUpdateTime(LocalDateTime.now());
        webofficeFj.setCreatorId(String.valueOf(user.getUserId()));
        webofficeFj.setModifierId(String.valueOf(user.getUserId()));
        webofficeFjList.add(webofficeFj);
        WebofficeFj weboffice = new WebofficeFj();
        weboffice.setFjId(fileId);
        webofficeFjList = webofficeFjMapper.selectWebofficeFjList(weboffice);
        return webofficeFjList;
    }

    /***
     * 获取单个版本详情
     * @param fileId
     * @return
     */
    public WebofficeFj fetchFileVersion(String fileId, int version)
    {
        if(!DateUtils.isNumeric(fileId)){
            fileId = "0";
        }
        WebofficeFj webofficeFj = new WebofficeFj();
        webofficeFj.setFjId(fileId);
        webofficeFj.setVersion(version);
        List<WebofficeFj> webofficeFjs = webofficeFjMapper.selectWebofficeFjList(webofficeFj);
        if(webofficeFjs!=null && webofficeFjs.size()>0){
            return webofficeFjs.get(0);
        }else {
            return new WebofficeFj();
        }

    }

    /***
     * 查询最新版本的文件
     * @param fileId
     * @return
     */
    public WebofficeFj fetchFile(String fileId)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        WebofficeFj webofficeFj = new WebofficeFj();
        webofficeFj.setFjId(fileId);
        List<WebofficeFj> webofficeFjs = webofficeFjMapper.selectWebofficeFjList(webofficeFj);
        if(webofficeFjs!=null && webofficeFjs.size()>0){
            return webofficeFjs.get(0);
        }else {
            //从redis取文件信息
            LoanApplicationFj cacheObject = redisCache.getCacheObject(fileId + "info");
            webofficeFj.setName(cacheObject.getName());
            webofficeFj.setSize(102400L);
            webofficeFj.setVersion(1);
            webofficeFj.setCreateTime(LocalDateTime.now());
            webofficeFj.setUpdateTime(LocalDateTime.now());
            webofficeFj.setCreatorId(String.valueOf(user.getUserId()));
            webofficeFj.setModifierId(String.valueOf(user.getUserId()));
            return webofficeFj;
        }

    }
}
