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 {

    public static String EXPORT = "/springboot/school_center/task/";
    @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());
            File file = new File(ExportExcelServiceImpl.EXPORT + exportExcel.getExportUrl());
            fileInputStream = new FileInputStream(file);
            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){
                    e.printStackTrace();
                }
            }
            if(in != null) {
                try {
                    in.close();
                } catch (Exception e){

                }
            }
        }
    }
}
