package cn.wise.sc.cement.business.controller;

import cn.wise.sc.cement.business.enumation.FileExt;
import cn.wise.sc.cement.business.model.BaseResponse;
import cn.wise.sc.cement.business.model.LoginUser;
import cn.wise.sc.cement.business.service.ISysUserService;
import cn.wise.sc.cement.business.util.dfs.FastDFSUtils;
import cn.wise.sc.cement.business.util.dfs.FileTypeUtil;
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.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 sun.misc.BASE64Encoder;

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
 */
@Api(tags = "附件管理")
@RestController
@RequestMapping("/enclosure")
public class EntityEnclosureController {

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

    @Autowired
    protected HttpServletResponse response;
    @Autowired
    protected HttpServletRequest request;
    @Autowired
    private ISysUserService userService;

    @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 {
            LoginUser loginUser = userService.getLoginUser();
            if (loginUser != null) {
                filePath = FastDFSUtils.uploadPic(file.getBytes(), file.getOriginalFilename(), file.getSize());
                fileName = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."));
                extName = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            } else {
                return BaseResponse.errorMsg("登录信息失效");
            }
            if (extName.contains(FileExt.EXCL.getName()) || extName.contains(FileExt.EXCLX.getName())) {
                String pdfPath = FastDFSUtils.conventAndUpload(file.getInputStream(), fileName);
                map.put("pdfPath", pdfPath);
            } else {
                map.put("pdfPath", filePath);
            }
            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("/imgUpLoad")
    public BaseResponse imgUpLoad(MultipartFile file) {
        Map<String, Object> map = new HashMap<>();
        String filePath = null;
        String fileName = null;
        String extName = null;
        try {
            LoginUser loginUser = userService.getLoginUser();
            if (loginUser != null) {
                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("."));
            } else {
                return BaseResponse.errorMsg("登录信息失效");
            }
            String picUrl = filePath;
            map.put("fileUrl", picUrl);
            map.put("fileName", fileName);
            map.put("extName", extName);
            map.put("pdfPath", filePath);
            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");
            LoginUser loginUser = userService.getLoginUser();
            if (loginUser != null) {
                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);
                        if (extName.contains(FileExt.EXCL.getName()) || extName.contains(FileExt.EXCLX.getName())) {
                            String pdfPath = FastDFSUtils.conventAndUpload(file.getInputStream(), fileName);
                            mapSub.put("pdfPath", pdfPath);
                        } else {
                            mapSub.put("pdfPath", filePath);
                        }
                        filePathList.add(mapSub);
                    }
                } else {
                    return BaseResponse.errorMsg("没有文件");
                }
            } 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();
            LoginUser loginUser = userService.getLoginUser();
            if (loginUser != null) {
                fileUrl = fileUrl.substring(fileUrl.indexOf("g"));
                byte[] by = FastDFSUtils.fileDownload(fileUrl);
                out.write(by);
                out.close();
//	            BASE64Encoder encoder = new BASE64Encoder();
//	            String data = encoder.encode(by);
//	            return BaseResponse.okMsg(data);
            } else {
                return BaseResponse.errorMsg("登录信息失效");
            }
            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 {
            LoginUser loginUser = userService.getLoginUser();

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

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

}
