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.net.URLEncoder;
import java.nio.charset.StandardCharsets;
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,String docModel) throws IOException {
        Map<String, Object> params = new HashMap<>();
        // 渲染文本

        params.put("time",wrodParameter.getTime());
        //装备类型总数
        params.put("deviceNumber",wrodParameter.getDeviceNumber());
        //入库数量
        params.put("inLibraryNum",wrodParameter.getInLibraryNum());
        //维修数量
        params.put("sendRepairNum",wrodParameter.getSendRepairNum());
        //维修退回
        params.put("receiveRepairNum",wrodParameter.getReceiveRepairNum());
        //销毁数量
        params.put("destoryNum",wrodParameter.getDestoryNum());
        //发起配发数量
        params.put("sendAllotNum",wrodParameter.getSendAllotNum());
        //接收配发数量
        params.put("receiveAllotNum",wrodParameter.getReceiveAllotNum());
        //发起退回数量
        params.put("sensAllotBackNum",wrodParameter.getSensAllotBackNum());
        //接收退回
        params.put("receiveAllotBackNum",wrodParameter.getReceiveAllotBackNum());
        //清退数量
        params.put("sendBackNum",wrodParameter.getSendBackNum());
        //报废数量
        params.put("scrapStatisticsNum",wrodParameter.getScrapStatisticsNum());
        //列装数量
        params.put("packingNum",wrodParameter.getPackingNum());
        //退装数量
        params.put("retiredNum",wrodParameter.getRetiredNum());
        //退役
        params.put("decommissioningStatisticsNum",wrodParameter.getDecommissioningStatisticsNum());
        //向下级进行维修退回
        params.put("toRepairBackNum",wrodParameter.getToRepairBackNum());
        //接收下级进行维修
        params.put("toRepairNum",wrodParameter.getToRepairNum());

        params.put("TitleAnnual",wrodParameter.getTitleAnnual());
        params.put("TitleTimeEnd",wrodParameter.getTitleTimeEnd());
        params.put("TitleTimeStart",wrodParameter.getTitleTimeStart());
        params.put("TitleUnitName",wrodParameter.getTitleUnitName());
        String fileName = wrodParameter.getTitleTimeStart()+"至"+wrodParameter.getTitleTimeEnd()+"使用报告" + ".doc";
        String templatePath = ResourceUtils.getURL(  "classpath:").getPath()+"docTemplate/"+docModel;
        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) {
//        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();
//            }
//        }

        if(name != null){
            response.setHeader("content-type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            try {
                response.setHeader("Content-Disposition", "attachment;filename="+new String(name.getBytes("utf-8"),"utf-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            File file = new File(url);
            long fileLength = file.length();
            response.setHeader("Content-Length", fileLength + "");
            //如果文件存在，返回文件，文件不存在，返回文件不存在提示
            if(fileLength != 0 ){
                setFileDownloadHeader(httpServletRequest,response,name);
                OutputStream os = null;
                InputStream is = null;
                BufferedInputStream bs = null;
                byte[] buffer = new byte[1024];
                try {
                    is = new FileInputStream(file);
                    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) {
                    log.error(file.getAbsolutePath() + "文件不存在");

                } catch (IOException e) {
                    //log.error(file.getAbsolutePath() + "文件读取异常");
                    log.error(file.getAbsolutePath() + "文件用户终止下载");
                } finally {
                    try {
                        bs.close();
                        is.close();
                        os.close();
                    } catch (IOException e) {
                        log.error("用户终止下载");
                        //e.printStackTrace();
                    }
                }
            }else {
                log.info(url + "该文件不存在");
            }
        }else {
            log.error("请求的文件名为空");
        }

    }




        /**
         * 解决中文名称
         */
       private void setFileDownloadHeader(HttpServletRequest request, HttpServletResponse response, String fileName) {
        try {
            //中文文件名支持
            String encodedfileName;
            String agent = request.getHeader("USER-AGENT");
            log.info("浏览器名称:{}",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"), "ISO8859-1");
                encodedfileName= new String(fileName.getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
                log.info("进入-Mozilla");
            } else if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) {
                encodedfileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1"); // firefox浏览器
            } else if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
                encodedfileName = URLEncoder.encode(fileName, "UTF-8");// IE浏览器
            } else if (request.getHeader("User-Agent").toUpperCase().indexOf("CHROME") > 0) {
                encodedfileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");// 谷歌
            } else {
                encodedfileName = java.net.URLEncoder.encode(fileName, "UTF-8");
                log.info("[file_name] 未匹配到浏览器，使用默认方法命名文件名");
            }
            response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedfileName + "\"");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }


    }


