package com.casic.missiles.controller.system;


import cn.afterturn.easypoi.entity.ImageEntity;
import com.casic.missiles.service.listeners.register.FilePrintRegisterUtils;
import com.casic.missiles.utils.PdfUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.stereotype.Controller;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

@Api(tags = "文档格式转换接口")
@Controller
@RequestMapping("/poi")
public class PoiController {

    private String filepath="C:\\upload";

    @ApiOperation("word转pdf")
    @PostMapping(value = "/convertWordToPdf1")
    @ResponseBody
    public void convertWordToPdf1() throws Exception {
        File uploadFile = new File(filepath);
        String wordDir = "";
        if (!uploadFile.exists()) {
            uploadFile.mkdirs();
        }
        if (!filepath.endsWith("/")) {
            wordDir = filepath + File.separator + "word";
        }
        File tf = new File(wordDir + File.separator + "ttt.docx");
//        File tf_pic = new File(wordDir + File.separator + "logo.jpg");
//        String pic_url = tf_pic.getCanonicalPath();
        Calendar now = Calendar.getInstance();
        Map<String, Object> params = new HashMap<>();
        List<Map<String,Object>> dataList=new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            Map<String, Object> param = new HashMap<>();
            param.put("assetName", "彭于晏"+i);
            param.put("assetModel", "男"+i);
            param.put("assetNo", "中国"+i);
            param.put("validDate", "中国"+i);
//            ImageEntity image = new ImageEntity();
//            image.setHeight(100);
//            image.setWidth(100);
//            image.setUrl(pic_url);
//            image.setData(PdfUtil.getImageBase64(pic_url));
//            param.put("image", image);
            dataList.add(param);
        }

        params.put("assetList",dataList);
        params.put("y", now.get(Calendar.YEAR));
        params.put("m", (now.get(Calendar.MONTH) + 1));
        params.put("d", now.get(Calendar.DAY_OF_MONTH));

        String fileName = "tttt1.docx";
        String word = FilePrintRegisterUtils.exportWord(tf.getPath(), wordDir, fileName, params);
        System.out.println("****新模板"+word);

    }

    @ApiOperation("word转pdf")
    @PostMapping(value = "/convertWordToPdf")
    @ResponseBody
    public void convertWordToPdf(HttpServletResponse response) throws Exception {
        File uploadFile = new File(filepath);
        String wordDir = "";
        String pdfDir = "";
        if (!uploadFile.exists()) {
            uploadFile.mkdirs();
        }
        if (!filepath.endsWith("/")) {
            wordDir = filepath + File.separator + "word";
            pdfDir = filepath + File.separator + "pdf";
        }
        File tf = new File(wordDir + File.separator + "tem.docx");
        File tf_pic = new File(wordDir + File.separator + "logo.jpg");
        String pic_url = tf_pic.getCanonicalPath();
        Calendar now = Calendar.getInstance();
        Map<String, Object> params = new HashMap<>();
        List<Map<String,Object>> dataList=new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            Map<String, Object> param = new HashMap<>();
            param.put("name", "彭于晏"+i);
            param.put("sex", "男"+i);
            param.put("address", "中国"+i);
            ImageEntity image = new ImageEntity();
            image.setHeight(100);
            image.setWidth(100);
            image.setUrl(pic_url);
            image.setData(PdfUtil.getImageBase64(pic_url));
            param.put("image", image);
            dataList.add(param);
        }

        params.put("dataList",dataList);
        params.put("y", now.get(Calendar.YEAR));
        params.put("m", (now.get(Calendar.MONTH) + 1));
        params.put("d", now.get(Calendar.DAY_OF_MONTH));

        String fileName = "wordExport.docx";
        String word = PdfUtil.exportWord(tf.getPath(), wordDir, fileName, params);
        String pdfFileName = "convertDocx2Pdf.pdf";
        String downloadFile = "pdf导出.pdf";

        if (word.equals("")) {
            Assert.notNull(word, "word路径不能为空");
        } else {
            PdfUtil.convertDocx2Pdf(word, pdfDir + File.separator + pdfFileName);
            response.setContentType("application/force-download");// 设置强制下载不打开
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + URLEncoder.encode(downloadFile, "UTF-8"));  //中文名称下载
            byte[] buffer = new byte[1024];
            FileInputStream fis = null;
            BufferedInputStream bis = null;
            OutputStream outputStream = null;
            try {
                fis = new FileInputStream(pdfDir + File.separator + pdfFileName);
                bis = new BufferedInputStream(fis);
                outputStream = response.getOutputStream();
                int i = bis.read(buffer);
                while (i != -1) {
                    outputStream.write(buffer, 0, i);
                    i = bis.read(buffer);
                }
                outputStream.flush();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (outputStream != null) {
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    File file = new File(pdfDir);
                    if (file != null && file.isFile() && file.exists()) {
                        file.delete();
                    }
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }



    @ApiOperation("test")
    @PostMapping(value = "/testPrint")
    @ResponseBody
    public void testPrint() throws Exception {
        FilePrintRegisterUtils.docToDocx("C:\\upload\\word\\test-report.doc","C:\\upload\\word\\test-report.docx");

        File tf = new File("C:\\upload\\word\\test-report.docx");
        Calendar now = Calendar.getInstance();
        Map<String, Object> params = new HashMap<>();
        params.put("customerName","张三");
        params.put("customerAddress","北京");
        params.put("sampleNo","10001000");
        params.put("sampleName","样品001");
        params.put("manufacturingNo","样品001");
        params.put("y", now.get(Calendar.YEAR));
        params.put("m", (now.get(Calendar.MONTH) + 1));
        params.put("d", now.get(Calendar.DAY_OF_MONTH));

        String fileName = "testParams.docx";
        String word = FilePrintRegisterUtils.exportWord(tf.getPath(), "C:\\upload\\word\\", fileName, params);
        System.out.println("****新模板"+word);

    }

}
