namespace Tiobon.Core.Services;

/// <summary>
/// 培训记录 (服务)
/// </summary>
public class Ghre_CertificateServices : BaseServices<Ghre_Certificate, Ghre_CertificateDto, InsertGhre_CertificateInput, EditGhre_CertificateInput>, IGhre_CertificateServices
{
    private readonly IBaseRepository<Ghre_Certificate> _dal;
    public Ghre_CertificateServices(ICaching caching, IBaseRepository<Ghre_Certificate> dal)
    {
        this._dal = dal;
        base.BaseDal = dal;
        base._caching = caching;
    }

    public override async Task<ServicePageResult<Ghre_CertificateDto>> QueryFilterPage(QueryBody filter, string condition, bool? IsEnable = true)
    {
        if (string.IsNullOrWhiteSpace(filter.orderBy))
            filter.orderBy = "CreateTime1 DESC";

        if (filter.pageSize == 0)
            filter.pageSize = 10000;

        var countSql = @$" SELECT COUNT(1) FROM  Ghre_Certificate_V";
        var sql = @$" SELECT *
                    FROM Ghre_Certificate_V  A";

        string conditions = " WHERE 1=1 ";
        if (await Db.Queryable<Ghrs_Menu>().Where(x => x.DataPrivType == "Priv" && x.MenuNo == filter.menuName).AnyAsync())
        {
            var staffIds = await GetUserStaffPrivIds((int)App.User.ID);
            if (staffIds.Any())
                conditions = $" WHERE StaffId IN ({string.Join(",", staffIds.Select(id => "'" + id + "'"))})";
        }
        if (IsEnable == true)
            conditions += " AND IsEnable = 1";
        else if (IsEnable == false)
            conditions += " AND IsEnable = 0";

        if (!string.IsNullOrWhiteSpace(condition))
            conditions += " AND " + condition;

        conditions += $" AND dbo.FUserDataBelongPriv ({App.User.ID}, DataBelongID, NULL) = 1";

        if (filter.jsonParam != null)
            foreach (JProperty jProperty in filter.jsonParam.Properties())
            {
                var name = jProperty.Name;
                var value = jProperty.Value.ToString();
                if (name == "page" || name == "pageSize")
                    continue;
                if (name == "Date")
                {
                    var jsonParam = JsonConvert.DeserializeObject<JsonParam1>(value);
                    conditions += $" AND (Date BETWEEN '{jsonParam.columnValue[0]}' AND '{jsonParam.columnValue[1]}')";

                    continue;
                }
                if (!string.IsNullOrWhiteSpace(value))
                    conditions = DealConditions(conditions, name, value);
            }

        sql += conditions;
        countSql += conditions;
        int total = await Db.Ado.GetIntAsync(countSql);

        sql = "SELECT * FROM (SELECT *, ROW_NUMBER() OVER (ORDER BY " + filter.orderBy + ") NUM FROM (SELECT * FROM (" + sql + " ";
        sql += ") A ) B ) C";

        sql += " WHERE NUM <= " + filter.pageNum * filter.pageSize + " AND NUM >" + (filter.pageNum - 1) * filter.pageSize;

        var entitys = await Db.Ado.SqlQueryAsync<Ghre_CertificateDto>(sql);

        entitys.ForEach(entity =>
        {
            if (!string.IsNullOrWhiteSpace(entity.Indate))
                entity.Indate = DateTimeHelper.ConvertToDayString(entity.Indate);
        });

        return new ServicePageResult<Ghre_CertificateDto>(filter.pageNum, total, filter.pageSize, entitys);

    }

    #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_Certificate);
        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));

        var fields = new List<string>
        {
            "工号",
            "姓名",
            "证书名称",
            "课程",
            "颁发日期",
            "证书有效期",
            "备注"
        };
        for (int i = 0; i < dt.Rows.Count; i++)
        {
            var comments = new List<string>();


            bool isContinue = false;

            fields.ForEach(x =>
            {
                if (!dt.Columns.Contains(x))
                {
                    comments.Add("未查询到【" + x + "】列！");
                    data.ErrorCount++;
                    dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a));
                    isExistError = true;
                    isContinue = true;
                }
            });

            if (isContinue)
                continue;

            var StaffNo = dt.Rows[i]["工号"].ToString();
            var StaffName = dt.Rows[i]["姓名"].ToString();
            var CertificateName = dt.Rows[i]["证书名称"].ToString();
            var CourseName = dt.Rows[i]["课程"].ToString();
            var AwardDate = dt.Rows[i]["颁发日期"].ToString();
            var ValidityPeriod = dt.Rows[i]["证书有效期"].ToString();

            if (StaffNo.IsNullOrEmpty() && StaffName.IsNullOrEmpty())
                continue;

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

            var staff = await Db.Queryable<Ghra_Staff>().Where(x => x.StaffNo == StaffNo && x.StaffName == StaffName).FirstAsync();
            if (staff == null)
            {
                comments.Add($"未查询到该员工，工号或姓名填写错误！");
                data.ErrorCount++;
                dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a));
                isExistError = true;
                continue;
            }
            var rule = await Db.Queryable<Ghre_CertificateRule>().Where(x => x.CertificateName == CertificateName).FirstAsync();
            if (rule == null)
            {
                comments.Add($"无效的证书名称！");
                data.ErrorCount++;
                dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a));
                isExistError = true;
                continue;
            }
            var course = await Db.Queryable<Ghre_Course>().Where(x => x.CourseName == CourseName).FirstAsync();
            if (course == null)
            {
                comments.Add($"无效的课程！");
                data.ErrorCount++;
                dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a));
                isExistError = true;
                continue;
            }
            //if (await base.AnyAsync(x => x.CertificateRuleId == rule.Id && x.StaffId == staff.StaffID && x.CourseId == course.Id))
            //{
            //    comments.Add($"系统已存在相同证照数据！");
            //    data.ErrorCount++;
            //    dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a));
            //    isExistError = true;
            //    continue;
            //}

            if (AwardDate.IsNullOrEmpty())
                AwardDate = DateTime.Now.ToString();
            var dict = new Dictionary<string, object>
                {
                    { "Id", SnowFlakeSingle.Instance.NextId() },
                    { "CreateBy", App.User.ID },
                    { "CreateTime", DateTime.Now },
                    { "CertificateRuleId", rule.Id },
                    { "StaffId", staff.StaffID },
                    { "CourseId", course.Id },
                    { "AwardDate", AwardDate },
                    { "ValidityPeriod", ValidityPeriod },
                    { "RemarkSz", remarkSz }
                };
            try
            {
                await Db.Insertable(dict).AS("Ghre_Certificate").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);
    }


    public ServiceResult<List<Ghre_CertificateControl>> QueryControl()
    {
        var list = new List<Ghre_CertificateControl>
        {
            new Ghre_CertificateControl()
            {
                groupName="证书信息",
                groupList = {
                    new Ghre_CertificateControlItem()
                    {
                        label="证书编号",
                        field="CertificateNo",
                        type= "fieldText"
                    },
                    new Ghre_CertificateControlItem()
                    {
                        label="发证日期",
                        field="AwardDate",
                        type= "fieldText"
                    },
                    new Ghre_CertificateControlItem()
                    {
                        label="颁发机构",
                        field="CertificationBody",
                        type= "fieldText"
                    },
                    new Ghre_CertificateControlItem()
                    {
                        label="有效期至",
                        field="ValidityPeriod",
                        type= "fieldText"
                    },
                    new Ghre_CertificateControlItem()
                    {
                        label="电子章",
                        field="ElectronicSealUrl",
                        type= "image"
                    }
                }
            }
            ,new Ghre_CertificateControl()
            {
                groupName="学员信息",
                groupList = {
                    new Ghre_CertificateControlItem()
                    {
                        label="员工姓名",
                        field="StaffName",
                        type= "fieldText"
                    },
                    new Ghre_CertificateControlItem()
                    {
                        label="部门",
                        field="DeptName",
                        type= "fieldText"
                    },
                    new Ghre_CertificateControlItem()
                    {
                        label="岗位",
                        field="TitleName",
                        type= "fieldText"
                    },
                    new Ghre_CertificateControlItem()
                    {
                        label="照片",
                        field="PhotoUrl",
                        type= "fieldText"
                    }
                }

            }
            ,new Ghre_CertificateControl()
            {
                groupName="课程信息",
                groupList = {
                    new Ghre_CertificateControlItem()
                    {
                        label="课程名称",
                        field="CourseName",
                        type= "fieldText"
                    },
                    new Ghre_CertificateControlItem()
                    {
                        label="课程场景",
                        field="CourseSceneName",
                        type= "fieldText"
                    },
                    new Ghre_CertificateControlItem()
                    {
                        label="学习时间",
                        field="StudyTime",
                        type= "fieldText"
                    }
                }

            }
            ,new Ghre_CertificateControl()
            {
                groupName="考试信息",
                groupList = {
                    new Ghre_CertificateControlItem()
                    {
                        label="考试名称",
                        field="ExamName",
                        type= "fieldText"
                    },
                    new Ghre_CertificateControlItem()
                    {
                        label="考试编号",
                        field="ExamNo",
                        type= "fieldText"
                    },
                    new Ghre_CertificateControlItem()
                    {
                        label="考试分数",
                        field="ExamScore",
                        type= "fieldText"
                    },
                    new Ghre_CertificateControlItem()
                    {
                        label="考试结果",
                        field="ExamResult",
                        type= "fieldText"
                    },
                    new Ghre_CertificateControlItem()
                    {
                        label="考试评语",
                        field="ExamComment",
                        type= "fieldText"
                    }
                }

            }
        };
        return ServiceResult<List<Ghre_CertificateControl>>.OprateSuccess("查询成功！", list);
    }
    #endregion
}