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.DataExportTask;
import org.springblade.flow.datalog.service.DataExportTaskService;
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/export")
@Api(tags = "AA表单数据导出任务接口", value = "DataExportTaskLog")
public class DataExportTaskController {

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

	@Autowired
	private DataExportTaskService exportTaskService;

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

	@PostMapping("/download")
	@ApiOperation(value = "下载Excel文件")
	public void download(Long id, HttpServletResponse response) throws IORuntimeException, IOException {
		DataExportTask task = exportTaskService.getById(id);
		File file = new File(formDir + task.getFileName());
		if (file != null && file.exists() && file.isFile()) {
			response.setContentType("application/vnd.ms-excel");
			response.setCharacterEncoding("utf-8");
			String fileName = URLEncoder.encode(task.getName(), "UTF-8");
			response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
			response.getOutputStream().write(FileUtil.readBytes(file));
			response.getOutputStream().flush();
		}
	}
}
