package com.ebts.system.service.impl;

import com.ebts.common.constant.ReturnConstants;
import com.ebts.common.core.entity.Result;
import com.ebts.common.core.entity.entity.Role;
import com.ebts.common.core.entity.model.LoginUser;
import com.ebts.common.utils.SecurityUtils;
import com.ebts.system.dao.FileDao;
import com.ebts.system.entity.SysFile;
import com.ebts.system.service.FileService;
import com.ebts.system.utils.FtpUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 文件信息Service业务层处理
 *
 * @author binlin
 * @date 2021-02-17
 */
@Service
public class FileServiceImpl implements FileService {
    private Logger logger = LoggerFactory.getLogger(FileServiceImpl.class);

    @Resource
    private FileDao fileDao;


    /**
     * 查询文件信息
     *
     * @param fileId 文件信息ID
     * @return 文件信息
     */
    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public Result<SysFile> selectFileById(Long fileId) {
        SysFile sysFile = fileDao.selectFileById(fileId);
        if (sysFile != null) {
            return Result.ok(sysFile);
        } else {
            return Result.info(ReturnConstants.RESULT_EMPTY);
        }
    }

    /**
     * 查询文件信息列表
     *
     * @param sysFile 文件信息
     * @return 文件信息
     */
    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public Result<List<SysFile>> selectFileList(SysFile sysFile) {
        List<SysFile> sysFileList = fileDao.selectFileList(sysFile);
        if (sysFileList.size() > 0) {
            return Result.ok(sysFileList);
        } else {
            return Result.info(ReturnConstants.RESULT_EMPTY);
        }
    }

    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public Result<List<SysFile>> selectFileFolder() {
        List<SysFile> sysFiles = fileDao.selectFileFolder();
        return Result.ok(sysFiles);
    }

    /**
     * 新增文件信息
     *
     * @param sysFile 文件信息
     * @return 结果
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public Result<SysFile> insertFile(SysFile sysFile) {
        if (sysFile == null) {
            return Result.error("文件上传失败!");
        }
        if (sysFile.getpId() != null) {
            if (sysFile.getpId() > 0) {
                SysFile folder = fileDao.selectFileById(sysFile.getpId());
                sysFile.setInherit(folder.getRoleIds());
            }
        }
        sysFile.setCreateBy(SecurityUtils.getUserId());
        try {
            sysFile = FtpUtils.uploadFtp(sysFile);
        } catch (RuntimeException e) {
            logger.error(e.getMessage());
            return Result.error("文件处理出错,请重新上传文件!");
        }
        fileDao.insertFile(sysFile);
        return Result.ok(sysFile);
    }

    /**
     * 修改文件信息
     *
     * @param sysFile 文件信息
     * @return 结果
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public Result<Integer> updateFile(SysFile sysFile) {
        if (sysFile.getIsPublic().equals("1")) {
            return Result.error("此文件不可修改!");
        }
        if (sysFile.getpId() != null || sysFile.getpId() > 0) {
            SysFile folder = fileDao.selectFileById(sysFile.getpId());
            sysFile.setInherit(folder.getRoleIds());
        }
        sysFile.setUpdateBy(SecurityUtils.getUserId());
        fileDao.updateFile(sysFile);
        return Result.ok();
    }

    /**
     * 批量删除文件信息
     *
     * @param fileIds 需要删除的文件信息ID
     * @return 结果
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public Result<Integer> deleteFileByIds(Long[] fileIds) {
        List<SysFile> sysFiles = new ArrayList<>();
        SysFile sysFile = null;
        for (Long fileId : fileIds) {
            sysFile = fileDao.selectFileById(fileId);
            sysFiles.add(sysFile);
        }
        if (!FtpUtils.deleteFile(sysFiles)) {
            return Result.error(ReturnConstants.OP_ERROR);
        }
        fileDao.deleteFileByIds(fileIds);
        return Result.ok();
    }

    /**
     * 下载文件
     *
     * @param fileId
     * @param loginUser
     * @return
     */
    @Override
    @Transactional(propagation = Propagation.SUPPORTS)
    public Result<SysFile> downloadFile(Long fileId, LoginUser loginUser) {
        SysFile sysFile = fileDao.selectFileById(fileId);
        if (sysFile.getIsPublic().equals("2")) {
            if (loginUser == null) {
                return Result.error("请登录后再试!");
            } else {
                if (!loginUser.getUser().isAdmin()) {
                    String roleid;
                    if (sysFile.getpId() != 0) {
                        roleid = sysFile.getInherit() + "," + sysFile.getRoleIds();
                    } else {
                        roleid = sysFile.getRoleIds();
                    }
                    String[] roleIds = roleid.split(",");
                    boolean start = true;
                    for (Role role : loginUser.getUser().getRoles()) {
                        for (String roleId : roleIds) {
                            if (String.valueOf(role.getRoleId()).equals(roleId)) {
                                start = false;
                                break;
                            }
                        }
                        if (!start) {
                            break;
                        }
                    }
                    if (start) {
                        return Result.error("您没有下载该文件的权限!");
                    }
                }
            }
        }
        String fileName = FtpUtils.downloadFile(sysFile);
        if (fileName == null) {
            return Result.error("文件下载失败!");
        } else {
            return Result.ok(sysFile);
        }
    }

    /**
     * 删除文件信息信息
     *
     * @param fileId 文件信息ID
     * @return 结果
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED,rollbackFor = Exception.class)
    public Result<Integer> deleteFileById(Long fileId) {
        fileDao.deleteFileById(fileId);
        return Result.ok(ReturnConstants.SYS_FAILL);
    }

}
