package com.xxfc.platform.vehicle.rest.admin;

import cn.hutool.core.io.IoUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.github.wxiaoqi.security.admin.feign.UserFeign;
import com.github.wxiaoqi.security.admin.feign.dto.UserDTO;
import com.github.wxiaoqi.security.auth.client.config.UserAuthConfig;
import com.github.wxiaoqi.security.common.exception.BaseException;
import com.xxfc.platform.vehicle.biz.VehicleBiz;
import com.xxfc.platform.vehicle.biz.VehicleInformationDownloadBiz;
import com.xxfc.platform.vehicle.common.BaseController;
import com.xxfc.platform.vehicle.pojo.VehicleExcelVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.util.List;


@RestController
@RequestMapping("VehicleInformationDownload")
@Slf4j
public class VehicleInformationDownloadController extends BaseController<VehicleInformationDownloadBiz> {

    @Autowired
    UserFeign userFeign;

    @Autowired
    private UserAuthConfig userAuthConfig;

    @Autowired
    private VehicleBiz vehicleBiz;

    @Autowired
    HttpServletResponse response;

    @GetMapping("/excel")
    public void downloadExcel(@RequestParam(value = "vehiclePageQueryVoJson",required = false) String vehiclePageQueryVoJson) throws Exception {
        UserDTO userDTO = userFeign.userinfoByToken(userAuthConfig.getToken(request)).getData();
        if (userDTO==null) {
            throw  new BaseException("token已失效");
        }
        List<VehicleExcelVo> rows = baseBiz.getList(vehiclePageQueryVoJson, userDTO);
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.addHeaderAlias("numberPlate", "车牌号");
        writer.addHeaderAlias("code", "车辆编码");
        writer.addHeaderAlias("vehicleType", "车型");
        writer.addHeaderAlias("useTypeName", "用途");
        writer.addHeaderAlias("parkBranchCompanyName", "停靠分公司");
        // 一次性写出内容，使用默认样式，强制输出标题
        writer.write(rows, true);
        //response为HttpServletResponse对象
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        //test.xls是弹出下载对话框的文件名，不能为中文，中文请自行编码
        response.setHeader("Content-Disposition", "attachment;filename=clxx.xlsx");
        //out为OutputStream，需要写出到的目标流
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        // 关闭writer，释放内存
        writer.close();
        //此处记得关闭输出Servlet流
        IoUtil.close(out);
    }
}
