package org.springblade.flow.datalog.controller;

import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.http.HttpServletResponse;

import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.tool.api.R;
import org.springblade.flow.datalog.model.DataImportLog;
import org.springblade.flow.datalog.service.DataImportLogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 
 * @author William
 * @date 2022年12月2日 下午4:34:46
 */
@RestController
@RequestMapping("/paas/visualdev/data/import")
@Api(tags = "AA表单数据导入记录接口", value = "DataImportLog")
public class DataImportLogController {

	@Value("${blade.file.uploadPath}")
	private String uploadDir;

	@Autowired
	private DataImportLogService importLogService;

	@GetMapping("/list")
	@ApiOperation(value = "分页查询")
	public R<IPage<DataImportLog>> list(String modelId, Integer current, Integer size) {
		LambdaQueryWrapper<DataImportLog> wrapper = Wrappers.<DataImportLog>lambdaQuery();
		wrapper.eq(DataImportLog::getModelId, modelId);
		wrapper.orderByDesc(DataImportLog::getId);
		Query query = new Query();
		query.setCurrent(current);
		query.setSize(size);
		return R.data(importLogService.page(Condition.getPage(query), wrapper));
	}

	@PostMapping("/download")
	@ApiOperation(value = "下载当时导入的Excel文件")
	public void download(Long id, HttpServletResponse response) throws IORuntimeException, IOException {
		DataImportLog dataLog = importLogService.getById(id);
		String filePath = uploadDir + dataLog.getFilePath().replace("uploads/", "");
		File file = new File(filePath);
		if (file != null && file.exists() && file.isFile()) {
			response.setContentType("application/vnd.ms-excel");
			response.setCharacterEncoding("utf-8");
			String fileName = URLEncoder.encode(dataLog.getName(), "UTF-8");
			response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
			response.getOutputStream().write(FileUtil.readBytes(file));
			response.getOutputStream().flush();
		}
	}
}
