package com.yeejoin.equipmanage.controller;

import com.yeejoin.equipmanage.common.entity.publics.CommonResponse;
import com.yeejoin.equipmanage.common.entity.vo.AppDownloadVO;
import com.yeejoin.equipmanage.common.utils.ExcelUtil;
import com.yeejoin.equipmanage.common.utils.FileUploadTypeEnum;
import com.yeejoin.equipmanage.service.IDownloadFileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;

import javax.servlet.http.HttpServletResponse;
import java.util.Optional;

@Api(basePath = "/file-download", value = "文件操作API", description = "处理模版下载")
@RestController
@RequestMapping("/file-download")
public class DownloadController extends AbstractBaseController {

	@Autowired
	@Lazy
	private IDownloadFileService iDownloadFileService;

	/**
	 * <pre>
	 * excel模版下载
	 * </pre>
	 *
	 * @param type     模板类型 {@link FileUploadTypeEnum}
	 * @param response {@link HttpServletResponse}
	 * @return CommonResponse
	 * @throws @version: 1.0
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET", value = "excel模版下载(<font color='blue'>release</font>)", notes = "excel模版下载")
	@RequestMapping(value = "/download-xls", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	public CommonResponse downloadXML(@ApiParam(value = "模板类型", required = true) @RequestParam String type,
			HttpServletResponse response) {

		try {
			String speciesType = Optional.ofNullable(type).orElseThrow(NullPointerException::new);
			String fileName = FileUploadTypeEnum.getName(type) + "导入参考模版.xls";
			HSSFWorkbook workbook = iDownloadFileService.DownloadFile(speciesType);
			ExcelUtil.exportExcel(response, workbook, fileName);

			return new CommonResponse(SUCCESS, "模版下载完成");
		} catch (Exception e) {
			e.printStackTrace();
			return new CommonResponse(FAILED);
		}
	}

	/**
	 * <pre>
	 * app离线模式数据下载
	 * </pre>
	 * 
	 * @return AppDownloadVO
	 */
	@TycloudOperation(ApiLevel = UserType.AGENCY)
	@ApiOperation(httpMethod = "GET", value = "app离线模式数据下载", notes = "app离线模式数据下载")
	@GetMapping(value = "/appDownloadDatas")
	public AppDownloadVO appDownloadDatas() {
		return iDownloadFileService.appDownloadDatas();
	}
}
