package com.persagy.proxy.adm.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.util.ResourceUtils;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Lists;
import com.persagy.proxy.adm.constant.AdmCommonConstant;
import com.persagy.proxy.adm.request.AdmResponse;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @version 1.0.0
 * @company persagy 
 * @author zhangqiankun
 * @date 2021年10月21日 下午12:24:28
 */
@Slf4j
public class AdmExcelUtil {

	public static final String TEMP_PAHT = "/temp/";
	
	public static final String TEMP_UPLOAD_PAHT = "/temp/upload/";
	
	/**
	 * 文件写入至本地
	 * 
	 * @param workbook
	 * @param projectId
	 * @param path
	 * @param orgFileName
	 * @return 
	 */
	public static String writeFile2Local(Workbook workbook, String projectId, String path, String orgFileName) {
		FileOutputStream fileOutputStream = null;
		String date = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss"));
		// 重组文件名
        String fileName = projectId + date + "." + orgFileName.substring(orgFileName.lastIndexOf(".") + 1);
        try {
    		// 调用中台存储完成之后，此文件存储至本地
    		File templateFile = createTemplateFile(path, fileName);
    		fileOutputStream = new FileOutputStream(templateFile);
    		workbook.write(fileOutputStream);
		} catch (Exception e) {
			log.error("文件存储失败", e);
		} finally {
			if (fileOutputStream != null) {
				try {
					fileOutputStream.close();
				} catch (IOException e) {}
			}
		}
        return fileName;
	}
	
	/**
	 * 获取对应的文件，或者默认文件
	 * 不同路径，防止镜像部署时获取不到
	 * 
	 * @param templateName 带后缀的文件名
	 * @return
	 * @throws FileNotFoundException 
	 */
	public static File getTemplateOrDefaultFile(String templateName) throws FileNotFoundException {
		File file = ResourceUtils.getFile(AdmCommonConstant.SERVER_ROOT_PATH + TEMP_PAHT + templateName);
		if (!file.exists()) {
			file = ResourceUtils.getFile(AdmCommonConstant.SERVER_ROOT_PATH + TEMP_PAHT + "relation-template.xlsx");
		}
		return file;
	}
	
	/**
	 * 获取对应的模板文件，不同路径，防止镜像内获取不到
	 * 
	 * @param templateName 带后缀的文件名
	 * @return
	 * @throws FileNotFoundException 
	 */
	public static File getTemplateFile(String templateName) throws FileNotFoundException {
		return ResourceUtils.getFile(AdmCommonConstant.SERVER_ROOT_PATH + TEMP_PAHT + templateName);
	}
	
	/**
	 * 创建本地文件，这里不再在classpath下创建
	 * 
	 * @param path 以 / 结尾
	 * @param fileName 文件名称，带后缀
	 * @throws IOException 
	 */
	public static File createTemplateFile(String path, String fileName) throws IOException {
		File file = new File(path);
		if (!file.exists()) {
			file.mkdirs();
		}
		file = new File(path + fileName);
		if (!file.exists()) {
			file.createNewFile();
		}
		return file;
	}
	
	/**
	 * 获取导入结果
	 * 
	 * @param graphId
	 * @param successCount
	 * @param failCount
	 * @return
	 */
	public static JSONObject getImportResult(String graphId, int successCount, int failCount) {
		JSONObject result = new JSONObject();
		result.put("relationType", graphId);
		result.put("successCount", successCount);
		result.put("failCount", failCount);
        result.put("state", getState(successCount, failCount));
		return result;
	}
	
	/**
	 * 获取导入结果
	 * 
	 * @param message
	 * @param state
	 * @param successCount
	 * @param failCount
	 * @return
	 */
	public static AdmResponse getImportFailResult(String message, String state, int successCount, int failCount) {
		JSONObject content = new JSONObject();
		content.put("state", state);
		content.put("successCount", successCount);
		content.put("failCount", failCount);
		
		AdmResponse failure = AdmResponse.failure(message);
		failure.setContent(Lists.newArrayList(content));
		return failure;
	}
	
	/**
	 * 获取导入结果
	 * 
	 * @param message
	 * @param successCount
	 * @param failCount
	 * @return
	 */
	public static AdmResponse getImportSuccessResult(String message, int successCount, int failCount) {
		JSONObject content = new JSONObject();
		content.put("state", getState(successCount, failCount));
		content.put("successCount", successCount);
		content.put("failCount", failCount);
		AdmResponse success = AdmResponse.success(Lists.newArrayList(content));
		success.setMessage(message);
		return success;
	}
	
	/**
	 * 获取文件导入状态
	 * 
	 * @param successCount
	 * @param failCount
	 * @return
	 */
	private static String getState(int successCount, int failCount) {
		if (successCount > 0 && failCount > 0) {
        	return "1";
        } else if (successCount > 0 && failCount == 0) {
        	return "0";
        }
        return "2";
	}
	
}
