package com.winsun.service.impl;

import com.winsun.bean.ExportExcel;
import com.winsun.service.ExportExcelService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.text.SimpleDateFormat;

/**
 * @author liph
 * @date 2020/10/19 09:36
 */
@Service
@Slf4j
public class ExportExcelServiceImpl implements ExportExcelService {
    @Override
    public void uploadExcel(ExportExcel exportExcel, HttpServletResponse response) {
        FileInputStream fileInputStream = null;
        DataInputStream in = null;
        ServletOutputStream os = null;
        try {
            os = response.getOutputStream();
            SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
            String formatPath = format.format(exportExcel.getCreateTime());
            StringBuilder filePath = new StringBuilder();
            filePath.append("enclosure").append(File.separator).append("export").append(File.separator)
                    .append(formatPath).append(File.separator).append("订单")
                    .append(exportExcel.getCreateTime().getTime()).append(".xls");
            fileInputStream = new FileInputStream(new File(filePath.toString()));
            in = new DataInputStream(fileInputStream);
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = in.read(bufferOut)) != -1) {
                os.write(bufferOut, 0, bytes);
            }
            os.flush();
        } catch (Exception e) {
            log.error("下载excel文件异常" + e.getMessage(), e);
        } finally {
            if(fileInputStream != null) {
                try {
                    fileInputStream.close();
                } catch (Exception e){

                }
            }
            if(in != null) {
                try {
                    in.close();
                } catch (Exception e){

                }
            }
        }
    }
}
