package com.zksy.commonFile.service.impl;

import com.zksy.common.core.domain.AjaxResult;
import com.zksy.common.exception.ServiceException;
import com.zksy.commonFile.service.ManageCommonService;
import com.zksy.system.basicData.domain.CrmFile;
import com.zksy.system.basicData.mapper.CrmFileMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author sy
 * @date 2022/4/1 17:01
 */
@Slf4j
@Service
public class ManageCommonServiceImpl implements ManageCommonService {

    @Value("${local.fileserver.filetypes}")
    private String allowFileTypes;

    @Value("${local.fileserver.upload.path}")
    private String localFileServerUploadDir;

    @Value("${local.fileserver.baseurl}")
    private String localFileServerBaseUrl;

    @Value("${local.fileserver.mapping.path}")
    private String localFileServerMappingPath;

    @Autowired
    private CrmFileMapper mapper;

    @Override
    public AjaxResult uploadFile(MultipartFile multipartFile, Long fid, String moduleName) {
        try {
            // 获取文件名
            String fileOriginalName = multipartFile.getOriginalFilename();
            //获取文件大小
            Long fileSize = multipartFile.getSize();
            String fileName = UUID.randomUUID().toString() + fileOriginalName.substring(fileOriginalName.lastIndexOf("."), fileOriginalName.length());

            log.info("（加个时间戳，尽量避免文件名称重复）保存的文件名为: " + fileName + "\n");
            //加个时间戳，尽量避免文件名称重复
            String path = localFileServerUploadDir + fileName;
            //文件绝对路径
            log.info("保存文件绝对路径" + path + "\n");
            //创建文件路径
            File dest = new File(path);
            //判断文件是否已经存在
            if (dest.exists()) {
                return AjaxResult.error("文件已存在");
            }
            //判断文件父目录是否存在
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdir();
            }
            //上传文件
            multipartFile.transferTo(dest); //保存文件
            log.info("保存文件路径" + path + "\n");
            //url="http://你自己的域名/项目名/images/"+fileName;//正式项目
//            String url = localFileServerBaseUrl + serverContextPath + localFileServerMappingPath +"/" + fileName;
            String url = localFileServerMappingPath + "/" + fileName;

            //log.info("保存的完整url====" + url + "\n");
            CrmFile uploadRes = new CrmFile();
            uploadRes.setFid(fid);
            uploadRes.setFileOriginalName(fileOriginalName);
            uploadRes.setFileUrl(url);
            uploadRes.setFileName(fileName);
            uploadRes.setFileSize(fileSize);
            uploadRes.setCreateTime(new Date());
            uploadRes.setCreateBy("管理员");
            uploadRes.setModuleName(moduleName);
            mapper.insert(uploadRes);
            return AjaxResult.success("文件上传成功",uploadRes);
        } catch (IOException e) {
            log.error("文件上传异常!");
            log.error(ExceptionUtils.getStackTrace(e));
            return AjaxResult.error("文件上传失败");
        }
    }

    @Override
    public String uploadFilePath(MultipartFile multipartFile) {
        String url = "";
        try {
            // 获取文件名
            String fileOriginalName = multipartFile.getOriginalFilename();
            //获取文件大小
            Long fileSize = multipartFile.getSize();
            String fileName = UUID.randomUUID().toString() + fileOriginalName.substring(fileOriginalName.lastIndexOf("."), fileOriginalName.length());

            log.info("（加个时间戳，尽量避免文件名称重复）保存的文件名为: " + fileName + "\n");
            //加个时间戳，尽量避免文件名称重复
            String path = localFileServerUploadDir + fileName;
            //文件绝对路径
            log.info("保存文件绝对路径" + path + "\n");
            //创建文件路径
            File dest = new File(path);
            //判断文件是否已经存在
            if (dest.exists()) {
                throw new ServiceException("文件已存在");
            }
            //判断文件父目录是否存在
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdir();
            }
            //上传文件
            multipartFile.transferTo(dest); //保存文件
            log.info("保存文件路径" + path + "\n");
            //url="http://你自己的域名/项目名/images/"+fileName;//正式项目
//            String url = localFileServerBaseUrl + serverContextPath + localFileServerMappingPath +"/" + fileName;
            url = localFileServerMappingPath + "/" + fileName;

        }catch (IOException e){
            log.error("文件上传异常!");
            log.error(ExceptionUtils.getStackTrace(e));
        }
        return url;
    }

    @Override
    public AjaxResult uploadListFile(List<MultipartFile> multipartFiles, Long fid, String moduleName) {
        try {
            List<CrmFile> crmFileList = new ArrayList<>();
            if (multipartFiles.size() > 0) {
                for (MultipartFile multipartFile : multipartFiles) {
                    // 获取文件名
                    String fileOriginalName = multipartFile.getOriginalFilename();
                    //获取文件大小
                    Long fileSize = multipartFile.getSize();
                    String fileName = UUID.randomUUID().toString() + fileOriginalName.substring(fileOriginalName.lastIndexOf("."), fileOriginalName.length());

                    log.info("（加个时间戳，尽量避免文件名称重复）保存的文件名为: " + fileName + "\n");
                    //加个时间戳，尽量避免文件名称重复
                    String path = localFileServerUploadDir + fileName;
                    //文件绝对路径
                    log.info("保存文件绝对路径" + path + "\n");
                    //创建文件路径
                    File dest = new File(path);
                    //判断文件是否已经存在
                    if (dest.exists()) {
                        return AjaxResult.error("文件已存在");
                    }
                    //判断文件父目录是否存在
                    if (!dest.getParentFile().exists()) {
                        dest.getParentFile().mkdir();
                    }
                    //上传文件
                    multipartFile.transferTo(dest); //保存文件
                    log.info("保存文件路径" + path + "\n");
                    //url="http://你自己的域名/项目名/images/"+fileName;//正式项目
//            String url = localFileServerBaseUrl + serverContextPath + localFileServerMappingPath +"/" + fileName;
                    String url = localFileServerMappingPath + "/" + fileName;

                    //log.info("保存的完整url====" + url + "\n");
                    CrmFile uploadRes = new CrmFile();
                    uploadRes.setFid(fid);
                    uploadRes.setFileOriginalName(fileOriginalName);
                    uploadRes.setFileUrl(url);
                    uploadRes.setFileName(fileName);
                    uploadRes.setFileSize(fileSize);
                    uploadRes.setCreateTime(new Date());
                    uploadRes.setCreateBy("管理员");
                    uploadRes.setModuleName(moduleName);
                    mapper.insert(uploadRes);
                    crmFileList.add(uploadRes);
                }
                return AjaxResult.success("文件上传成功",crmFileList);
            } else {
                return AjaxResult.error("无文件上传");
            }
        }catch (IOException e) {
            log.error("文件上传异常!");
            log.error(ExceptionUtils.getStackTrace(e));
            return AjaxResult.error("文件上传异常");
        }
    }

    @Override
    public AjaxResult deleteFile(String id) {
        CrmFile fileUpload = mapper.selectById(id);
        String filePath = localFileServerUploadDir+fileUpload.getFileName();
        File file = new File(filePath);
        if (file.exists()) {
            boolean isDeleted = file.delete();
            if (isDeleted) {
                //删除数据库信息
                mapper.deleteById(id);
                return AjaxResult.success("文件已成功删除");
            } else {
                return AjaxResult.error("无法删除该文件");
            }
        } else {
            return AjaxResult.error("指定的文件不存在");
        }
    }
}
