package me.zhengjie.modules.dm.video.service.impl;

import cn.hutool.core.util.ObjectUtil;
import lombok.RequiredArgsConstructor;
import me.zhengjie.config.FileProperties;
import me.zhengjie.domain.LocalStorage;
import me.zhengjie.exception.BadRequestException;
import me.zhengjie.modules.dm.video.domain.DmVideo;
import me.zhengjie.modules.dm.video.repository.DmVideoRepository;
import me.zhengjie.modules.dm.video.service.DmVideoService;
import me.zhengjie.modules.dm.video.service.dto.DmVideoDto;
import me.zhengjie.modules.dm.video.service.dto.DmVideoQueryCriteria;
import me.zhengjie.modules.dm.video.service.mapstruct.DmVideoMapper;
import me.zhengjie.utils.FileUtil;
import me.zhengjie.utils.PageUtil;
import me.zhengjie.utils.QueryHelp;
import me.zhengjie.utils.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.List;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class DmVideoServiceImpl implements DmVideoService {
    private final DmVideoRepository dmVideoRepository;
    private final DmVideoMapper dmVideoMapper;
    private final FileProperties properties;

    @Override
    public Map<String, Object> queryAll(DmVideoQueryCriteria criteria, Pageable pageable) {
        Page<DmVideo> page = dmVideoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        return PageUtil.toPage(page.map(dmVideoMapper::toDto));
    }

    @Override
    public List<DmVideoDto> queryAll(DmVideoQueryCriteria criteria) {
        return dmVideoMapper.toDto(dmVideoRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public DmVideo create(String name, MultipartFile multipartFile) {
        FileUtil.checkSize(properties.getMaxSize(), multipartFile.getSize());
        String suffix = FileUtil.getExtensionName(multipartFile.getOriginalFilename());
        String type = FileUtil.getFileType(suffix);
        File file = FileUtil.upload(multipartFile, properties.getPath().getPath() + type +  File.separator);
        if(ObjectUtil.isNull(file)){
            throw new BadRequestException("上传失败");
        }
        try {
            name = StringUtils.isBlank(name) ? FileUtil.getFileNameNoEx(multipartFile.getOriginalFilename()) : name;
            String path = type+"/"+file.getName();
            DmVideo dmVideo = new DmVideo(
                    path
            );
            return dmVideoRepository.save(dmVideo);
        }catch (Exception e){
            FileUtil.del(file);
            throw e;
        }
    }
}
