using Serilog;
using Tiobon.Core.Common.Https.HttpPolly;
using static Tiobon.Core.Model.Consts;

namespace Tiobon.Core.Services;

/// <summary>
/// Ghre_Teacher (服务)
/// </summary>
public class Ghre_TeacherServices : BaseServices<Ghre_Teacher, Ghre_TeacherDto, InsertGhre_TeacherInput, EditGhre_TeacherInput>, IGhre_TeacherServices
{
    private readonly IBaseRepository<Ghre_Teacher> _dal;
    private IGhre_AttachmentServices _ghre_AttachmentServices;
    private IGhre_TeacherAttachmentServices _ghre_TeacherAttachmentServices;
    private readonly IHttpPollyHelper _httpPollyHelper;
    public Ghre_TeacherServices(ICaching caching,
    IGhre_AttachmentServices ghre_AttachmentServices,
    IGhre_TeacherAttachmentServices ghre_TeacherAttachmentServices,
    IHttpPollyHelper httpPollyHelper,
    IBaseRepository<Ghre_Teacher> dal)
    {
        this._dal = dal;
        base.BaseDal = dal;
        base._caching = caching;
        _ghre_AttachmentServices = ghre_AttachmentServices;
        _ghre_TeacherAttachmentServices = ghre_TeacherAttachmentServices;
        _httpPollyHelper = httpPollyHelper;
    }

    public override async Task<ServicePageResult<Ghre_TeacherDto>> 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 (SELECT A.*,
             A.TeacherNo + A.TeacherName TeacherName1,
             CASE A.TeacherType
                WHEN 'In' THEN B.DeptName
                WHEN 'Out' THEN C.SchoolName
                ELSE NULL
             END 'DeptOrSchoolName1'
      FROM Ghre_Teacher A
           LEFT JOIN Ghro_Dept B ON A.DeptID = B.DeptID
           LEFT JOIN Ghre_School C ON A.SchoolId = C.Id) A";
        var sql1 = @$"DECLARE @langId   INT = {filter.langId};";
        var sql = @$"SELECT *
                        FROM (SELECT A.*,
                                     ISNULL
                                     ((SELECT CASE WHEN @langId = 1 THEN UserName ELSE UserEname END
                                       FROM Ghrs_User B
                                       WHERE B.UserId = A.CreateBy),
                                      '') CreateDataInfo,
                                     ISNULL
                                     ((SELECT CASE WHEN @langId = 1 THEN UserName ELSE UserEname END
                                       FROM Ghrs_User B
                                       WHERE B.UserId = A.UpdateBy),
                                      '') UpdateDataInfo,
                                     ISNULL (A.UpdateTime, A.CreateTime) CreateTime1,
                                     A.TeacherNo + A.TeacherName TeacherName1,
                                     CASE A.TeacherType
                                        WHEN 'In' THEN B.DeptName
                                        WHEN 'Out' THEN C.SchoolName
                                        ELSE NULL
                                     END 'DeptOrSchoolName1'
                              FROM Ghre_Teacher A
                                   LEFT JOIN Ghro_Dept B ON A.DeptID = B.DeptID
                                   LEFT JOIN Ghre_School C ON A.SchoolId = C.Id) A";

        string conditions = " WHERE 1=1 ";
        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}, A.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 (!string.IsNullOrWhiteSpace(value))
                {
                    var jsonParam = JsonConvert.DeserializeObject<JsonParam>(value);

                    switch (jsonParam.operationKey)
                    {
                        case "Include":
                            conditions += $" AND {name} LIKE '%{jsonParam.columnValue}%'";
                            break;
                        case "NotInclude":
                            conditions += $" AND {name} NOT LIKE '%{jsonParam.columnValue}%'";
                            break;
                        case "IsNull":
                            conditions += $" AND {name} IS NULL";
                            break;
                        case "NotNull":
                            conditions += $" AND {name} IS NOT NULL";
                            break;
                        case "Equal":
                            conditions += $" AND {name} ='{jsonParam.columnValue}'";
                            break;
                        case "NotEqual":
                            conditions += $" AND {name} !='{jsonParam.columnValue}'";
                            break;
                        case "GreaterOrEqual"://大于等于
                            conditions += $" AND {name} >='{jsonParam.columnValue}'";
                            break;
                        case "Greater"://大于
                            conditions += $" AND {name} >'{jsonParam.columnValue}'";
                            break;
                        case "LessOrEqual"://小于等于
                            conditions += $" AND {name} <='{jsonParam.columnValue}'";
                            break;
                        case "Less "://小于
                            conditions += $" AND {name} <'{jsonParam.columnValue}'";
                            break;
                        default:
                            break;
                    }
                }
            }

        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;
        sql = sql1 + sql;
        var entitys = await Db.Ado.SqlQueryAsync<Ghre_TeacherDto>(sql);

        var data = new ServicePageResult<Ghre_TeacherDto>(filter.pageNum, total, filter.pageSize, entitys);
        //});

        var schoolIds = data.result.DT_TableDataT1.Where(x => x.SchoolId != null).Select(x => x.SchoolId.Value).Distinct().ToList();
        var deptIDs = data.result.DT_TableDataT1.Where(x => x.DeptID != null).Select(x => x.DeptID).Distinct().ToList();

        var depts = await Db.Queryable<Ghro_Dept>().Where(x => deptIDs.Contains(x.DeptID)).Select(x => new { x.DeptID, x.DeptName }).ToListAsync();
        var schools = await Db.Queryable<Ghre_School>().Where(x => schoolIds.Contains(x.Id)).Select(x => new { x.Id, x.SchoolName }).ToListAsync();

        data.result.DT_TableDataT1.ForEach(async x =>
        {
            x.GenderLabel = await GetParaLabel("Gender", x.Gender);
            x.TeacherTypeLabel = await GetParaLabel("TrainingTeacherType", x.TeacherType);
            x.TeacherLevelLabel = await GetParaLabel("TrainingTeacherLevel", x.TeacherLevel);
            x.DeptOrSchoolName = x.TeacherType == "Out" ? schools.FirstOrDefault(o => o.Id == x.SchoolId)?.SchoolName : depts.FirstOrDefault(o => o.DeptID == x.DeptID)?.DeptName;
            x.DataBelongName = await GetDataBelongName(x.DataBelongID);
        });
        return data;
    }


    public override async Task<ServiceFormResult<Ghre_TeacherDto>> QueryForm(QueryForm body)
    {
        var data = await base.QueryForm(body);
        var entitys = data.result.DT_TableDataT1;
        var ids = entitys.Select(x => x.Id).ToList();
        var teacherAttachments = await _ghre_TeacherAttachmentServices.QueryDto(x => ids.Contains(x.TeacherId.Value));
        var ids1 = teacherAttachments.Select(x => x.Id.ToString()).ToList();
        var attachments = await _ghre_AttachmentServices.QueryDto(x => ids1.Contains(x.TableName));
        attachments.ForEach(x =>
        {
            x.FileURL = "/Advanced" + x.FileURL;
            x.PhysicsPath = "/Advanced" + x.PhysicsPath;
            x.RelativePath = "/Advanced" + x.RelativePath;
            x.ThumbnailPath = "/Advanced" + x.ThumbnailPath;
        });

        teacherAttachments.ForEach(x =>
        {
            x.Attachments = attachments.Where(o => o.TableName == x.Id.ToString()).ToList();
        });
        entitys.ForEach(x =>
        {
            x.TeacherAttachments = teacherAttachments.Where(o => o.TeacherId == x.Id).ToList();
        });

        data.result.DT_TableDataT1 = entitys;
        return data;
    }

    public override async Task<long> Add(InsertGhre_TeacherInput entity)
    {
        if (entity.EffectiveDate != null && entity.ExpirationDate != null)
            if (entity.EffectiveDate > entity.ExpirationDate)
                throw new Exception($"失效日期必须大于生效日期！");

        if (entity.TeacherType == "In")
        {
            entity.SchoolId = null;
            var staff = await Db.Queryable<Ghra_Staff>().FirstAsync(x => x.StaffID == entity.StaffId);
            if (staff != null)
            {
                entity.TeacherNo = staff.StaffNo;
                entity.TeacherName = staff.StaffName;
            }

            if (await base.AnyAsync(x => x.StaffId == entity.StaffId))
                throw new Exception($"员工【{staff.StaffName}({staff.StaffNo})】已在讲师列表中！");
        }
        else
        {
            entity.DeptID = null;
            entity.StaffId = null;
        }

        var id = await base.Add(entity);
        var sql = $"SELECT ISNULL(MAX(id)+1,1) FROM Ghre_Teacher WHERE Id !='{id}'";
        var id1 = await Db.Ado.GetLongAsync(sql);
        sql = $"UPDATE Ghre_Teacher SET Id={id1} WHERE  Id ='{id}'";
        await Db.Ado.ExecuteCommandAsync(sql);
        id = id1;

        if (entity.TeacherAttachments != null && entity.TeacherAttachments.Any())
        {
            for (int i = 0; i < entity.TeacherAttachments.Count; i++)
            {
                var insert = entity.TeacherAttachments[i];
                insert.TeacherId = id;
                var teacherAttachmentId = await _ghre_TeacherAttachmentServices.Add(insert);
                if (insert.Attachments != null && insert.Attachments.Any())
                    for (int j = 0; j < insert.Attachments.Count; j++)
                    {
                        await Db.Updateable<Ghre_Attachment>()
                              .SetColumns(it => new Ghre_Attachment() { TableName = teacherAttachmentId.ToString(), UpdateTime = DateTime.Now })
                              .Where(it => it.RelativePath == insert.Attachments[j].RelativePath)
                              .ExecuteCommandAsync();
                    }
            }
        }
        return id;
    }

    public override async Task<bool> Update(long Id, EditGhre_TeacherInput editModel)
    {

        if (editModel.EffectiveDate != null && editModel.ExpirationDate != null)
            if (editModel.EffectiveDate > editModel.ExpirationDate)
                throw new Exception($"失效日期必须大于生效日期！");

        if (editModel.TeacherType == "In")
        {
            editModel.SchoolId = null;
            var staff = await Db.Queryable<Ghra_Staff>().FirstAsync(x => x.StaffID == editModel.StaffId);
            if (staff != null)
            {
                editModel.TeacherNo = staff.StaffNo;
                editModel.TeacherName = staff.StaffName;
            }
        }
        else
        {
            editModel.DeptID = null;
            editModel.StaffId = null;
        }
        var result = await base.Update(Id, editModel, null, ["Status"]);
        await _ghre_TeacherAttachmentServices.Delete(x => x.TeacherId == Id);
        if (editModel.TeacherAttachments != null && editModel.TeacherAttachments.Any())
        {
            for (int i = 0; i < editModel.TeacherAttachments.Count; i++)
            {
                var insert = editModel.TeacherAttachments[i];
                insert.TeacherId = Id;
                var TeacherAttachmentId = await _ghre_TeacherAttachmentServices.Add(Mapper.Map(insert).ToANew<InsertGhre_TeacherAttachmentInput>());
                if (insert.Attachments != null && insert.Attachments.Any())
                    for (int j = 0; j < insert.Attachments.Count; j++)
                    {
                        await Db.Updateable<Ghre_Attachment>()
                              .SetColumns(it => new Ghre_Attachment() { TableName = TeacherAttachmentId.ToString(), UpdateTime = DateTime.Now })
                              .Where(it => it.RelativePath == insert.Attachments[j].RelativePath)
                              .ExecuteCommandAsync();
                    }
            }
        }

        return result;
    }
    public async Task<ServiceResult<long>> InsertByStatus(InsertGhre_TeacherInput insertModel, string status)
    {
        var data = ServiceResult<long>.OprateSuccess("新增成功", 0);
        insertModel.Status = status;
        var id = await Add(insertModel);

        data.Success = id > 0;
        if (data.Success)
            data.Data = id;
        else
            return ServiceResult<long>.OprateFailed("发布成功！");

        return data;
    }

    public async Task<ServiceResult> UpdateStatus(InsertGhre_TeacherInput input, string status)
    {

        HttpRequest request = UserContext.Context.Request;
        var api = request.Path.ObjToString().TrimEnd('/').ToLower();
        var ip = GetUserIp(UserContext.Context);

        var entities = new List<Ghre_Teacher>();
        foreach (var id in input.Ids)
        {
            if (!BaseDal.Any(id))
                continue;

            var entity = await BaseDal.QueryById(id);


            switch (status)
            {
                case DIC_REQUEST_STATUS.Active:
                    entity.AgreeReason = input.Reason;
                    entity.AgreeTime = DateTime.Now;
                    entity.AgreeUserId = App.User.ID;
                    break;
                case DIC_REQUEST_STATUS.Temporary:
                    entity.RefuseReason = input.Reason;
                    entity.RefuseTime = DateTime.Now;
                    entity.RefuseUserId = App.User.ID;
                    break;
            }

            entity.UpdateIP = ip;
            entity.UpdateProg = api;
            entity.Status = status;
            entities.Add(entity);
        }

        var result = await BaseDal.Update(entities);
        return ServiceResult.OprateSuccess("执行成功！");

    }


    #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_Teacher);
        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 TeacherType = dt.Rows[i]["讲师分类"].ToString();
            var StaffNo = dt.Rows[i]["工号"].ToString();
            var StaffName = dt.Rows[i]["姓名"].ToString();
            var SchoolName = dt.Rows[i]["培训机构"].ToString();
            var TeacherNo = dt.Rows[i]["讲师编号"].ToString();
            var TeacherName = dt.Rows[i]["讲师姓名"].ToString();
            var Gender = dt.Rows[i]["性别"].ToString();
            var Email = dt.Rows[i]["邮箱"].ToString();
            var Mobile = dt.Rows[i]["手机号码"].ToString();
            var TeacherLevel = dt.Rows[i]["讲师等级"].ToString();
            var Price = dt.Rows[i]["课时费"].ToString();
            var SkillPoints = dt.Rows[i]["擅长领域"].ToString();
            var remarkSz = dt.Rows[i]["备注"].ToString();

            var dict = new Dictionary<string, object>
                {
                { "Id",  SnowFlakeSingle.Instance.NextId() },
                { "CreateBy", App.User.ID },
                { "CreateTime", DateTime.Now },
                { "RemarkSz", remarkSz }
              };

            if (TeacherType.IsNullOrEmpty())
                continue;
            if (TeacherType == "内部")
            {
                if (StaffNo.IsNullOrEmpty())
                {
                    comments.Add("工号不能为空！");
                    data.ErrorCount++;
                    dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a));
                    isExistError = true;
                    continue;
                }
                if (StaffName.IsNullOrEmpty())
                {
                    comments.Add("姓名不能为空！");
                    data.ErrorCount++;
                    dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a));
                    isExistError = true;
                    continue;
                }

                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;
                }

                TeacherNo = staff.StaffNo;
                TeacherName = staff.StaffName;
                Email = staff.Email.ObjToString();
                Mobile = staff.Mobile.ObjToString();
                Gender = staff.Gender;

                dict.Add("DeptID", staff.DeptID);
                dict.Add("StaffId", staff.StaffID);
                dict.Add("TeacherType", "In");
            }
            else
            {
                if (Gender.IsNullOrEmpty())
                    Gender = "unknown";
                else
                    Gender = Gender == "男" ? "Male" : "Female";

                if (SchoolName.IsNullOrEmpty())
                {
                    comments.Add("培训机构不能为空！");
                    data.ErrorCount++;
                    dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a));
                    isExistError = true;
                    continue;
                }
                var school = await Db.Queryable<Ghre_School>().Where(x => x.SchoolName == SchoolName).FirstAsync();
                if (school is null)
                {
                    comments.Add("无效的培训机构！");
                    data.ErrorCount++;
                    dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a));
                    isExistError = true;
                    continue;
                }
                dict.Add("SchoolId", school.Id);

                if (TeacherNo.IsNullOrEmpty())
                {
                    comments.Add("讲师编号不能为空！");
                    data.ErrorCount++;
                    dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a));
                    isExistError = true;
                    continue;
                }
                if (TeacherName.IsNullOrEmpty())
                {
                    comments.Add("讲师姓名不能为空！");
                    data.ErrorCount++;
                    dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a));
                    isExistError = true;
                    continue;
                }
                dict.Add("TeacherType", "Out");
            }

            if (await base.AnyAsync(x => x.TeacherNo == TeacherNo))
            {
                comments.Add("讲师编号重复！");
                data.ErrorCount++;
                dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a));
                isExistError = true;
                continue;
            }
            if (TeacherLevel.IsNullOrEmpty())
            {
                comments.Add("讲师等级不能为空！");
                data.ErrorCount++;
                dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a));
                isExistError = true;
                continue;
            }

            var items = await GetParaList("TrainingTeacherLevel");
            TeacherLevel = items.Where(x => x.ParaDetailName == TeacherLevel).FirstOrDefault()?.ParaDetailNo ?? "In";

            if (Price.IsNullOrEmpty())
            {
                comments.Add("课时费不能为空！");
                data.ErrorCount++;
                dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a));
                isExistError = true;
                continue;
            }
            try
            {
                Convert.ToInt32(Price);
            }
            catch (Exception)
            {
                comments.Add($"课时费填写有误！");
                data.ErrorCount++;
                dt.Rows[i]["Comments"] = string.Join(";", comments.Select(a => a));
                isExistError = true;
                continue;
            }

            dict.Add("TeacherNo", TeacherNo);
            dict.Add("TeacherName", TeacherName);
            dict.Add("Email", Email);
            dict.Add("Mobile", Mobile);
            dict.Add("Gender", Gender);
            dict.Add("Price", Price);
            dict.Add("TeacherLevel", TeacherLevel);
            dict.Add("SkillPoints", SkillPoints);

            if (menuName == "F_TeacherManage")
                dict.Add("Status", "Wait");
            else
                dict.Add("Status", "Temporary");
            try
            {
                await Db.Insertable(dict).AS("Ghre_Teacher").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



    #region 牛尾培训讲师同步
    public async Task Ushio_Sync()
    {
        Log.Information($"【牛尾培训讲师同步】开始同步");
        try
        {
            string sql = @"SELECT A.SchoolId,
                                   b.DeptID,
                                   C.StaffId,
                                   A.TeacherType,
                                   A.TeacherNo,
                                   A.TeacherName,
                                   A.PhotoUrl,
                                   A.Gender,
                                   A.Email,
                                   A.Mobile,
                                   A.TeacherLevel,
                                   A.Price,
                                   A.SkillPoints,
                                   A.ApplyReason,
                                   C.StaffId SponsorId,A.WorkNo,A.WorkID
                            FROM [120.26.205.42].[GhrUshio].[dbo].Ushio_TrainTeacher A
                                 LEFT JOIN Ghro_Dept B ON A.DeptNo = B.DeptNo
                                 LEFT JOIN Ghra_Staff C ON A.TeacherNo = C.StaffNo
                                 LEFT JOIN Ghra_Staff D ON A.ApplyStaffNo = D.StaffNo
                            WHERE WorkNo NOT IN (SELECT WorkNo
                                                 FROM Ghre_Teacher
                                                 WHERE WorkNo IS NOT NULL AND IsEnable=1) AND EnableYN = 'Y'";

            var dt = await Db.Ado.GetDataTableAsync(sql);

            var list = Db.Utilities.DataTableToList<Ghre_TeacherDto>(dt);

            Log.Information($"【牛尾培训讲师同步】查询到待同步{list.Count}条数据");
            for (int i = 0; i < list.Count; i++)
            {
                Log.Information($"【牛尾培训讲师同步】同步队列{i + 1}/{list.Count}");

                var insert = Mapper.Map(list[i]).ToANew<InsertGhre_TeacherInput>();

                if (await base.AnyAsync(x => x.WorkNo == insert.WorkNo))
                    continue;
                //Advanced
                if (insert.SchoolId == 0) insert.SchoolId = null;
                var photoUrl = $"/files/upload/{DateTimeHelper.ConvertToSecondString1(DateTime.Now)}.png";

                try
                {

                    await _httpPollyHelper.DownLoad("http://120.26.205.42:3002" + insert.PhotoUrl, photoUrl);
                }
                catch (Exception)
                {
                    photoUrl = null;
                }

                var workId = insert.WorkID;

                insert.PhotoUrl = "/Advanced" + photoUrl;
                insert.Status = "Wait";
                insert.WorkID = null;
                var id = await base.Add(insert);

                sql = $"SELECT ISNULL(MAX(id)+1,1) FROM Ghre_Teacher WHERE Id !='{id}'";
                var id1 = await Db.Ado.GetLongAsync(sql);
                sql = $"UPDATE Ghre_Teacher SET Id={id1} WHERE  Id ='{id}'";
                await Db.Ado.ExecuteCommandAsync(sql);

                #region 同步证件
                sql = $@"SELECT CertificateNo,
                               CertificateName,
                               EffectiveDate,
                               ExpirationDate,
                               TeacherAttachmentID
                        FROM [120.26.205.42].[GhrUshio].[dbo].Ushio_TeacherAttachment
                        WHERE WorkID = {workId}";
                dt = await Db.Ado.GetDataTableAsync(sql);
                var attachments = Db.Utilities.DataTableToList<InsertGhre_TeacherAttachmentInput>(dt);
                Log.Information($"【牛尾培训讲师同步】查询到【{attachments.Count}】笔证件数据");

                if (attachments.Any())
                {
                    for (int j = 0; j < attachments.Count; j++)
                    {
                        attachments[j].TeacherId = id1;
                        var attachmentId = await _ghre_TeacherAttachmentServices.Add(attachments[j]);

                        sql = @$"SELECT AttachmentNo,
                                   AttachmentName,
                                   AttachmentName AttachFileName,
                                   AttachFileSize,
                                   FileUrl PhysicsPath,
                                   AttachFileExtension
                            FROM [120.26.205.42].[GhrUshio].[dbo].Ghrs_Attachment
                            WHERE     EnableYN = 'Y'
                                  AND Reverse1 = 'Ghre_TeacherAttachment'
                                  AND ReverseN1 = {attachments[j].TeacherAttachmentID}";

                        dt = await Db.Ado.GetDataTableAsync(sql);
                        var attachments1 = Db.Utilities.DataTableToList<InsertGhre_AttachmentInput>(dt);
                        if (attachments1.Any())
                        {
                            for (int m = 0; m < attachments1.Count; m++)
                            {
                                attachments1[m].TableName = attachmentId.ObjToString();

                                photoUrl = $"/files/upload/{DateTimeHelper.ConvertToSecondString1(DateTime.Now)}/{attachments1[m].AttachFileName}.png";

                                try
                                {

                                    await _httpPollyHelper.DownLoad(attachments1[m].PhysicsPath, photoUrl);
                                    attachments1[m].PhysicsPath = photoUrl;
                                    attachments1[m].RelativePath = photoUrl;
                                    attachments1[m].ThumbnailPath = photoUrl;
                                    attachments1[m].FileURL = photoUrl;
                                    await _ghre_AttachmentServices.Add(attachments1);
                                }
                                catch (Exception)
                                {
                                    photoUrl = null;
                                }
                            }

                        }

                    }

                }
                #endregion

            }

            sql = @"SELECT A.SchoolId,
                                   b.DeptID,
                                   C.StaffId,
                                   A.TeacherType,
                                   A.TeacherNo,
                                   A.TeacherName,
                                   A.PhotoUrl,
                                   A.Gender,
                                   A.Email,
                                   A.Mobile,
                                   A.TeacherLevel,
                                   A.Price,
                                   A.SkillPoints,
                                   A.ApplyReason,
                                   C.StaffId SponsorId,A.WorkNo,A.WorkID
                            FROM [120.26.205.42].[GhrUshio].[dbo].Ushio_TrainTeacher A
                                 LEFT JOIN Ghro_Dept B ON A.DeptNo = B.DeptNo
                                 LEFT JOIN Ghra_Staff C ON A.TeacherNo = C.StaffNo
                                 LEFT JOIN Ghra_Staff D ON A.ApplyStaffNo = D.StaffNo
                            WHERE WorkNo IN (SELECT WorkNo
                                                 FROM Ghre_Teacher
                                                 WHERE WorkNo IS NOT NULL AND IsEnable=1) AND EnableYN = 'N'";

            dt = await Db.Ado.GetDataTableAsync(sql);

            list = Db.Utilities.DataTableToList<Ghre_TeacherDto>(dt);

            Log.Information($"【牛尾培训讲师同步】查询到待同步{list.Count}条数据");
            for (int i = 0; i < list.Count; i++)
            {
                Log.Information($"【牛尾培训讲师同步】同步队列{i + 1}/{list.Count}");

                await Db.Updateable<Ghre_Teacher>()
         .SetColumns(it => new Ghre_Teacher() { IsEnable = 0 })
         .Where(it => it.TeacherNo == list[i].TeacherNo)
         .ExecuteCommandAsync();

            }
        }
        catch (Exception E)
        {
            Log.Information($"【牛尾培训讲师同步】发生错误：{E.Message}");
            Log.Information($"【牛尾培训讲师同步】发生错误行：{E.StackTrace}");
        }
        Log.Information($"【牛尾培训讲师同步】结束同步");
    }
    #endregion
}