package com.yeejoin.amos.boot.module.jcs.biz.controller;

import com.baomidou.mybatisplus.core.toolkit.Sequence;
import com.yeejoin.amos.boot.biz.common.controller.BaseController;
import com.yeejoin.amos.boot.biz.common.utils.RedisUtils;
import com.yeejoin.amos.boot.module.common.api.dto.ExcelDto;
import com.yeejoin.amos.boot.module.jcs.api.enums.ExcelEnums;
import com.yeejoin.amos.boot.module.jcs.biz.service.impl.DataSourcesImpl;
import com.yeejoin.amos.boot.module.jcs.biz.service.impl.ExcelServiceImpl;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.typroject.tyboot.core.foundation.enumeration.UserType;
import org.typroject.tyboot.core.restful.doc.TycloudOperation;
import org.typroject.tyboot.core.restful.exception.instance.BadRequest;
import org.typroject.tyboot.core.restful.utils.ResponseHelper;
import org.typroject.tyboot.core.restful.utils.ResponseModel;

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

/**
 * 导出导入
 *
 * @author system_generator
 * @date 2021-06-29
 */
@RestController
@Api(tags = "导出")
@RequestMapping(value = "/excel")
public class ExcelController extends BaseController {

	@Autowired
	ExcelServiceImpl excelService;

	@Autowired
	DataSourcesImpl dataSources;

	@Autowired
	RedisUtils redisUtils;

	@Autowired
	Sequence sequence;

	private static final String NOT_DUTY = "休班";

	@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "获取上传excle文件是否成功")
	@GetMapping("/get/template/isSuccess/{key}")
	public ResponseModel<Object> getTemplateIsSuccess(HttpServletResponse response,
			@PathVariable(value = "key") String key) {
		if (redisUtils.hasKey(key)) {
			Object obj = redisUtils.get(key);
			return ResponseHelper.buildResponse(obj);
		}
		return ResponseHelper.buildResponse(null);
	}

	@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "下载模板")
	@GetMapping("/download/template/{type}")
	public void downloadTemplate(HttpServletResponse response, @PathVariable(value = "type") String type) {
		try {
			ExcelEnums excelEnums = ExcelEnums.getByKey(type);
			ExcelDto excelDto = new ExcelDto(excelEnums.getFileName(), excelEnums.getSheetName(),
					excelEnums.getClassUrl(), excelEnums.getType());
			excelService.templateExport(response, excelDto);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("系统异常！");
		}
	}

	/**
	 * * @param Map par 可以传递过滤条件，传入具体实现类中
	 * 
	 * @return
	 * 
	 *         <PRE>
	 * author tw
	 * date 2021/9/13
	 *         </PRE>
	 */
	@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "导出公用类")
	@GetMapping("/export/{type}")
	public void getFireStationFile(HttpServletResponse response, @PathVariable(value = "type") String type,
			@RequestParam Map par) {
		try {
			ExcelEnums excelEnums = ExcelEnums.getByKey(type);
			ExcelDto excelDto = new ExcelDto(excelEnums.getFileName(), excelEnums.getSheetName(),
					excelEnums.getClassUrl(), excelEnums.getType());
			excelService.commonExport(response, excelDto, par);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("系统异常！");
		}
	}

	@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "导入公用")
	@PostMapping("/upload/{type}")
	public ResponseModel<Object> upload(@RequestPart("file") MultipartFile multipartFile,
			@PathVariable(value = "type") String type) {
		try {
			long uuid = sequence.nextId();
			String uuidString = Long.toString(uuid);
			redisUtils.set(uuidString, 0);
			ExcelEnums excelEnums = ExcelEnums.getByKey(type);
			ExcelDto excelDto = new ExcelDto(excelEnums.getFileName(), excelEnums.getSheetName(),
					excelEnums.getClassUrl(), excelEnums.getType());
			excelService.commonUpload(multipartFile, excelDto, uuidString);
			return ResponseHelper.buildResponse(uuidString);
		} catch (RuntimeException e) {
			e.printStackTrace();
			throw new BadRequest("文件格式不正确或excel 模板不匹配"); // BUG 2821 by litw 2021年9月16日
		} catch (Exception e) {
			throw new BadRequest("文件格式不正确或excel 模板不匹配！");
		}

	}

//    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
//    @ApiOperation(value = "上传文件数据-2")
//    @PostMapping("/upload2")
//    public void upload2(@RequestPart("file") MultipartFile multipartFile,
//                        @RequestParam(required = false) String fileName,
//                        @RequestParam(required = false) String sheetName,
//                        @RequestParam String type) {
//        try {
//            excelService.commonUpload(multipartFile, new ExcelDto(fileName, sheetName, type));
//        } catch (Exception e) {
//            e.printStackTrace();
//            throw new RuntimeException("系统异常！");
//        }
//    }
//    @TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
//    @ApiOperation(value = "导出公用类2")
//    @GetMapping("/export/list")
//    public void exportByType(HttpServletResponse response, @RequestParam(required = false) String fileName,
//                             @RequestParam(required = false) String sheetName, @RequestParam String type) {
//        try {
//            excelService.commonExport(response, new ExcelDto(fileName, sheetName, type));
//        } catch (Exception e) {
//            e.printStackTrace();
//            throw new RuntimeException("系统异常！");
//        }
//    }
	/**
	 * 导出值班模板
	 *
	 * @param response
	 * @param beginDate 值班开始日期
	 * @param endDate   值班结束日期
	 * @param excelDto  导出类型参数
	 * @param ids       部门或队伍的id列表，逗号分隔
	 */
	@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "导出值班模板", notes = "导出值班模板")
	@PostMapping(value = "/duty_template")
	public void dutyCarTemplate(HttpServletResponse response, @RequestParam("beginDate") String beginDate,
			@RequestParam("endDate") String endDate, ExcelDto excelDto, @RequestParam("ids") String ids) {
		try {
			excelService.dutyTemplateExport(response, beginDate, endDate, excelDto, ids);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("系统异常！");
		}
	}

	@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "导出值班信息", notes = "导出值班模板")
	@GetMapping(value = "/duty_info")
	public void dutyCarDuty(HttpServletResponse response, @RequestParam("beginDate") String beginDate,
			@RequestParam("endDate") String endDate, ExcelDto excelDto) {
		try {
			excelService.dutyInfoExport(response, beginDate, endDate, excelDto);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("系统异常！");
		}
	}

	@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "导出公用类带过滤参数")
	@PostMapping("/exportByParams/{type}")
	public void getFireStationFileByParams(HttpServletResponse response, @PathVariable(value = "type") String type,
			@RequestParam(value = "params") String params) {
		try {
			ExcelEnums excelEnums = ExcelEnums.getByKey(type);
			ExcelDto excelDto = new ExcelDto(excelEnums.getFileName(), excelEnums.getSheetName(),
					excelEnums.getClassUrl(), excelEnums.getType());
			excelService.exportByParams(response, excelDto, params);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("系统异常！");
		}
	}

	@TycloudOperation(needAuth = false, ApiLevel = UserType.AGENCY)
	@ApiOperation(value = "导出给提供设备接口")
	@GetMapping(value = "/exportForEquipment")
	public ResponseModel<String[]> getFireStationFileByParams(String type, String method) {
		try {
			return ResponseHelper.buildResponse(dataSources.selectList(type, method));
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("系统异常！");
		}
	}
}
