package com.bs.web.controller.common;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.bs.cm.domain.CmAttach;
import com.bs.cm.service.ICmAttachService;
import com.bs.common.config.BsConfig;
import com.bs.common.constant.Constants;
import com.bs.common.core.domain.AjaxResult;
import com.bs.common.exception.ServiceException;
import com.bs.common.utils.FileUtil;
import com.bs.common.utils.StringUtils;
import com.bs.common.utils.file.FileUploadUtils;
import com.bs.common.utils.file.FileUtils;
import com.bs.framework.config.ServerConfig;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 通用请求处理
 *
 * @author bs
 */
@RestController
@RequestMapping("/common")
@Api(tags = "文件上传")
public class CommonController {
    private static final Logger log = LoggerFactory.getLogger(CommonController.class);

    @Autowired
    private ServerConfig serverConfig;

    @Autowired
    private ICmAttachService cmAttachService;

    private static final String FILE_DELIMETER = ",";

    /**
     * 通用下载请求
     *
     * @param fileName 文件名称
     * @param delete   是否删除
     */
    @GetMapping("/download")
    @ApiOperation("文件下载")
    public void fileDownload(String fileName, Boolean delete, HttpServletResponse response, HttpServletRequest request) {
        try {
            if (!FileUtils.checkAllowDownload(fileName)) {
                throw new Exception(StringUtils.format("文件名称({})非法，不允许下载。 ", fileName));
            }
            String realFileName = System.currentTimeMillis() + fileName.substring(fileName.indexOf("_") + 1);
            String filePath = BsConfig.getDownloadPath() + fileName;

            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, realFileName);
            FileUtils.writeBytes(filePath, response.getOutputStream());
            if (delete) {
                FileUtils.deleteFile(filePath);
            }
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }


    @ApiOperation("根据attachId下载对应文件")
    @GetMapping("/fileDownloadById")
    public void fileDownloadById(String attachId,HttpServletResponse response, HttpServletRequest request) {
        if (StringUtils.isBlank(attachId) || "null".equals(attachId)) {
            throw new ServiceException("附件ID不能为空");
        }
        CmAttach cmAttach = cmAttachService.getById(attachId);
        String path =cmAttach.getAttachFileUrl();
        path =BsConfig.getFilePath()+path;
//        Constants.RESOURCE_PREFIX
        path = path.replace(Constants.RESOURCE_PREFIX, "");
        File compressedImageFile = new File(path);
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        FileUtil.downloadFile(request, response, compressedImageFile, false);
    }



    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload")
    @ApiOperation("单文件上传")
    public AjaxResult uploadFile(MultipartFile file,String fileId) throws Exception {
        try {
            // 上传文件路径
            String filePath = BsConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = serverConfig.getUrl() + fileName;
            String newFileName = FileUtils.getName(fileName);
            String originalFilename = file.getOriginalFilename();
            CmAttach cmAttach = new CmAttach();
            cmAttach.setFileId(fileId);
            cmAttach.setFileSort(1);
            cmAttach.setAttachName(newFileName);
            cmAttach.setAttachContentType(file.getContentType());
            cmAttach.setAttachFileSize(file.getSize());
            String suffix = FileUtil.getExtensionName(originalFilename);
            String type = FileUtil.getFileType(suffix);
            cmAttach.setAttachFileType(type);
            cmAttach.setAttachFileUrl(fileName);
            cmAttach.setOldName(originalFilename);
            cmAttach.setVersionNo("1");
            cmAttach.setRemark("");
            cmAttachService.save(cmAttach);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", newFileName);
            ajax.put("cmAttach", cmAttach);
            ajax.put("originalFilename", originalFilename);
            return ajax;
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 通用上传请求（多个）
     */
    @PostMapping("/uploads")
    @ApiOperation("多文件上传")
    public AjaxResult uploadFiles(List<MultipartFile> files, String fileId) throws Exception {
        try {
            // 上传文件路径
            String filePath = BsConfig.getUploadPath();
            List<String> urls = new ArrayList<String>();
            List<String> fileNames = new ArrayList<String>();
            List<String> newFileNames = new ArrayList<String>();
            List<String> originalFilenames = new ArrayList<String>();
            List<CmAttach> cmAttachList = new ArrayList<>();
            for (MultipartFile file : files) {
                // 上传并返回新文件名称
                String fileName = FileUploadUtils.upload(filePath, file);
                String url = serverConfig.getUrl() + fileName;
                urls.add(url);
                fileNames.add(fileName);
                String newFileName = FileUtils.getName(fileName);
                newFileNames.add(newFileName);
                String originalFilename = file.getOriginalFilename();
                originalFilenames.add(originalFilename);
                CmAttach cmAttach = new CmAttach();
                cmAttach.setFileId(fileId);
                cmAttach.setFileSort(1);
                cmAttach.setAttachName(newFileName);
                cmAttach.setAttachContentType(file.getContentType());
                cmAttach.setAttachFileSize(file.getSize());
                String suffix = FileUtil.getExtensionName(originalFilename);
                String type = FileUtil.getFileType(suffix);
                cmAttach.setAttachFileType(type);
                cmAttach.setAttachFileUrl(fileName);
                cmAttach.setOldName(originalFilename);
                cmAttach.setVersionNo("1");
                cmAttach.setRemark("");
                cmAttachList.add(cmAttach);
            }
            cmAttachService.saveBatch(cmAttachList);
            AjaxResult ajax = AjaxResult.success();
            ajax.put("urls", StringUtils.join(urls, FILE_DELIMETER));
            ajax.put("fileNames", StringUtils.join(fileNames, FILE_DELIMETER));
            ajax.put("newFileNames", StringUtils.join(newFileNames, FILE_DELIMETER));
            ajax.put("originalFilenames", StringUtils.join(originalFilenames, FILE_DELIMETER));
            return ajax;
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 上查询文件列表
     * @param fileId
     * @param type
     * @return
     */
    @ApiOperation("根据fileId查找附件列表")
    @GetMapping(value = "/getAttachList/{fileId}")
    public AjaxResult getAttachVo(@PathVariable String fileId, String type) {
        if (org.apache.commons.lang3.StringUtils.isBlank(fileId) || "null".equals(fileId)) {
            return AjaxResult.error("fileId不能为空");
        } else if ("undefined".equals(fileId)) {
            return AjaxResult.success();
        }
        List<CmAttach> attachVo = cmAttachService.list(new LambdaQueryWrapper<CmAttach>().eq(CmAttach::getFileId,fileId));
        //压缩图片
        return AjaxResult.success(attachVo);
    }

    /**
     * 根据fileIds查找附件列表
     * @param fileIds
     * @return
     */
    @ApiOperation("根据fileIds查找附件列表")
    @GetMapping(value = "/getFileIdsByAttachVos")
    public AjaxResult getFileIdsByAttachVos(String[] fileIds) {
        LambdaQueryWrapper<CmAttach> refWrapper = new LambdaQueryWrapper();
        if (null != fileIds && fileIds.length > 0) {
            refWrapper.in(CmAttach::getFileId, fileIds);
            List<CmAttach> refs = cmAttachService.list(refWrapper);
            //通过fileId进行分组
            Map<String, List<CmAttach>> attachVoMap = refs.stream().collect(Collectors.groupingBy(CmAttach::getFileId));
            return AjaxResult.success(attachVoMap);
        } else {
            return AjaxResult.warn("请输入文件fileIds!");
        }
    }


    @ApiOperation("根据fileId删除表及对应文件")
    @DeleteMapping(value = "/deleteFileByFileId/{fileId}")
    public AjaxResult deleteFileByFileId(@PathVariable String fileId) {
        if (org.apache.commons.lang3.StringUtils.isBlank(fileId) || "null".equals(fileId)) {
            return AjaxResult.error("fileId不能为空");
        }
        List<CmAttach> cmAttachs = cmAttachService.list(new LambdaQueryWrapper<CmAttach>().eq(CmAttach::getFileId,fileId));
        cmAttachs.forEach(cmAttach->{
            String path =cmAttach.getAttachFileUrl();
        /*    path = path.replace(Constants.RESOURCE_PREFIX, "");
            path = path.replace(cmAttach.getAttachName(), "");
            path =BsConfig.getFilePath()+path+"xt_"+cmAttach.getAttachName();*/
            path =BsConfig.getFilePath()+path;
            File compressedImageFile = new File(path);
            if (compressedImageFile.exists()) {
                FileUtil.del(compressedImageFile);
            }
        });
        cmAttachService.remove(new LambdaQueryWrapper<CmAttach>().eq(CmAttach::getFileId,fileId));
        return AjaxResult.success();
    }


    @ApiOperation("根据attachId删除表及对应文件")
    @DeleteMapping(value = "/deleteFile/{attachId}")
    public AjaxResult deleteFile(@PathVariable Long attachId) {
        if (attachId==null) {
            return AjaxResult.error("attachId不能为空");
        }
        CmAttach cmAttach = cmAttachService.getById(attachId);
        String path =cmAttach.getAttachFileUrl();
        path =BsConfig.getFilePath()+path;
        File compressedImageFile = new File(path);
        if (compressedImageFile.exists()) {
            FileUtil.del(compressedImageFile);
        }
        cmAttachService.removeById(attachId);
        return AjaxResult.success();
    }


    /**
     * 本地资源通用下载
     */
    @GetMapping("/download/resource")
    public void resourceDownload(String resource, HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        try {
            if (!FileUtils.checkAllowDownload(resource)) {
                throw new Exception(StringUtils.format("资源文件({})非法，不允许下载。 ", resource));
            }
            // 本地资源路径
            String localPath = BsConfig.getProfile();
            // 数据库资源地址
            String downloadPath = localPath + StringUtils.substringAfter(resource, Constants.RESOURCE_PREFIX);
            // 下载名称
            String downloadName = StringUtils.substringAfterLast(downloadPath, "/");
            response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
            FileUtils.setAttachmentResponseHeader(response, downloadName);
            FileUtils.writeBytes(downloadPath, response.getOutputStream());
        } catch (Exception e) {
            log.error("下载文件失败", e);
        }
    }
}
