package com.patzn.lims.excel.controller;

import com.patzn.cloud.commons.api.RestAssert;
import com.patzn.lims.core.web.ServiceController;
import com.patzn.poibox.excel.ExcelHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * Excel 相关控制器
 * </p>
 *
 * @author wwd
 * @since 2020-03-20
 */
@Api(description = "Excel 相关操作")
@RestController
@RequestMapping("/v1/excel")
public class ExcelController  {

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private HttpServletResponse response;

    private static final Map<String, String> TPL = new HashMap<>();
    static {
        ExcelController.TPL.put("DrugAptitudeImport", "资质项目导入模板");
    }

    @ApiOperation(value = "根据模板名称下载模板", notes = "根据模板名称下载导入模板")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "模板名称", required = true, paramType = "path", dataType = "String"),
    })
    @GetMapping("/template/{name}")
    public void template(@PathVariable("name") String name) {
        RestAssert.fail(null == ExcelController.TPL.get(name), "导入模板不存请联系管理员");
        try {
            // 文件路径
            String filePath = String.format("templates/excel/input/%s.xlsx", name);
            // 兼容打包 JAR 压缩情况处理
            ExcelHelper.excelTemplateDownload(response, ExcelController.TPL.get(name), getClass().getClassLoader().getResourceAsStream(filePath));
        } catch (Throwable t) {
            RestAssert.fail("该模板不存在");
        }
    }

}
