namespace Tiobon.Core.Services;

/// <summary>
/// 课程分类 (服务)
/// </summary>
public class Ghre_CourseClassServices : BaseServices<Ghre_CourseClass, Ghre_CourseClassDto, InsertGhre_CourseClassInput, EditGhre_CourseClassInput>, IGhre_CourseClassServices
{
    private readonly IBaseRepository<Ghre_CourseClass> _dal;

    public Ghre_CourseClassServices(ICaching caching, IBaseRepository<Ghre_CourseClass> dal)
    {
        this._dal = dal;
        base.BaseDal = dal;
        base._caching = caching;
    }
    public override async Task<ServicePageResult<Ghre_CourseClassDto>> QueryFilterPage(QueryBody filter, string condition, bool? IsEnable = true)
    {
        var data = await base.QueryFilterPage(filter, condition, IsEnable);
        data.result.DT_TableDataT1.ForEach(x =>
        {
            x.BuiltInLabel = x.BuiltIn == 1 ? "是" : "否";
        });
        return data;
    }

    #region Excel导入


    public override async Task<ServiceResult<string>> DownloadExcel(string menuName)
    {
        var physicsPath = $"{Environment.CurrentDirectory}{Path.DirectorySeparatorChar}wwwroot";
        var path = $"{$"{Path.DirectorySeparatorChar}files{Path.DirectorySeparatorChar}ExcelTemplate{Path.DirectorySeparatorChar}"}";
        if (!Directory.Exists(physicsPath + path))
            Directory.CreateDirectory(physicsPath + path);

        Type entityType = typeof(Ghre_CourseClass);
        var fileName = entityType.GetEntityTableName() + ".xlsx";


        var physicsPath1 = physicsPath + path + fileName;
        //if (dataSourceLists.Any())
        //    physicsPath1 = physicsPath + path + newFileName;
        var result = ServiceResult<string>.OprateSuccess("课程分类_" + DateTimeHelper.ConvertToSecondString1(DateTime.Now) + ".xlsx", physicsPath1);
        return result;
    }
    public override async Task<ServiceResult<ExcelData>> ImportExcel(IFormFile file, string menuName = null, long? MasterId = null)
    {
        var data = new ExcelData();
        long id = SnowFlakeSingle.instance.getID();
        var physicsPath = $"{Environment.CurrentDirectory}{Path.DirectorySeparatorChar}wwwroot";
        var path = $"{$"{Path.DirectorySeparatorChar}files{Path.DirectorySeparatorChar}import{Path.DirectorySeparatorChar}{id}{Path.DirectorySeparatorChar}"}";
        if (!Directory.Exists(physicsPath + path))
            Directory.CreateDirectory(physicsPath + path);

        var filepath = physicsPath + path + file.FileName;
        using (var stream = File.Create(filepath))
        {
            await file.CopyToAsync(stream);
        }
        string extension = Path.GetExtension(filepath);

        bool isExistError = false;
        var id1 = SnowFlakeSingle.instance.getID();
        string errorFileName = path + SnowFlakeSingle.instance.getID() + extension;

        var dt = NPOIHelper.ImportExcel(filepath, "课程分类");
        if (dt.Columns["Comments"] == null)
            dt.Columns.Add("Comments", typeof(string));

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            var comments = new List<string>();

            if (!dt.Columns.Contains("分类编号"))
            {
                comments.Add("未查询到【分类编号】列！");
                data.ErrorCount++;
                dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a));
                isExistError = true;
                continue;
            }
            if (!dt.Columns.Contains("分类名称"))
            {
                comments.Add("未查询到【分类名称】列！");
                data.ErrorCount++;
                dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a));
                isExistError = true;
                continue;
            }
            if (!dt.Columns.Contains("备注"))
            {
                comments.Add("未查询到【备注】列！");
                data.ErrorCount++;
                dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a));
                isExistError = true;
                continue;
            }

            var ClassNo = dt.Rows[i]["分类编号"].ToString();
            var ClassName = dt.Rows[i]["分类名称"].ToString();
            if (ClassNo.IsNullOrEmpty() && ClassName.IsNullOrEmpty())
                continue;

            var remarkSz = dt.Rows[i]["备注"].ToString();

            if (await base.AnyAsync(x => x.ClassName == ClassName && x.ClassNo == ClassNo))
            {
                comments.Add($"系统已存在相同编号名称课程分类数据！");
                data.ErrorCount++;
                dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a));
                isExistError = true;
                continue;
            }


            var dict = new Dictionary<string, object>
                {
                    { "Id", SnowFlakeSingle.Instance.NextId() },
                    { "CreateBy", App.User.ID },
                    { "CreateTime", DateTime.Now },
                    { "ClassNo", ClassNo },
                    { "ClassName", ClassName },
                    { "RemarkSz", remarkSz }
                };
            try
            {
                await Db.Insertable(dict).AS("Ghre_CourseClass").ExecuteCommandAsync();
                data.SuccessCount++;
                //data.SuccessCount += list.Count;
            }
            catch (Exception E)
            {
                comments.Add(E.Message);
                data.ErrorCount++;
                dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a));
                isExistError = true;
                continue;
            }

        }

        if (isExistError)
        {
            NPOIHelper.ExportExcel(dt, null, "课程分类", physicsPath + errorFileName);
            data.filePath = "/Advanced" + errorFileName;
        }
        return ServiceResult<ExcelData>.OprateSuccess("导入成功！", data);
    }
    #endregion
}