package com.bonus.sgzb.system.controller;

import com.bonus.sgzb.common.core.web.domain.AjaxResult;
import com.bonus.sgzb.system.config.ErrorCode;
import com.bonus.sgzb.system.domain.FileInfo;
import com.bonus.sgzb.system.service.SysFileService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.util.IOUtils;
import org.springframework.core.io.ResourceLoader;
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 javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;

/**
 * @author bns
 */
@Slf4j
@RestController
@RequestMapping("/sys/file")
public class SysFileController {

    @Resource
    private SysFileService service;

    public final static List<String> ATTACHMENT_FILE_SUFFIX = Arrays.asList("doc","txt","docx","pdf","rft","rar","xlsx","xls");

    public final static List<String> COST_FILE_SUFFIX = Arrays.asList("jpg", "png", "pdf");

    @Resource
    private ResourceLoader resourceLoader;


    @PostMapping("/upload")
    @ApiOperation(value = "文件上传")
    public AjaxResult upload(HttpServletRequest request) {
        String limitWords = request.getParameter("limitWords");
        FileInfo file = new FileInfo();
        try {
            file = service.uploadFile(request);
           // String suffix = file.getFileName().substring(file.getFileName().lastIndexOf(".") + 1);

          /*  if (! ATTACHMENT_FILE_SUFFIX.contains(suffix) || ! COST_FILE_SUFFIX.contains(suffix)) {
                return AjaxResult.error(ErrorCode.COMMISSION_BILL_ATTACHMENT_NOT_SUPPORT.getCode(),
                        ErrorCode.COMMISSION_BILL_ATTACHMENT_NOT_SUPPORT.getMessage());
            }*/
            if (limitWords != null && file.getWords() > Integer.parseInt(limitWords)){
                return AjaxResult.error(ErrorCode.ATTACHMENT_UPLOAD_FAILED.getCode(),
                        ErrorCode.ATTACHMENT_UPLOAD_FAILED.getMessage());
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        if (file != null && file.getId() != 0){
            return AjaxResult.success(file);
        }else {
            return AjaxResult.error(ErrorCode.FAILURE_TO_UPLOAD_FILE.getCode(),
                    ErrorCode.FAILURE_TO_UPLOAD_FILE.getMessage());
        }

    }

    @ApiOperation(value = "模板", httpMethod = "GET")
    @GetMapping("download")
    public void download(HttpServletRequest request, HttpServletResponse response, String filename) {
        InputStream inputStream = null;
        ServletOutputStream servletOutputStream = null;
        try {
            String path = "download/" + filename;
            org.springframework.core.io.Resource resource = resourceLoader.getResource("classpath:" + path);
            response.setContentType("application/vnd.ms-excel");
            response.addHeader("Cache-Control", "no-cache, no-store, must-revalidate");
            response.addHeader("charset", "utf-8");
            response.addHeader("Pragma", "no-cache");
            String encodeName = URLEncoder.encode(filename, StandardCharsets.UTF_8.toString());
            response.setHeader("Content-Disposition", "attachment; filename=\"" + encodeName + "\"; filename*=utf-8''" + encodeName);

            inputStream = resource.getInputStream();
            servletOutputStream = response.getOutputStream();
            IOUtils.copy(inputStream, servletOutputStream);
            response.flushBuffer();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (servletOutputStream != null) {
                    servletOutputStream.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
                // 召唤jvm的垃圾回收器
                System.gc();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

}
