package com.tykj.dev.device.file.Controller;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfWriter;
import com.tykj.dev.config.swagger.AutoDocument;
import com.tykj.dev.device.file.entity.FileRet;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.MultipartRequest;
import com.itextpdf.text.Rectangle;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.UUID;

/**
 * @author zjm
 * @version 1.0.0
 * @ClassName FileController.java
 * @Description TODO
 * @createTime 2020年08月03日 18:05:00
 */
@RestController
@AutoDocument
@Api(tags = "文件模块", description = "提供文件相关的接口")
@Slf4j
public class FileController {
    @Value("${file.path}")
    public String url;
    @Value("${preview.path}")
    public String preview;
    /**
     * 文件上传
     */
    @PostMapping("/upload")
    public ResponseEntity<FileRet> upload(HttpServletRequest request){
        MultipartRequest multiRequest = (MultipartRequest)request;
        MultipartFile file = multiRequest.getFile("file");
        String originalFilename = file.getOriginalFilename();
        System.out.println(originalFilename);
       File file1= new File(url);
        if (!file1.exists()){
            file1.mkdirs();
        }
        FileOutputStream fos = null;
        InputStream inputStream = null;
        OutputStream os = null;

        String[] split = originalFilename.split("\\.");
        String newName=UUID.randomUUID().toString()+"."+split[split.length-1];
            byte[] typeByte = new byte[1024*1024*10];
            try {
                inputStream = file.getInputStream();
                fos = new FileOutputStream(url+newName);
                int i = 0;
                while((i=inputStream.read(typeByte))!=-1){
                    fos.write(typeByte,0,i);
                }
                fos.flush();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if(inputStream!=null){
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    inputStream = null;
                }
            }

            if(fos!=null){
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    fos = null;
                }
            }

            if(os!=null){
                try {
                    os.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }finally {
                    os = null;
                }
            }


        return  ResponseEntity.ok(new FileRet(originalFilename,url+newName,preview+newName));
    }


    /**
     * 文件下载
     */
    @PostMapping("/download")
    public void download(@RequestParam(value = "url")  String url, @RequestParam(value = "name") String name, HttpServletResponse response, HttpServletRequest httpServletRequest){
        String fileName = name;
        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/octet-stream");
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "utf-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        setFileDownloadHeader(httpServletRequest, response, fileName);
        OutputStream os = null;
        InputStream is = null;
        BufferedInputStream bs = null;
        byte[] buffer = new byte[1024];
        try {
            is = new FileInputStream(new File(url));
            bs = new BufferedInputStream(is);
            os = response.getOutputStream();
            int i = bs.read(buffer);
            while (i != -1) {
                os.write(buffer, 0, i);
                i = bs.read(buffer);
            }
            os.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bs.close();
                is.close();
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @PostMapping("/print/pdf")
    public ResponseEntity<FileRet> fileUpload(HttpServletRequest request) throws IOException, DocumentException {

        List<MultipartFile> multipartFiles = ((MultipartHttpServletRequest)request).getFiles("file");
        System.out.println("数据条数"+multipartFiles.size());
        File file1 = new File(url+"print/");
        if (!file1.exists()){
            file1.mkdirs();
        }
        String fileName = UUID.randomUUID().toString()+".pdf";
        File file = new File(url+"print/"+fileName);

        // 第一步：创建一个document对象。
        Document document = new Document();
        document.setMargins(0, 0, 0, 0);
        // 第二步：
        // 创建一个PdfWriter实例，
        PdfWriter.getInstance(document, new FileOutputStream(file));
        // 第三步：打开文档。
        document.open();
        for(MultipartFile multipartFile:multipartFiles){
            Image img = Image.getInstance(multipartFile.getBytes());
            //转成
//                    Image.byte()
            //多文件上传 图片专程byte 2进制
            img.setAlignment(Image.ALIGN_CENTER);
            // 根据图片大小设置页面，一定要先设置页面，再newPage（），否则无效
            document.setPageSize(new Rectangle(img.getWidth(), img.getHeight()));
            document.newPage();
            document.add(img);

        }
        document.close();
        return ResponseEntity.ok(new FileRet("",url+"print/"+fileName+fileName,preview+"print/"+fileName));
    }

    /**
     * 解决中文名称
     */
    private void setFileDownloadHeader(HttpServletRequest request, HttpServletResponse response, String fileName) {
        try {
            //中文文件名支持
            String encodedfileName;
            String agent = request.getHeader("USER-AGENT");
            if (null != agent && agent.contains("MSIE")) {//IE
                encodedfileName = java.net.URLEncoder.encode(fileName, "UTF-8");
            } else if (null != agent && agent.contains("Mozilla")) {
                encodedfileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
            } else {
                encodedfileName = java.net.URLEncoder.encode(fileName, "UTF-8");
            }
            response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedfileName + "\"");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }
}
