package vip.xiaonuo.disk.service.impl;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qiwenshare.common.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.common.pojo.CommonResult;
import vip.xiaonuo.disk.domain.FileBean;
import vip.xiaonuo.disk.domain.ResourceFile;
import vip.xiaonuo.disk.domain.ResourceUserFile;
import vip.xiaonuo.disk.domain.UserFile;
import vip.xiaonuo.disk.dto.file.TranscodingReqDTO;
import vip.xiaonuo.disk.mapper.FileMapper;
import vip.xiaonuo.disk.mapper.ResourceFileMapper;
import vip.xiaonuo.disk.mapper.ResourceUserFileMapper;
import vip.xiaonuo.disk.mapper.UserFileMapper;
import vip.xiaonuo.disk.service.TranscodingService;
import vip.xiaonuo.disk.util.OfficeConverter;
import vip.xiaonuo.disk.util.PdfUtils;
import vip.xiaonuo.disk.util.VideoConverter;

import javax.annotation.Resource;
import java.util.ArrayList;

/**
 * 资源转码 service
 * @author jinjilong
 */
@Service
@Slf4j
public class TranscodingServiceImpl implements TranscodingService {

    @Resource
    private VideoConverter videoConverter;

    @Resource
    private FileMapper fileMapper;

    @Resource
    private UserFileMapper userFileMapper;

    @Resource
    private PdfUtils pdfUtils;

    @Resource
    private OfficeConverter officeConverter;




    @Resource
    private ResourceUserFileMapper resourceUserFileMapper;


    @Resource
    private ResourceFileMapper resourceFileMapper;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public CommonResult<String> transcodingVideo(TranscodingReqDTO transcodingReqDTO) {
        // 校验目标文件是否存在，是否是本人的
        String userId = StpLoginUserUtil.getLoginUser().getId();
        QueryWrapper<UserFile> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(UserFile::getFileId, transcodingReqDTO.getFileId());
        UserFile userFile = userFileMapper.selectOne(queryWrapper);
        if (userFile == null || !userFile.getUserId().equals(userId)) {
            return CommonResult.error("文件不存在或不是本人的");
        }
        FileBean fileBean = fileMapper.selectById(userFile.getFileId());
        if (fileBean == null) {
            return CommonResult.error("文件不存在");
        }
        // 构建转码格式列表
        ArrayList<String> formatList = new ArrayList<>();
        formatList.add(transcodingReqDTO.getFormat());
        // 判断视频还是图片
        if (transcodingReqDTO.getTranscodingType() == 0) {
            try {
                // 转码视频
                // mp4 wmv avi flv mpeg mpg rmvb mov 互相转
                videoConverter.convertAndUpload(fileBean.getFileUrl(), fileBean.getFileId(), new String[]{transcodingReqDTO.getFormat()});
                // 转换后把文件信息新增到数据库
                saveFile(userFile, fileBean, userId, transcodingReqDTO);
            } catch (Exception ex) {
                log.error(ex.getMessage());
                return CommonResult.error("格式转换失败");
            }
        } else if (transcodingReqDTO.getTranscodingType() == 1) {
            // 转码文档
            // pdf doc docx ppt pptx xls xlsx
            // doc转docx，ppt转pptx，xls转xlsx 所有均转pdf
            // 判断目标格式
            try {
                if ("pdf".equals(transcodingReqDTO.getFormat())) {
                    pdfUtils.convertToPdf(fileBean.getFileUrl(), fileBean.getFileId() + "." + transcodingReqDTO.getFormat());
                } else {
                    officeConverter.convertAndUpload(fileBean.getFileUrl(), fileBean.getFileId() + "." + transcodingReqDTO.getFormat());
                }
                // 转换后把文件信息新增到数据库
                saveFile(userFile, fileBean, userId, transcodingReqDTO);
            } catch (Exception ex) {
                log.error("格式转换:"+ex.getMessage());
                return CommonResult.error("格式转换失败");
            }
        }
        return CommonResult.ok("格式转换成功");
    }

    @Override
    public CommonResult<String> transcodingResource(TranscodingReqDTO transcodingReqDTO) {
        // 校验目标文件是否存在，是否是本人的
        String userId = StpLoginUserUtil.getLoginUser().getId();
        QueryWrapper<ResourceUserFile> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(ResourceUserFile::getFileId, transcodingReqDTO.getFileId());
        ResourceUserFile userFile = resourceUserFileMapper.selectOne(queryWrapper);
        if (userFile == null || !userFile.getUserId().equals(userId)) {
            return CommonResult.error("文件不存在或不是本人的");
        }
        ResourceFile fileBean = resourceFileMapper.selectById(userFile.getFileId());
        if (fileBean == null) {
            return CommonResult.error("文件不存在");
        }
        // 构建转码格式列表
        ArrayList<String> formatList = new ArrayList<>();
        formatList.add(transcodingReqDTO.getFormat());
        // 判断视频还是图片
        if (transcodingReqDTO.getTranscodingType() == 0) {
            try {
                // 转码视频
                // mp4 wmv avi flv mpeg mpg rmvb mov 互相转
                videoConverter.convertAndUpload(fileBean.getFileUrl(), fileBean.getFileId(), new String[]{transcodingReqDTO.getFormat()});
                // 转换后把文件信息新增到数据库
                saveResourceFile(fileBean, transcodingReqDTO);
            } catch (Exception ex) {
                log.error(ex.getMessage());
                return CommonResult.error("格式转换失败");
            }
        } else if (transcodingReqDTO.getTranscodingType() == 1) {
            // 转码文档
            // pdf doc docx ppt pptx xls xlsx
            // doc转docx，ppt转pptx，xls转xlsx 所有均转pdf
            // 判断目标格式
            try {
                if ("pdf".equals(transcodingReqDTO.getFormat())) {
                    pdfUtils.convertToPdf(fileBean.getFileUrl(), fileBean.getFileId() + "." + transcodingReqDTO.getFormat());
                } else {
                    officeConverter.convertAndUpload(fileBean.getFileUrl(), fileBean.getFileId() + "." + transcodingReqDTO.getFormat());
                }
                // 转换后把文件信息新增到数据库
                saveResourceFile(fileBean, transcodingReqDTO);
            } catch (Exception ex) {
                log.error("格式转换:"+ex.getMessage());
                return CommonResult.error("格式转换失败");
            }
        }
        return CommonResult.ok("格式转换成功");
    }

    public void saveResourceFile(ResourceFile fileBean, TranscodingReqDTO transcodingReqDTO) {
        ResourceFile newFile = new ResourceFile();
        newFile.setFileId(fileBean.getFileId());
        newFile.setPreviewFileUrl("converted/" + fileBean.getFileId() + "." + transcodingReqDTO.getFormat());
        resourceFileMapper.updateById(newFile);
    }


    /**
     * 封装参数，存储进数据库
     */
    public void saveFile(UserFile userFile, FileBean fileBean, String userId, TranscodingReqDTO transcodingReqDTO) {
        FileBean newFile = new FileBean();
        newFile.setFileId(IdUtil.simpleUUID());
        newFile.setFileUrl("converted/" + fileBean.getFileId() + "." + transcodingReqDTO.getFormat());
        newFile.setCreateUserId(userId);
        newFile.setFileSize(videoConverter.getConverterFileSize("converted/" + fileBean.getFileId() + "." + transcodingReqDTO.getFormat()));
        newFile.setFileStatus(1);
        newFile.setIdentifier(fileBean.getIdentifier());
        newFile.setStorageType(3);
        newFile.setCreateTime(DateUtil.getCurrentTime());
        fileMapper.insert(newFile);
        UserFile newUserFile = new UserFile();
        newUserFile.setUserFileId(IdUtil.simpleUUID());
        newUserFile.setCreateUserId(userId);
        newUserFile.setDeleteFlag(0);
        newUserFile.setExtendName(transcodingReqDTO.getFormat());
        newUserFile.setFileId(newFile.getFileId());
        newUserFile.setFileName(userFile.getFileName());
        newUserFile.setFilePath(userFile.getFilePath());
        newUserFile.setIsDir(userFile.getIsDir());
        newUserFile.setUserId(userId);
        newUserFile.setCreateTime(DateUtil.getCurrentTime());
        newUserFile.setUploadTime(DateUtil.getCurrentTime());
        userFileMapper.insert(newUserFile);
    }



}
