package org.nl.system.service.tools.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.nl.common.domain.query.PageQuery;
import org.nl.config.FileProperties;
import org.nl.common.exception.BadRequestException;
import org.nl.common.utils.FileUtil;
import org.nl.common.utils.SecurityUtils;
import org.nl.system.service.tools.dao.ToolLocalStorage;
import org.nl.system.service.tools.dao.mapper.ToolLocalStorageMapper;
import org.nl.system.service.tools.IToolLocalStorageService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.nl.system.service.tools.dto.ToolLocalStorageQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Set;

/**
 * <p>
 * 本地存储表 服务实现类
 * </p>
 *
 * @author generator
 * @since 2022-12-20
 */
@Service
public class ToolLocalStorageServiceImpl extends ServiceImpl<ToolLocalStorageMapper, ToolLocalStorage> implements IToolLocalStorageService {

    @Autowired
    private FileProperties properties;
    @Autowired
    private ToolLocalStorageMapper localStorageMapper;

    @Override
    public IPage<ToolLocalStorage> queryAll(ToolLocalStorageQuery criteria, PageQuery pageable) {
        return this.page(pageable.build(ToolLocalStorage.class), criteria.build());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Object 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 {
            String userId = SecurityUtils.getCurrentUserId();
            String nickName = SecurityUtils.getCurrentNickName();
            String now = DateUtil.now();
            name = StrUtil.isEmpty(name) ? FileUtil.getFileNameNoEx(multipartFile.getOriginalFilename()) : name;
            ToolLocalStorage localStorage = new ToolLocalStorage();
            localStorage.setStorage_id(IdUtil.getSnowflake(1,1).nextIdStr());
            localStorage.setReal_name(file.getName());
            localStorage.setName(name);
            localStorage.setSuffix(suffix);
            localStorage.setPath(file.getPath());
            localStorage.setType(type);
            localStorage.setSize(FileUtil.getSize(multipartFile.getSize()));
            localStorage.setCreate_id(userId);
            localStorage.setCreate_name(nickName);
            localStorage.setCreate_time(now);
            localStorage.setUpdate_id(userId);
            localStorage.setUpdate_name(nickName);
            localStorage.setUpdate_time(now);
            localStorageMapper.insert(localStorage);
            return localStorage;
        }catch (Exception e){
            FileUtil.del(file);
            throw e;
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(ToolLocalStorage resources) {
        ToolLocalStorage storage = localStorageMapper.selectById(resources.getStorage_id());
        if (ObjectUtil.isEmpty(storage)) throw new BadRequestException("文件信息不存在");
        resources.setUpdate_id(SecurityUtils.getCurrentUserId());
        resources.setUpdate_name(SecurityUtils.getCurrentNickName());
        resources.setUpdate_time(DateUtil.now());
        localStorageMapper.updateById(resources);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteAll(Set<String> ids) {
        ids.forEach(id -> {
            ToolLocalStorage localStorage = localStorageMapper.selectById(id);
            if (ObjectUtil.isNotEmpty(localStorage)) {
                FileUtil.del(localStorage.getPath());
                localStorageMapper.deleteById(localStorage);
            }
        });
    }
}
