package com.ningdatech.carapi.sys.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.ningdatech.basic.util.SpringUtils;
import com.ningdatech.carapi.sys.entity.constant.ImportTemplateConstant;
import com.ningdatech.carapi.sys.entity.enumeration.ImportTemplateEnum;
import com.ningdatech.carapi.sys.event.ImportDataEvent;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.List;

/**
 * <p>
 * ImportTemplateDownController
 * </p>
 *
 * @author WendyYang
 * @since 16:50 2022/10/15
 */
@RestController
@Api(tags = "导入模版下载")
@RequestMapping("/api/v1/importTemplate")
public class ImportTemplateDownController {

    @GetMapping("/down/{template}")
    @ApiOperation("导入模板下载")
    public void down(@PathVariable ImportTemplateEnum template, HttpServletResponse response) throws IOException {
        ExcelWriter writer = ExcelUtil.getWriter();
        List<String> colList = ImportTemplateConstant.getTemplateTitle(template);
        writer.writeHeadRow(colList);
        writer.getStyleSet().setBorder(BorderStyle.NONE, IndexedColors.AUTOMATIC);
        CellStyle cellStyle = writer.getHeadCellStyle();
        cellStyle.setFillForegroundColor(IndexedColors.LIGHT_GREEN.getIndex());
        cellStyle.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        String fileName = URLEncoder.encode(template.getValue() + "模板", CharsetUtil.UTF_8);
        response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + fileName + ".xls");
        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        writer.close();
        IoUtil.close(out);
    }

    @PostMapping("/import")
    @ApiOperation("通用导入数据")
    public void importData(@RequestParam ImportTemplateEnum template, MultipartFile file) throws IOException {
        ImportDataEvent event = new ImportDataEvent(file);
        event.setTemplate(template);
        SpringUtils.publishEvent(event);
    }

}
