using Furion.DependencyInjection;
using Microsoft.AspNetCore.Hosting;
using MiniExcelLibs;
using Nirvana.Common.ApiBase;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace YBDevice.Application.Excel
{
    /// <summary>
    /// EXCEL处理
    /// </summary>
    public class ExcelService : IExcelService, ITransient
    {
        private static IWebHostEnvironment _hostingEnvironment;
        public ExcelService(IWebHostEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }
        /// <summary>
        /// 数据导出
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public async Task<ResultInfo> ExportAsync(List<Dictionary<string, object>> list)
        {
            if (list.Count == 0)
            {
                return new ResultInfo(ResultState.FAIL, "未查询到可用的数据");
            }
            string savefolder = _hostingEnvironment.WebRootPath;
            string rootname = $"/download/device";
            if (!Directory.Exists($"{savefolder}{rootname}"))
            {
                Directory.CreateDirectory($"{savefolder}{rootname}");
            }
            string filename = $"{DateTime.Now.ToString("yyyyMMddHHmmssff")}.xlsx";
            string path = $"{savefolder}{rootname}/{filename}";
            await MiniExcel.SaveAsAsync(path, list);
            return new ResultInfo(ResultState.SUCCESS, "导出成功", $"{rootname}/{filename}");
        }
    }
}
