/**
 * Copyright 2008-2009. Chongqing Communications Industry Services Co.,Ltd Information Technology Branch. All rights reserved. <a>http://www.crunii.com</a>
 */
package com.crunii.micro.service.sysmgr.service.impl;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.crunii.micro.common.dto.FileResponse;
import com.crunii.micro.common.exception.BusinessException;
import com.crunii.micro.common.ftp.RemoteFile;
import com.crunii.micro.common.utils.DateUtil;
import com.crunii.micro.common.utils.FileUtil;
import com.crunii.micro.common.utils.NanoIdUtil;
import com.crunii.micro.common.utils.UUIDUtil;
import com.crunii.micro.domain.dto.Worker;
import com.crunii.micro.domain.entity.main.TsmEncryptTest;
import com.crunii.micro.domain.entity.main.TsmFile;
import com.crunii.micro.domain.repo.main.TsmEncryptTestRepo;
import com.crunii.micro.domain.repo.main.TsmFileRepo;
import com.crunii.micro.service.sysmgr.dto.sysmgr.FileInfo;
import com.crunii.micro.service.sysmgr.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.Map;

/**
 * @author 田平 create 2019年6月18日上午9:28:45
 */
@Service(value = "fileService")
public class FileServiceImpl implements FileService {

	@Value("${image.store.path:defautl}")
	private String imageStorePath;

	@Autowired
	private RemoteFile remoteFile;

	@Autowired
	private TsmFileRepo tsmFileRepo;

	@Autowired
	private TsmEncryptTestRepo tsmEncryptTestRepo;

	private final Long fileLimit = 50L * 1024 * 1024;

	@Override
	public FileInfo getFileInfo(String fileId) {
		TsmFile file = tsmFileRepo.getOne(fileId);
		byte[] bytes = remoteFile.getFileBytes(file.getFilePath(), file.getFileStoreName());
		FileInfo fileInfo = new FileInfo();
		fileInfo.setFile(file);
		fileInfo.setFileBytes(bytes);
		return fileInfo;
	}

	/**
	 * <pre>
	 * 不同的业务尽量使用不同的目录
	 * </pre>
	 *
	 * @param configFile
	 */
	@Override
	public String doStoreImage(MultipartFile configFile) {
		String fileId = NanoIdUtil.randomLowerNanoId();
		try {
			// 远程目录不存在会自动创建目录
			String suffix = getSuffix(configFile.getOriginalFilename());
			String filePath = FileUtil.getRealPath(imageStorePath) + DateUtil.format(new Date(), "yyyyMMdd");
			String fileStoreName = fileId + suffix;
			TsmFile file = new TsmFile();
			file.setFileId(fileId);
			file.setFileName(configFile.getOriginalFilename());
			file.setFilePath(filePath);
			file.setFileStoreName(fileStoreName);
			file.setFileFullPath(filePath + "/" + fileStoreName);
			file.setCreateTime(new Date());
			tsmFileRepo.save(file);
			remoteFile.uploadFile(filePath, fileStoreName, configFile.getInputStream());
		} catch (IOException e) {
			throw new RuntimeException("sftpTool.uploadFileSftp error!", e);
		}
		return fileId;
	}

	public static String getSuffix(String fileName) {
		int idx = fileName.lastIndexOf(".");
		if (idx > -1) {
			return fileName.substring(idx);
		} else {
			return "";
		}
	}

	@Override
	public void doInsertEncrypt(TsmEncryptTest enc) {
		tsmEncryptTestRepo.save(enc);
	}

	@Override
	public void doUpdateEncrypt(TsmEncryptTest enc) {
		tsmEncryptTestRepo.save(enc);
	}

	@Override
	public TsmEncryptTest getEncrypt(int id) {
		return tsmEncryptTestRepo.getOne(id);
	}

	@Override
	public FileResponse doStoreFile(MultipartFile configFile, Worker worker) {
		if (configFile.getSize() > this.fileLimit) {
			Map<String, Object> format = MapUtil.of("fileName", configFile.getOriginalFilename());
			format.put("LimitSize", this.fileLimit / 1024 / 1024);
			throw new BusinessException(StrUtil.format(UPLOAD_SIZ_OUT_LIMIT_ERROR_MSG, format));
		}
		String fileId = UUIDUtil.getUUID();
		String url = null;
		FileResponse resp = new FileResponse();
		try {
			// 远程目录不存在会自动创建目录
			String suffix = getSuffix(configFile.getOriginalFilename());
			String filePath = FileUtil.getRealPath(this.imageStorePath) + DateUtil.format(new Date(), "yyyyMMdd");
			String fileStoreName = fileId + suffix;
			TsmFile file = new TsmFile();
			file.setFileId(fileId);
			file.setFileName(configFile.getOriginalFilename());
			file.setFilePath(filePath);
			file.setFileStoreName(fileStoreName);
			file.setFileFullPath(filePath + "/" + fileStoreName);
			file.setCreateTime(new Date());
			this.tsmFileRepo.save(file);
			this.remoteFile.uploadFile(filePath, fileStoreName, configFile.getInputStream());
			url = filePath + fileStoreName;

			resp.setName(configFile.getOriginalFilename());
			resp.setOriginalFilename(fileStoreName);
			resp.setUid(fileId);
            resp.setUrl("/xxxx/service-sysmgr/FileController/downloadFile?fileId=" + fileId);
//			resp.setUrl("/tzjs/service-sysmgr/FileController/downFileAndIdentify/" + fileId);
		} catch (IOException e) {
			throw new RuntimeException("sftpTool.uploadFileSftp error!", e);
		}
		return resp;
	}

}
