/**
 * Copyright 2019 DH
 * All right reserved.
 * 项目名称: 大恒泰山系统
 * 创建日期:2022/8/31
 */
package org.springblade.modules.manage.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.read.listener.ReadListener;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.github.xiaoymin.knife4j.annotations.ApiOperationSupport;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springblade.core.boot.ctrl.BladeController;
import org.springblade.core.log.annotation.ApiLog;
import org.springblade.core.mp.support.Condition;
import org.springblade.core.mp.support.Query;
import org.springblade.core.oss.model.BladeFile;
import org.springblade.core.tool.api.R;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.baseinfo.project.service.IProjectBaseInfoService;
import org.springblade.modules.baseinfo.rtu.service.IRtuBaseInfoService;
import org.springblade.modules.baseinfo.stbase.service.IMvAttStBaseService;
import org.springblade.modules.manage.dto.RtuImportRecordDTO;
import org.springblade.modules.manage.entity.RtuImportRecordDetailEntity;
import org.springblade.modules.manage.entity.RtuImportRecordEntity;
import org.springblade.modules.manage.entity.RtuInfoTableDataEntity;
import org.springblade.modules.manage.service.IRtuImportRecordDetailService;
import org.springblade.modules.manage.service.IRtuImportRecordService;
import org.springblade.task.RtuImportTask;
import org.springblade.modules.manage.vo.RtuImportRecordVO;
import org.springblade.modules.resource.builder.oss.OssBuilder;
import org.springblade.modules.system.service.IDeptService;
import org.springblade.task.TaskManager;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import springfox.documentation.annotations.ApiIgnore;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.FutureTask;

/***
 * Date:2022/8/31
 * Title:文件所属模块（必须填写）
 * Description：对本文件的详细描述，原则上不能少于30字
 * @author dylan
 * @version 1.0
 * Remark：认为有必要的其他信息
 */
@RestController
@RequestMapping("galaxy-business/data/manage")
@AllArgsConstructor
@Api(value = "数据管理模块", tags = "数据管理模块")
public class DataManageController extends BladeController {

	final IProjectBaseInfoService projectBaseInfoService;
	final IRtuBaseInfoService rtuBaseInfoService;
	final IRtuImportRecordService rtuImportRecordService;
	final IRtuImportRecordDetailService rtuImportRecordDetailService;
	final IDeptService deptService;
	final IMvAttStBaseService mvAttStBaseService;

	private final OssBuilder ossBuilder;

	@Resource
	private TaskManager taskManager;


	@GetMapping("/page")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页")
	public R<IPage<RtuImportRecordVO>> list(Query query) {
		return R.data(rtuImportRecordService.selectPage(Condition.getPage(query)));
	}


	@GetMapping("/detail/page")
	@ApiOperationSupport(order = 2)
	@ApiOperation(value = "分页")
	public R<IPage<RtuImportRecordDetailEntity>> detailPage(@ApiIgnore RtuImportRecordDetailEntity entity, Query query) {
		LambdaQueryWrapper<RtuImportRecordDetailEntity> wrapper = Wrappers.<RtuImportRecordDetailEntity>query().lambda();
		wrapper.eq(RtuImportRecordDetailEntity::getIsDeleted, 0);
		wrapper.eq(RtuImportRecordDetailEntity::getRecordId, entity.getId());
		wrapper.orderByDesc(RtuImportRecordDetailEntity::getSaveType);
		return R.data(rtuImportRecordDetailService.page(Condition.getPage(query), wrapper));
	}

	@ApiLog("测站信息-导入")
	@GetMapping(value = "/import/rtu/test")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "导入测站信息", notes = "")
	public R importTest() {
		try {

			String filePath = "D:\\tmp\\rtu\\xa.xlsx";

			// 这里 需要指定读用哪个class去读，然后读取第一个sheet 文件流会自动关闭
			EasyExcel.read(filePath, RtuInfoTableDataEntity.class, new ReadListener() {
				@Override
				public void invoke(Object o, AnalysisContext analysisContext) {
					System.out.println(JSON.toJSONString(o));
				}

				@Override
				public void doAfterAllAnalysed(AnalysisContext analysisContext) {

				}
			}).sheet().doRead();


//			int sheetIndex = 0;
//
//			// 定义输入流
//			FileInputStream fis = null;
//			List<Map> datas = null;
//
//			try {
//				// 创建输入流对象
//				fis = new FileInputStream(filePath);
//				// 创建一个easypoi使用的配置类
//				ImportParams params = new ImportParams();
//				// 设置表格坐标
//				params.setStartSheetIndex(sheetIndex);
//				// 校验Excel文件，去掉空行
//				params.setNeedVerify(true);
//				// 读取数据
//				datas = ExcelImportUtil.importExcel(fis, Map.class, params);
//			} catch (Exception e) {
//				e.printStackTrace();
//			} finally {
//				try {
//					if (fis != null) {
//						fis.close();
//					}
//				} catch (IOException e) {
//					e.printStackTrace();
//				}
//			}
//
//			for (Map apiInfo : datas) {
//				System.out.println(apiInfo);
//			}

			return R.success("导入成功");
		} catch (Exception e) {
			return R.fail("导入错误 " + e.getMessage());
		}
	}

	@ApiLog("测站信息-导入")
	@ApiImplicitParams({
		@ApiImplicitParam(name = "remark", value = "导入说明", paramType = "query", dataType = "string"),
		@ApiImplicitParam(name = "saveType", value = "操作类型", paramType = "query", dataType = "int"),
	})
	@PostMapping(value = "/import/rtu")
	@ApiOperationSupport(order = 6)
	@ApiOperation(value = "导入测站信息", notes = "")
	public R importRtuTable(@ApiIgnore RtuImportRecordDTO rtuImportRecordDTO, MultipartFile file) {
		try {
			BladeFile bladeFile = ossBuilder.template().putFile(file);
			if (null == bladeFile) {
				return R.fail("导入失败");
			}

			RtuImportRecordEntity recordEntity = new RtuImportRecordEntity();
			recordEntity.setImportStatus(0L);
			recordEntity.setRemark(rtuImportRecordDTO.getRemark());
			recordEntity.setSaveType(rtuImportRecordDTO.getSaveType());
			recordEntity.setImportTime(Func.formatDateTime(new Date()));
			recordEntity.setFileName(file.getOriginalFilename());
			this.rtuImportRecordService.save(recordEntity);

			RtuImportTask task = new RtuImportTask(bladeFile, recordEntity, this.rtuBaseInfoService, this.rtuImportRecordService, this.rtuImportRecordDetailService);
			FutureTask<Integer> futureTask = new FutureTask<>(task);
			taskManager.submitTask(futureTask);

			return R.success("导入任务提交成功");
		} catch (Exception e) {
			e.printStackTrace();
			return R.fail("导入错误 " + e.getMessage());
		}
	}
}
