package com.fdkankan.manage.service.impl;

import cn.hutool.core.date.DateUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fdkankan.common.util.DateExtUtil;
import com.fdkankan.manage.service.IExcelService;
import com.fdkankan.manage.service.IInvoiceService;
import com.fdkankan.manage.vo.InvoicePageParamVO;
import com.fdkankan.manage.vo.InvoiceVO;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Calendar;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * TODO
 * </p>
 *
 * @author dengsixing
 * @since 2022/6/6
 **/
@Service
public class ExcelServiceImpl implements IExcelService {

    @Autowired
    private IInvoiceService invoiceService;

    @Override
    public void exportInvoice(HttpServletRequest request, HttpServletResponse response, InvoicePageParamVO param)
        throws IOException {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = "开票申请数据" + DateUtil.format(Calendar.getInstance().getTime(), DateExtUtil.dateStyle6) + ".xlsx";
        fileName = URLEncoder.encode(fileName, "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName);
        try (ExcelWriter excelWriter = EasyExcel.write(response.getOutputStream(), InvoiceVO.class).build()) {
            // 这里注意 如果同一个sheet只要创建一次
            WriteSheet writeSheet = EasyExcel.writerSheet("开票申请数据").build();
            // 去调用写入,这里我调用了五次，实际使用时根据数据库分页的总的页数来
            int pageNum = 1;
            param.setPageSize(5000);
            Page<InvoiceVO> invoiceVOPage;
            do {
                param.setPageNum(pageNum);
                invoiceVOPage = invoiceService.pageInvoice(param);
                excelWriter.write(invoiceVOPage.getRecords(), writeSheet);
                ++pageNum;

            }while (invoiceVOPage.hasNext());
        }
    }
}
