package com.securitycontrol.system.base.controller;

import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import cn.afterturn.easypoi.excel.entity.enmus.ExcelType;
import com.securitycontrol.common.log.annotation.Log;
import com.securitycontrol.common.log.enums.OperationType;
import com.securitycontrol.entity.system.base.dto.ProDto;
import com.securitycontrol.system.export.entity.ProExportVo;
import com.securitycontrol.entity.system.base.vo.ProVo;
import com.securitycontrol.system.base.service.IProService;
import com.securitycontrol.common.core.utils.ExcelStyleUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;


/**
 * @author：cwchen
 * @date：2024-03-11-14:55
 * @version：1.0
 * @description：导出文件-web层
 */
@RestController
@RequestMapping("/sys/export/")
@Slf4j
public class ExportFileController {

    @Resource(name = "IProService")
    private IProService service;

    @GetMapping("exportProData")
    @Log(title = "基础管理", menu = "基础管理->工程管理", grade = OperationType.EXPORT_BUSINESS, details = "导出工程", type = "业务日志")
    public void exportData(HttpServletRequest request, HttpServletResponse response, ProDto dto) {
        try {
            List<ProExportVo> proExportVoList = new ArrayList<>();
            List<ProVo> proLists = service.getProLists(dto);
            for (int i = 0; i < proLists.size(); i++) {
                proLists.get(i).setProId((i + 1) + "");
                ProExportVo exportVo = new ProExportVo();
                BeanUtils.copyProperties(proLists.get(i), exportVo);
                proExportVoList.add(exportVo);
            }
            ExportParams exportParams = new ExportParams("工程列表", "工程列表", ExcelType.XSSF);
            exportParams.setStyle(ExcelStyleUtil.class);
            Workbook workbook = ExcelExportUtil.exportExcel(exportParams, ProExportVo.class, proExportVoList);
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setHeader("content-disposition", "attachment;fileName=" + URLEncoder.encode("工程列表" + ".xlsx", "UTF-8"));
            ServletOutputStream outputStream = response.getOutputStream();
            workbook.write(outputStream);
            outputStream.close();
            workbook.close();
        } catch (Exception e) {
            log.error("导出工程", e);
        }
    }
}
