package cn.wise.sc.energy.power.plant.business.controller;


import cn.wise.sc.energy.power.plant.business.utils.dfs.FastDFSUtils;
import cn.wise.sc.energy.power.plant.business.utils.dfs.FileTypeUtil;
import cn.wise.sc.energy.power.plant.common.core.bean.BaseResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 附件管理Controller
 *
 * @author ztw
 */
@CrossOrigin
@RestController
@RequestMapping("/enclosure")
public class EntityEnclosureController {

    private static final Logger logger = LoggerFactory.getLogger("adminLogger");

    @Autowired
    protected HttpServletResponse response;
    @Autowired
    protected HttpServletRequest request;


    //@ApiOperation(value = "单个文件上传")
    @PostMapping("/fileUpLoad")
    public BaseResponse fileUpLoad(MultipartFile file) {
        Map<String, Object> map = new HashMap<>();
        String filePath = null;
        String fileName = null;
        String extName = null;
        try {
            filePath = FastDFSUtils.uploadPic(file.getBytes(), file.getOriginalFilename(), file.getSize());
            fileName = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."));
            extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

            String picUrl = filePath;
            map.put("fileUrl", picUrl);
            map.put("extName", extName);
            map.put("fileName", fileName);
            if (!extName.equals(".pdf")) {
                String pdfPath = FastDFSUtils.conventAndUpload(file.getInputStream(), fileName);
                map.put("pdfPath", pdfPath);
            } else {
                map.put("pdfPath", filePath);
            }
            return BaseResponse.okData(map);
        } catch (Exception e) {
            logger.error(e.toString());
        }
        return BaseResponse.errorMsg("失败");
    }

    //@ApiOperation(value = "单个图片上传")
    @PostMapping("/imgUpLoad")
    public BaseResponse imgUpLoad(MultipartFile file) {
        Map<String, Object> map = new HashMap<>();
        String filePath = null;
        String fileName = null;
        String extName = null;
        try {

            if (!FileTypeUtil.isImageByExtension(file.getOriginalFilename())) {
                return BaseResponse.errorMsg("请上传有效图片");
            }
            filePath = FastDFSUtils.uploadPic(file.getBytes(), file.getOriginalFilename(), file.getSize());
            fileName = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."));
            extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

            String picUrl = filePath;
            map.put("fileUrl", picUrl);
            map.put("fileName", fileName);
            map.put("extName", extName);

            return BaseResponse.okData(map);
        } catch (Exception e) {
            logger.error(e.toString());
        }
        return BaseResponse.errorMsg("失败");
    }


    //@ApiOperation(value = "多个文件上传")
    @PostMapping("/filesUpLoad")
    public BaseResponse filesUpLoad(HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        List<MultipartFile> files = null;
        String filePath = null;
        String fileName = null;
        String extName = null;
        List<Map<String, Object>> filePathList = null;
        try {
            filePathList = new ArrayList<>();
            files = ((MultipartHttpServletRequest) request).getFiles("files");

            if (files != null && files.size() > 0) {
                for (MultipartFile file : files) {
                    Map<String, Object> mapSub = new HashMap<>();
                    filePath = FastDFSUtils.uploadPic(file.getBytes(), file.getOriginalFilename(), file.getSize());
                    fileName = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."));
                    extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
                    String picUrl = filePath;
                    mapSub.put("fileUrl", picUrl);
                    mapSub.put("fileName", fileName);
                    mapSub.put("extName", extName);
                    filePathList.add(mapSub);
                }
            } else {
                return BaseResponse.errorMsg("没有文件");
            }

            return BaseResponse.okData(map);
        } catch (Exception e) {
            logger.error(e.toString());
        }
        return BaseResponse.errorMsg("失败");
    }

    //@ApiOperation(value = "单个文件下载")
    @PostMapping("/fileDownload")
    public BaseResponse fileDownload(String fileUrl, String fileName, String extName) {
        OutputStream out = null;
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + fileName + extName);
            response.setContentType("application/force-download");
            out = response.getOutputStream();

            fileUrl = fileUrl.substring(fileUrl.indexOf("g"));
            byte[] by = FastDFSUtils.fileDownload(fileUrl);
            out.write(by);
            out.close();

            return BaseResponse.okMsg("成功");
        } catch (Exception e) {
            logger.error(e.toString());
        }
        return BaseResponse.errorMsg("失败");
    }

    //@ApiOperation(value = "app扫描二维码下载")
    @GetMapping("/appDownload")
    public BaseResponse appDownload(String fileUrl) {
        Map<String, Object> map = new HashMap<>();
        OutputStream out = null;
        try {
            response.setHeader("Content-Disposition", "attachment;filename=app-release.apk");
            response.setContentType("application/force-download");
            out = response.getOutputStream();
            fileUrl = fileUrl.substring(fileUrl.indexOf("g"));
            byte[] by = FastDFSUtils.fileDownload(fileUrl);
            out.write(by);
            out.close();
            return BaseResponse.okMsg("成功");

        } catch (Exception e) {
            logger.error(e.toString());
        }
        return BaseResponse.errorMsg("失败");
    }


    //@ApiOperation(value = "删除相关文件")
    @PostMapping("/fileDeleted")
    public BaseResponse fileDeleted(String[] filePaths) {
        Map<String, Object> map = new HashMap<>();
        String filePath = null;
        boolean rel = false;
        try {

            for (String url : filePaths) {
                /*filePath = url.substring(0,url.indexOf("g"));*/
                rel = FastDFSUtils.deletePic(url);
                if (!rel) {
                    return BaseResponse.errorMsg("删除失败");
                }
            }


            return BaseResponse.okMsg("成功");
        } catch (Exception e) {
            logger.error(e.toString());
        }
        return BaseResponse.errorMsg("失败");
    }


}
