package com.xinelu.manage.controller.importdownload;

import com.xinelu.common.constant.Constants;
import com.xinelu.common.exception.ServiceException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import java.io.File;
import java.io.IOException;
import java.util.Objects;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * 导入与下载Controller
 *
 * @author zh
 * @date 2024-02-26
 */

@Api(tags = "导入与下载控制器")
@RestController
@RequestMapping("/system/importDownload")
public class ImportDownloadController {

    /**
     * 下载导入模板
     *
     * @param fileType 文件类型
     * @param res      http请求
     **/
    @ApiOperation(value = "下载导入模板", notes = "fileType:agency:机构信息模板,department:科室信息模板,"
	    + "outpatient:门诊患者模板,prehospitalized:预住院患者模板,inhospital:在院患者模板，discharged：出院患者模板")
    @RequestMapping("downloadTemplate")
    public void download(@RequestParam(value = "fileType") String fileType, HttpServletResponse res) throws IOException {
        if (StringUtils.isBlank(fileType)) {
            throw new ServiceException("请选择文件类型！");
        }
        File file = null;
		//本地服务使用 classpath:template
		switch (fileType) {
			case Constants.AGENCY:
				file = ResourceUtils.getFile("template/机构信息导入表.xlsx");
				break;
			case Constants.DEPARTMENT:
				file = ResourceUtils.getFile("template/科室信息导入表.xlsx");
				break;
			case Constants.PRE_HOSPITALIZED: // 预住院患者
				file = ResourceUtils.getFile("template/预住院患者信息导入表.xlsx");
				break;
			case Constants.IN_HOSPITAL: // 在院患者
				file = ResourceUtils.getFile("template/在院患者信息导入表.xlsx");
				break;
			case Constants.DISCHARGED: // 出院患者
				file = ResourceUtils.getFile("template/出院患者信息导入表.xlsx");
				break;
			case Constants.OUTPATIENT: // 门诊患者
				file = ResourceUtils.getFile("template/门诊患者信息导入表.xlsx");
				break;
			case Constants.PATIENT_INFO_IMPORT: // 门诊患者
				file = ResourceUtils.getFile("template/OutpatientFollowUpRecords.xlsx");
				break;
			case Constants.BATCH_SEND_TASK_INFO:
				file = ResourceUtils.getFile("template/批量推送人员信息表.xlsx");
				break;
		}
        if (Objects.isNull(file)) {
            throw new ServiceException("下载导入模板文件失败，请联系管理员！");
        }
        res.setCharacterEncoding("UTF-8");
        res.setHeader("Content-Disposition", "inline;filename=" + fileType + ".txt");
        res.setContentType("text/plain;UTF-8");
        ServletOutputStream os = res.getOutputStream();
        byte[] bytes = FileUtils.readFileToByteArray(file);
        os.write(bytes);
        os.flush();
        os.close();
    }
}