package com.tykj.dev.device.file.service.Impl;

import com.tykj.dev.device.file.entity.WrodParameter;
import com.tykj.dev.device.file.service.UseReportFIleService;
import com.tykj.dev.device.file.util.WordUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ResourceUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author zjm
 * @version 1.0.0
 * @ClassName UseReportFIleServiceImpl.java
 * @Description TODO
 * @createTime 2020年09月15日 19:33:00
 */
@Service
@Slf4j
public class UseReportFIleServiceImpl implements UseReportFIleService {
    @Value("${file.path}")
    public String url;
    @Value("${preview.path}")
    public String preview;

    @Override
    public void findToFileService(WrodParameter wrodParameter, HttpServletResponse response, HttpServletRequest httpServletRequest) throws IOException {
        Map<String, Object> params = new HashMap<>();
        // 渲染文本
        params.put("time",wrodParameter.getTime());
        params.put("total",wrodParameter.getTotal());
        params.put("BackPackNum",wrodParameter.getBackPackNum());
        params.put("DestructionNum",wrodParameter.getDestructionNum());
        params.put("FieldingNum",wrodParameter.getFieldingNum());

        params.put("MaintenanceNum",wrodParameter.getMaintenanceNum());
        params.put("RepelNum",wrodParameter.getRepelNum());
        params.put("StorageNum",wrodParameter.getStorageNum());
        params.put("TitleAnnual",wrodParameter.getTitleAnnual());
        params.put("TitleTimeEnd",wrodParameter.getTitleTimeEnd());
        params.put("TitleTimeStart",wrodParameter.getTitleTimeStart());
        params.put("TitleUnitName",wrodParameter.getTitleUnitName());
        params.put("WithNum",wrodParameter.getWithNum());
        String fileName = wrodParameter.getTitleTimeStart()+"至"+wrodParameter.getTitleTimeEnd()+"使用报告" + ".doc";
        String templatePath = ResourceUtils.getURL(  "classpath:").getPath()+"docxModel.docx";
        url=url+"report/";
        String uuidName=UUID.randomUUID().toString().replace("-", "") + ".doc";
       String fileUrl= WordUtil.createWord(templatePath,url,uuidName,params);

        response.setContentType("application/x-download");
        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(fileUrl));
            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 {
                if (bs != null) {
                    bs.close();
                }
                if (is != null) {
                    is.close();
                }
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    @Override
    public void download(String url, String name, HttpServletResponse response, HttpServletRequest httpServletRequest) {
        String fileName = name;
//        response.setHeader("content-type", "application/octet-stream");
        response.setContentType("application/x-download");
        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 {
                if (bs!=null) {
                    bs.close();
                }
                if (is != null) {
                    is.close();
                }
                if (os != null) {
                    os.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 解决中文名称
     */
    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();
        }
    }

}
