using Gatedge.K3Cloud.Utils;
using Gatedge.K3Cloud.Utils.Model.K3Request;
using Gatedge.ScanCode.Models.Vo.BaseData;
using Gatedge.ScanCode.Options;
using Gatedge.ScanCode.Services.IServices;
namespace Gatedge.ScanCode.Services
{
///
/// 金蝶k3服务类
///
public class K3FileService : IK3FileService
{
///
/// 金蝶云星空工具类
///
private K3CloudApiUtils _utils;
private readonly FileOption _fileOption;
private readonly ILogger _logger;
///
/// 初始化工具类
///
///
///
public K3FileService(FileOption fileOption, ILogger logger)
{
_fileOption = fileOption;
_logger = logger;
}
///
/// 下载物料
///
///
private List DonwloadFile(AttachmentFile file)
{
var base64File = DonwloadFile(file, 0);
return base64File;
}
///
/// 下载物料
///
///
///
private List DonwloadFile(AttachmentFile file, long startIndex)
{
FileParam fileParam = new FileParam()
{
FileId = file.FileID,
StartIndex = startIndex,
};
var fileResponse = _utils.FileDonwload(fileParam);
var fileBytes = Convert.FromBase64String(fileResponse.FilePart).ToList();
if (fileResponse.IsLast == false)
{
var nextStartIndex = Convert.ToInt64(fileResponse.StartIndex);
fileBytes.AddRange(DonwloadFile(file, nextStartIndex));
return fileBytes;
}
return fileBytes;
}
///
/// Base64字符串转文件并保存
///
/// base64字符串
/// 保存的文件名
/// 是否转换并保存成功
private bool Base64StringToFile(List dataBytes, string fileName)
{
try
{
string path = _fileOption.DonwloadPath; //文件保存路径
string fullPath = _fileOption.DonwloadPath + '/' + fileName;
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
File.WriteAllBytes(fullPath, dataBytes.ToArray());
return File.Exists(fullPath);
}
catch (Exception e)
{
_logger.LogError("异常类型: \t" + e.GetType());
_logger.LogError("异常描述:\t" + e.Message);
_logger.LogError("异常方法:\t" + e.TargetSite);
_logger.LogError("异常堆栈:\t" + e.StackTrace);
}
return false;
}
///
/// 获取文件路径,如果没有就会先下载,再返回路径
///
///
///
public string GetFilePath(AttachmentFile file)
{
string filePath = _fileOption.DonwloadPath + "/" + file.FileName;
if (!File.Exists(filePath))
{
var fileBase64String = DonwloadFile(file);
var isSave = Base64StringToFile(fileBase64String, file.FileName);
if (!isSave)
{
throw new Exception("文件保存错误,请联系管理员");
}
}
return filePath;
}
///
/// 设置K3Util
///
///
public void SetK3Util(K3CloudApiUtils utils)
{
_utils = utils;
}
}
}