using SqlSugar;
using System.Dynamic;
using Tiobon.Core.Common.DB.Dapper.Extensions;
using Tiobon.Core.Model.ViewModels.Extend;

namespace Tiobon.Core.Api.Controllers;

[AllowAnonymous, Route("api/Ghrh_ResumeTemplatePreview"), ApiExplorerSettings(GroupName = Grouping.GroupName_Other)]
public class Ghrh_ResumeTemplatePreviewController : Controller
{

    private readonly ISqlSugarClient _db;
    private readonly IGhrh_ResumeServices _ghrh_ResumeServices;
    private readonly IGhrh_ResumeHomeServices _ghrh_ResumeHomeServices;
    private readonly IGhrh_ResumeEduBGServices _ghrh_ResumeEduBGServices;
    private readonly IGhrh_ResumeWorkExpServices _ghrh_ResumeWorkExpServices;
    private readonly IGhrh_ResumeLicenceServices _ghrh_ResumeLicenceServices;
    private readonly IGhrh_ResumeTrainingServices _ghrh_ResumeTrainingServices;
    private readonly IGhrh_ResumeStatementServices _ghrh_ResumeStatementServices;


    public Ghrh_ResumeTemplatePreviewController(ISqlSugarClient db,
        IGhrh_ResumeServices ghrh_ResumeServices,
        IGhrh_ResumeEduBGServices ghrh_ResumeEduBGServices,
        IGhrh_ResumeWorkExpServices ghrh_ResumeWorkExpServices,
        IGhrh_ResumeLicenceServices ghrh_ResumeLicenceServices,
        IGhrh_ResumeTrainingServices ghrh_ResumeTrainingServices,
        IGhrh_ResumeStatementServices ghrh_ResumeStatementServices,
        IGhrh_ResumeHomeServices ghrh_ResumeHomeServices)
    {
        _db = db;
        _ghrh_ResumeServices = ghrh_ResumeServices;
        _ghrh_ResumeHomeServices = ghrh_ResumeHomeServices;
        _ghrh_ResumeEduBGServices = ghrh_ResumeEduBGServices;
        _ghrh_ResumeWorkExpServices = ghrh_ResumeWorkExpServices;
        _ghrh_ResumeLicenceServices = ghrh_ResumeLicenceServices;
        _ghrh_ResumeTrainingServices = ghrh_ResumeTrainingServices;
        _ghrh_ResumeStatementServices = ghrh_ResumeStatementServices;
    }
    /// <summary>
    /// Index
    /// </summary>
    /// <returns></returns>
    [Route("{id}")]
    public async Task<IActionResult> Index(long id)
    {
        string sql = @"DECLARE @ID   BIGINT = 1

BEGIN
   DECLARE
      @MasterTemplateID   INT = 0,
      @TemplateType       INT                                        -- 母版设定ID
   SELECT @TemplateType = TemplateType
   FROM Ghrh_ResumeTemplate
   WHERE ID = @ID
   SELECT @MasterTemplateID = ID
   FROM Ghrh_ResumeTemplate
   WHERE IsEnable = 1 AND TemplateType = 1

   SELECT *
   FROM (SELECT a.ID,
                a.ID ResumeTemplateInfoGroupID,
                b.ID ResumeInfoGroupID,
                b.GroupName tabName,
                b.GroupType tabKey,
                b.TableName,
                b.TablePKIDName,                                   --  是否可挑选栏位
                ISNULL (a.IsDisplay, 0) isDisplay,
                isnull (a.SortNo, b.SortNo) SortNo,
                CASE
                   WHEN b.GroupType = 'Base' THEN 'list'
                   WHEN b.GroupType = 'Attachment' THEN 'Attachment'
                   WHEN b.GroupType = 'Statement' THEN 'Statement'
                   ELSE 'block'
                END AS type,
                -- case when ISNULL(a.IsDisplay,0)=0 then ''
                CASE
                   WHEN 1 = 2
                   THEN
                      ''
                   ELSE
                      CASE
                         WHEN b.GroupType = 'Base'                  -- 读取各模板设定
                         THEN
                            isnull
                            (
                               (SELECT pp.ColumnName field,
                                       pp.ResumeInfoColumnName label,
                                       pp.IsRequired required,
                                       pp.ColumnType elementType,
                                       CASE
                                          WHEN pp.DataSourceType =
                                               'ParaDetailNo'
                                          THEN
                                             (SELECT   'TBParaDetail_'
                                                     + ParaTypeNo
                                                     + '_'
                                                     + ParaMasterNo
                                              FROM Ghrs_ParaMaster
                                              WHERE ParaMasterId =
                                                    pp.DataSource)
                                          WHEN pp.DataSourceType =
                                               'CommonList'
                                          THEN
                                             (SELECT   'CommonList_'
                                                     + ListCommonSqlNo
                                              FROM Ghrs_ListCommonSql
                                              WHERE ListCommonSqlId =
                                                    pp.DataSource)
                                          ELSE
                                             NULL
                                       END dataSource,
                                       pp.DataType dataType,
                                       pp.MultipleSelect multipleSelect,
                                       kk.SortNo sortNo,
                                       pp.Placeholder placeholder,
                                       pp.Editable editable
                                FROM Ghrh_ResumeTemplateInfoGroupColumn kk,
                                     Ghrh_ResumeInfoColumn pp
                                WHERE     kk.ResumeTemplateInfoGroupID = a.ID
                                      -- a.ResumeTemplateInfoGroupID
                                      AND kk.ResumeInfoColumnID = pp.ID
                                      AND kk.IsDisplay = 1
                                      AND pp.IsEnable = 1
                                      AND kk.IsEnable = 1
                                order by kk.SortNo
                                FOR JSON PATH, INCLUDE_NULL_VALUES),
                               '')
                         WHEN b.GroupType = 'Photo'                 -- 读取各模板设定
                         THEN
                            (SELECT PhotoType
                             FROM Ghrh_ResumeTemplate
                             WHERE ResumeTemplateID = @MasterTemplateID
                             FOR JSON PATH, INCLUDE_NULL_VALUES)
                         WHEN b.GroupType NOT IN ('Base', 'Photo')  -- 读取母版的设定
                         THEN
                            isnull
                            (
                               (SELECT pp.ColumnName field,
                                       pp.ResumeInfoColumnName label,
                                       pp.IsRequired required,
                                       pp.ColumnType elementType,
                                       CASE
                                          WHEN pp.DataSourceType =
                                               'ParaDetailNo'
                                          THEN
                                             (SELECT   'TBParaDetail_'
                                                     + ParaTypeNo
                                                     + '_'
                                                     + ParaMasterNo
                                              FROM Ghrs_ParaMaster
                                              WHERE ParaMasterId =
                                                    pp.DataSource)
                                          WHEN pp.DataSourceType =
                                               'CommonList'
                                          THEN
                                             (SELECT   'CommonList_'
                                                     + ListCommonSqlNo
                                              FROM Ghrs_ListCommonSql
                                              WHERE ListCommonSqlId =
                                                    pp.DataSource)
                                          ELSE
                                             NULL
                                       END dataSource,
                                       pp.DataType dataType,
                                       pp.MultipleSelect multipleSelect,
                                       kk.SortNo sortNo,
                                       pp.Placeholder placeholder,
                                       pp.Editable editable
                                FROM Ghrh_ResumeTemplateInfoGroupColumn kk,
                                     Ghrh_ResumeInfoColumn pp
                                WHERE     kk.ResumeTemplateID =
                                          @MasterTemplateID
                                      AND kk.ResumeInfoGroupId = b.Id
                                      -- b.ResumeInfoGroupId
                                      AND pp.Id = kk.ResumeInfoColumnId
                                      AND kk.IsDisplay = 1
                                      AND pp.IsEnable = 1
                                      AND kk.IsEnable = 1
                                order by kk.SortNo
                                FOR JSON PATH, INCLUDE_NULL_VALUES),
                               '')
                      END
                END children1
         FROM Ghrh_ResumeInfoGroup b
              LEFT JOIN Ghrh_ResumeTemplateInfoGroup a
                 ON     a.ResumeInfoGroupId = b.ID
                    AND a.IsEnable = 1
                    AND a.ResumeTemplateID = @ID
         WHERE b.IsEnable = 1) a
   WHERE a.IsDisplay = 1
   -- order by ISNULL(a.IsDisplay,0) desc,isnull(a.SortNo,b.SortNo)  -- 显示的放上面, 不显示的放下面, 再按照序号排序
   ORDER BY a.SortNo ASC
END";
        string statementRemark = string.Empty;
        var columns = await _db.Ado.SqlQueryAsync<ResumeFormColumn>(sql);
        columns.ForEach(x =>
        {
            if (x.children1.IsNotEmptyOrNull())
                x.children = JsonHelper.JsonToObj<List<ResumeFormColumnChildren>>(x.children1);
            if (x.children != null)
            {

                x.children = x.children.Where(o => o.label != "附件").ToList();
                if (x.tabKey == "Base")
                {
                    x.children.ForEach(o =>
                    {
                        if (o.field == "TitleId") o.field = "TitleName";
                        if (o.field == "Gender") o.field = "GenderLabel";
                        if (o.field == "Education") o.field = "EducationLabel";
                        if (o.field == "Nation") o.field = "NationLabel";
                        if (o.field == "MaritalStatus") o.field = "MaritalStatusLabel";
                        if (o.field == "PoliticStatus") o.field = "PoliticStatusLabel";
                        if (o.field == "UrgentRelation") o.field = "UrgentRelationLabel";
                        if (o.field == "CertificateType") o.field = "CertificateTypeLabel";
                        if (o.field == "RegisteredType") o.field = "RegisteredTypeLabel";
                        if (o.field == "EduDegree") o.field = "EduDegreeLabel";
                        if (o.field == "ApplyStatus") o.field = "ApplyStatusLabel";
                        if (o.field == "Channel")
                        {
                            o.field = "ChannelLabel";
                        }
                    });

                    x.children = x.children.Where(o => o.field != "EduDegree"
                    && o.field != "Gende"
                    && o.field != "StaffName"
                    && o.field != "ApplyStatus"
                    && o.field != "Channel"
                    && o.field != "WorkYears"
                    && o.field != "WorkYears"
                    && o.field != "Age").ToList();
                }
                else if (x.tabKey == "Family")
                    x.children.ForEach(o =>
                    {
                        if (o.field == "Gender") o.field = "GenderLabel";
                        if (o.field == "RelationType") o.field = "RelationTypeLabel";
                    });
                else if (x.tabKey == "Education")
                    x.children.ForEach(o =>
                    {
                        if (o.field == "IsGraduate") o.field = "IsGraduateLabel";
                        if (o.field == "DegreeLevel") o.field = "DegreeLevelLabel";
                        if (o.field == "BeginDate") o.field = "BeginDate1";
                        if (o.field == "EndDate") o.field = "EndDate1";
                    });
                else if (x.tabKey == "WorkExp" || x.tabKey == "Licence")
                    x.children.ForEach(o =>
                    {
                        if (o.field == "BeginDate") o.field = "BeginDate1";
                        if (o.field == "EndDate") o.field = "EndDate1";
                    });
                else if (x.tabKey == "Training")
                    x.children.ForEach(o =>
                    {
                        if (o.field == "BeginDate") o.field = "BeginDate1";
                        if (o.field == "EndDate") o.field = "EndDate1";
                        if (o.field == "IsPass") o.field = "IsPassLabel";
                    });
                else if (x.tabKey == "Statement")
                {
                    var child = x.children.Where(o => o.field == "StatementRemark").SingleOrDefault();
                    if (child != null)
                        statementRemark = child.placeholder;
                    x.children = x.children.Where(o => o.field != "StatementRemark").ToList();
                }
            }
            x.children1 = null;
        });
        ViewBag.Columns = columns.Where(o => o.tabName != "附件").ToList();



        #region Data
        dynamic Data = new ExpandoObject();

        var formColumns = await QueryResumeFormColumn(1);

        #region Base 
        var entity = await _ghrh_ResumeServices.QueryById(id);
        var columnNames = formColumns.Where(x => x.GroupType == "Base").Select(x => x.ColumnName).ToList();
        columnNames = columnNames.Distinct().ToList();
        var dicts = new Dictionary<string, object>
        {
        };
        columnNames.Add("TitleName");
        columnNames.Add("GenderLabel");
        columnNames.Add("EducationLabel");
        columnNames.Add("NationLabel");
        columnNames.Add("MaritalStatusLabel");
        columnNames.Add("PoliticStatusLabel");
        columnNames.Add("UrgentRelationLabel");
        columnNames.Add("CertificateTypeLabel");
        columnNames.Add("RegisteredTypeLabel");
        columnNames.Add("EduDegreeLabel");
        columnNames.Add("ApplyStatusLabel");
        columnNames.Add("ChannelLabel");
        columnNames.ForEach(x =>
        {
            var value = entity.GetPropertyValue(x);
            if (x == "RemarkSz")
            {
                if (value != null)
                {
                    value = "<div>" + value.ToString().Replace("\n", "</br>") + "</div>";
                }
                dicts.Add(x, value);

            }
            else
                dicts.Add(x, value);
        });

        ViewBag.BaseDic = dicts;
        ViewBag.entity = entity;
        #endregion

        #region 家庭关系 

        columnNames = formColumns.Where(x => x.GroupType == "Family").Select(x => x.ColumnName).ToList();
        columnNames = columnNames.Distinct().ToList();
        columnNames.Add("GenderLabel");
        columnNames.Add("RelationTypeLabel");
        var familys = await _ghrh_ResumeHomeServices.QueryDto(x => x.ResumeId != null && x.ResumeId == id);
        var familyDic = new List<Dictionary<string, object>>();
        familys.ForEach(family =>
        {
            var dicts = new Dictionary<string, object>();
            columnNames.ForEach(x =>
            {
                var value = family.GetPropertyValue(x);
                dicts.Add(x, value);
            });
            familyDic.Add(dicts);
        });

        ViewBag.FamilyDic = familyDic;
        #endregion

        #region 教育背景 

        columnNames = formColumns.Where(x => x.GroupType == "Education").Select(x => x.ColumnName).ToList();
        columnNames = columnNames.Distinct().ToList();
        columnNames.Add("IsGraduateLabel");
        columnNames.Add("DegreeLevelLabel");
        columnNames.Add("BeginDate1");
        columnNames.Add("EndDate1");
        var educations = await _ghrh_ResumeEduBGServices.QueryDto(x => x.ResumeId != null && x.ResumeId == id);
        var educationDic = new List<Dictionary<string, object>>();
        educations.ForEach(education =>
        {
            var dicts = new Dictionary<string, object>();
            columnNames.ForEach(x =>
            {
                var value = education.GetPropertyValue(x);
                dicts.Add(x, value);
            });
            educationDic.Add(dicts);
        });

        ViewBag.EducationDic = educationDic;
        #endregion 

        #region 工作经历
        columnNames = formColumns.Where(x => x.GroupType == "WorkExp").Select(x => x.ColumnName).ToList();
        columnNames = columnNames.Distinct().ToList();
        columnNames.Add("BeginDate1");
        columnNames.Add("EndDate1");
        var workExps = await _ghrh_ResumeWorkExpServices.QueryDto(x => x.ResumeId != null && x.ResumeId == id);
        var workExpDic = new List<Dictionary<string, object>>();
        workExps.ForEach(workExp =>
        {
            var dicts = new Dictionary<string, object>();
            columnNames.ForEach(x =>
            {
                var value = workExp.GetPropertyValue(x);
                dicts.Add(x, value);
            });
            workExpDic.Add(dicts);
        });

        ViewBag.WorkExpDic = workExpDic;
        #endregion

        #region 证件
        columnNames = formColumns.Where(x => x.GroupType == "Licence").Select(x => x.ColumnName).ToList();
        columnNames = columnNames.Distinct().ToList();
        columnNames.Add("BeginDate1");
        columnNames.Add("EndDate1");
        var Licences = await _ghrh_ResumeLicenceServices.QueryDto(x => x.ResumeId != null && x.ResumeId == id);
        var licenceDic = new List<Dictionary<string, object>>();
        Licences.ForEach(licence =>
        {
            var dicts = new Dictionary<string, object>();
            columnNames.ForEach(x =>
            {
                var value = licence.GetPropertyValue(x);
                dicts.Add(x, value);
            });
            licenceDic.Add(dicts);
        });

        ViewBag.LicenceDic = licenceDic;
        #endregion

        #region 简历培训记录 
        columnNames = formColumns.Where(x => x.GroupType == "Training").Select(x => x.ColumnName).ToList();
        columnNames = columnNames.Distinct().ToList();
        columnNames.Add("BeginDate1");
        columnNames.Add("EndDate1");
        columnNames.Add("IsPassLabel");
        var Trainings = await _ghrh_ResumeTrainingServices.QueryDto(x => x.ResumeId != null && x.ResumeId == id);
        var trainingDic = new List<Dictionary<string, object>>();
        Trainings.ForEach(training =>
        {
            var dicts = new Dictionary<string, object>();
            columnNames.ForEach(x =>
            {
                var value = training.GetPropertyValue(x);
                dicts.Add(x, value);
            });
            trainingDic.Add(dicts);
        });

        ViewBag.TrainingDic = trainingDic;
        #endregion

        var statements = await _ghrh_ResumeStatementServices.QueryDto(x => x.ResumeId != null && x.ResumeId == id);//证件

        var StatementDic = new Dictionary<string, bool?>();
        statements.ForEach(statement =>
        {
            if (!StatementDic.ContainsKey(statement.StatementCode))
                StatementDic.Add(statement.StatementCode, statement.TrueOrFalse);
        });
        ViewBag.StatementDic = StatementDic;

        #endregion

        string cssUrl = AppSettings.app(["Startup", "FrontUrl"]);
        string path = string.Empty;
        cssUrl += "/Advanced";
        if (App.HostEnvironment.IsDevelopment())
            cssUrl = "http://localhost:9292";
        cssUrl += "/css/resume.css";
        ViewBag.CssUrl = cssUrl;
        ViewBag.StatementRemark = statementRemark.Replace("\\n", "</br>");

        var displaySignatureArea = false;

        var config = await _db.Queryable<Ghrh_Config>().Where(x => x.ConfigCode == "ESS_Recruit_File_Display_Signature_Area").SingleAsync();

        if (config != null && config.ConfigValue == "1")
            displaySignatureArea = true;

        ViewBag.DisplaySignatureArea = displaySignatureArea;

        return View();
    }

    [NonAction]
    public async Task<List<ResumeFormColumn1>> QueryResumeFormColumn(long resumeTemplateID)
    {
        var sql = @$"DECLARE @ResumeTemplateID   BIGINT = {resumeTemplateID}

            SELECT A.ColumnName, A.ResumeInfoColumnName ColumnNameDesc, A.ColumnType, D.GroupType
            FROM Ghrh_ResumeInfoColumn A
                 LEFT JOIN Ghrh_ResumeTemplateInfoGroupColumn B
                    ON     B.ResumeInfoColumnID = A.ID
                       AND B.IsDisplay = 1
                       AND B.IsEnable = 1
                       AND A.IsEnable = 1
                 JOIN Ghrh_ResumeTemplateInfoGroup C
                    ON B.ResumeTemplateInfoGroupID = C.Id
                 JOIN Ghrh_ResumeInfoGroup D
                    ON C.ResumeInfoGroupId = D.ID AND D.IsEnable = 1
            WHERE C.ResumeTemplateID = @ResumeTemplateID 
            -- AND D.GroupType = 'Base'
            ORDER BY D.GroupType, b.SortNo";

        return await _db.Ado.SqlQueryAsync<ResumeFormColumn1>(sql);
    }
}
