using Microsoft.AspNetCore.Mvc;
using System.Text.RegularExpressions;

namespace Tiobon.Core.Services;

public partial class CommonServices : BaseServices<RootEntityTkey<int>>, ICommonServices
{
    IHttpContextAccessor _httpContextAccessor;
    public ICaching _caching;
    public CommonServices(IHttpContextAccessor httpContextAccessor, ICaching caching = null)
    {
        _httpContextAccessor = httpContextAccessor;
        _caching = caching;
    }

    #region 获取菜单
    /// <summary>
    /// 获取菜单
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<ServiceResult<MenuReturn>> GetMenuAsync([FromBody] MenuParam param)
    {
        var result = new MenuReturn();
        string sql = "SELECT MenuID, MenuType FROM Ghrs_Menu WHERE IsEnable = 1 AND MenuNo = '{0}'";
        sql = string.Format(sql, param.menuName);
        DataTable dt = await DbAccess.GetDataTableAsync(sql);

        int MenuID = 0;
        string MenuType = string.Empty;
        if (dt.Rows.Count > 0)
        {
            MenuID = int.Parse(dt.Rows[0]["MenuID"].ToString());
            MenuType = dt.Rows[0]["MenuType"].ToString();
        }

        switch (MenuType)
        {
            case "MenuForm":
                {
                    sql = @"SELECT MenuNo,
                                   [dbo].[FLangKeyToValue] (MKey, {0}, MenuName) MenuName,
                                   IconType,
                                   MenuUrl,
                                   [dbo].[FParaDetailNoToName] ('GHRPara',
                                                                'MenuGroupTitle',
                                                                MenuGroupTitle,
                                                                {0},
                                                                1) MenuGroupTitle
                            FROM Ghrs_Menu
                            WHERE     ParentmenuID ='{1}'
                                  AND IsEnable = 1
                                  AND (SELECT count (1)
                                       FROM Ghrs_UserRole
                                       WHERE     UserID = '{2}'
                                             AND IsEnable = 1
                                             AND dbo.Fs_GetMenuIsCheckByRole (RoleId, MenuID, '') > 0) >
                                      0
                            ORDER BY SortNo";
                    sql = string.Format(sql, param.langId, MenuID, App.User.ID);
                    result.DT_SubMenu = await Db.Ado.SqlQueryAsync<DT_SubMenu>(sql);

                    sql = @"SELECT iif (MenuColDisplayType ! = 'Tile', 'Tab', 'Tile') MenuColType
                            FROM Ghrs_Menu
                            WHERE menuID = 120";
                    sql = string.Format(sql, MenuID);
                    result.DT_MenuColType = await Db.Ado.SqlQueryAsync<DT_MenuColType>(sql);
                    break;
                }

            default:
                {
                    break;

                }
        }

        return new ServiceResult<MenuReturn>() { Success = true, Message = "查询成功", Data = result, };
    }
    #endregion

    #region 获取模块信息
    /// <summary>
    /// 获取模块信息
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<ServiceResult<ModuleReturn>> GetModuleInfoAsync([FromBody] ModuleParam param)
    {
        var result = new ModuleReturn();

        //SELECT NULL fnKeySeq,
        //       'SetDefault' fnKey,
        //       [dbo].[FLangKeyToValue]('GHR_Common_000000',{2},'恢复默认') fnTitle,
        //       'table' fnType,
        //       'left' position,
        //       'ghr-icon-setDefault' icon
        //UNION ALL


        //UNION ALL
        //                SELECT NULL fnKeySeq,
        //                       'DataSort' fnKey,
        //                       'GHR_Common_000045' fnTitle,
        //                       'table',
        //                       'left',
        //                       'ghr-data-sort'

        #region 定义页面的操作按钮
        string sql = @"SELECT fnKey,
                       fnKeyValue,
                       [dbo].[FLangKeyToValue] (fnKeyValue, {2}, fnKeyValue) fnTitle,
                       fnType,
                       position,
                       icon,
                       'true' display
                    FROM (SELECT CASE
                                    WHEN substring (fnKey, 3, 99) + 'YN' = 'NewYN' THEN 1
                                    WHEN substring (fnKey, 3, 99) + 'YN' = 'ToExcelYN' THEN 2
                                    WHEN substring (fnKey, 3, 99) + 'YN' = 'FromExcelYN' THEN 3
                                    WHEN substring (fnKey, 3, 99) + 'YN' = 'BatchUpdateYN' THEN 4
                                    WHEN substring (fnKey, 3, 99) + 'YN' = 'BatchDelYN' THEN 5
                                    WHEN substring (fnKey, 3, 99) + 'YN' = 'LogYN' THEN 6
                                    WHEN substring (fnKey, 3, 99) + 'YN' = 'ManualYN' THEN 7
                                    WHEN substring (fnKey, 3, 99) + 'YN' = 'UpdateYN' THEN 2
                                    WHEN substring (fnKey, 3, 99) + 'YN' = 'DelYN' THEN 4
                                    WHEN substring (fnKey, 3, 99) + 'YN' = 'CopyYN' THEN 3
                                    WHEN substring (fnKey, 3, 99) + 'YN' = 'DetailYN' THEN 1
                                    ELSE 8
                                 END fnKeySeq,
                                 substring (fnKey, 3, 99) + 'YN' fnKey,
                                 'Ghr_FnKey_' + fnKey fnKeyValue,
                                 CASE
                                    WHEN substring (fnKey, 3, 99) + 'YN' IN ('NewYN',
                                                                             'ToExcelYN',
                                                                             'FromExcelYN',
                                                                             'BatchUpdateYN',
                                                                             'BatchDelYN',
                                                                             'RecycleYN',
                                                                             'CancelRecycleYN',
                                                                             'ManualYN',
                                                                             'LogYN',
                                                                             'BatchDelYN',
                                                                             'BatchUpdateYN')
                                    THEN
                                       'table'
                                    WHEN substring (fnKey, 3, 99) + 'YN' IN ('UpdateYN',
                                                                             'DelYN',
                                                                             'CopyYN',
                                                                             'DetailYN')
                                    THEN
                                       'row'
                                    WHEN substring (fnKey, 3, 99) + 'YN' IN ('QueryYN',
                                                                             'AdvanceQueryYN',
                                                                             'QuerySettingYN',
                                                                             '')
                                    THEN
                                       'search'
                                    ELSE
                                       ''
                                 END fnType,
                                 'left' position,
                                 CASE substring (fnKey, 3, 99) + 'YN'
                                    WHEN 'NewYN' THEN 'ghr-icon-add'
                                    WHEN 'ToExcelYN' THEN 'ghr-file-export'
                                    WHEN 'FromExcelYN' THEN 'ghr-file-import'
                                    WHEN 'UpdateYN' THEN 'ghr-icon-edit'
                                    WHEN 'BatchUpdateYN' THEN 'ghr-batch-update'
                                    WHEN 'DelYN' THEN 'ghr-icon-trash'
                                    WHEN 'BatchDelYN' THEN 'ghr-batch-del'
                                    WHEN 'LogYN' THEN 'ghr-log'
                                    WHEN 'ManualYN' THEN 'ghr-operation-manual'
                                    WHEN 'CopyYN' THEN 'ghr-icon-copy'
                                    WHEN 'DetailYN' THEN 'ghr-icon-eye-open'
                                    ELSE ''
                                 END icon
                          FROM (SELECT max (c.IsWaterMark) IsWaterMark,
                                       max (c.IsPWDAgain) IsPWDAgain,
                                       max (c.IsFromExcel) IsFromExcel,
                                       max (c.IsToExcel) IsToExcel,
                                       max (c.IsNew) IsNew,
                                       max (c.IsDetail) IsDetail,
                                       max (c.IsDel) IsDel,
                                       max (c.IsDel) IsBatchDel,
                                       max (c.IsUpdate) IsUpdate,
                                       max (c.IsUpdate) IsBatchUpdate,
                                       max (c.IsQuery) IsQuery,
                                       max (c.IsPrint) IsPrint,
                                       0  IsLog,
                                       max (c.IsManual) IsManual,
                                       max (c.IsCopy) IsCopy
                                FROM Ghrs_UserRole a, Ghrs_RoleMenu c, Ghrs_Menu d
                                WHERE     a.IsEnable = 1
                                      AND c.IsEnable = 1
                                      AND d.IsEnable = 1
                                      AND EXISTS
                                             (SELECT 1
                                              FROM Ghrs_Role kk
                                              WHERE kk.roleid = a.roleid AND kk.IsEnable = 1)
                                      AND a.UserID = '{1}'
                                      AND a.RoleId = c.RoleID
                                      AND c.MenuId = d.MenuId
                                      AND d.MenuNo = '{0}') kk
                               UNPIVOT (fnKeyValue
                                       FOR fnKey
                                       IN (IsWaterMark,
                                          IsPWDAgain,
                                          IsFromExcel,
                                          IsToExcel,
                                          IsNew,
                                          IsDetail,
                                          IsUpdate,
                                          IsDel,
                                          IsQuery,
                                          IsPrint,
                                          IsLog,
                                          IsManual,
                                          IsCopy,
                                          IsBatchUpdate,
                                          IsBatchDel)) AS tt
                          WHERE fnKeyValue > 0
                          UNION ALL
                          SELECT NULL fnKeySeq,
                                 'QuerySettingYN' fnKey,
                                 'GHR_Common_000064' fnTitle,
                                 'search' fnType,
                                 'left' position,
                                 NULL icon
                          UNION ALL
                          SELECT NULL fnKeySeq,
                                 'LabelYN' fnKey,
                                 'GHR_Common_000065' fnTitle,
                                 NULL fnType,
                                 NULL position,
                                 NULL icon
                          UNION ALL
                          SELECT NULL fnKeySeq,
                                 'MoreStyleYN' fnKey,
                                 'GHR_Common_000066' fnTitle,
                                 NULL fnType,
                                 NULL position,
                                 NULL icon
                          UNION ALL
                          SELECT NULL fnKeySeq,
                                 'GridView' fnKey,
                                 'GHR_Common_000067' fnTitle,
                                 'table' fnType,
                                 'right' position,
                                 'ant-design:setting-outlined' icon
                          UNION ALL
                          SELECT 8 fnKeySeq,
                                 'SetDefault' fnKey,
                                 '恢复默认' fnTitle,
                                 'table' fnType,
                                 'left' position,
                                 'ghr-icon-setDefault' icon
                        ) A
                    WHERE fnKey NOT IN
                             (SELECT b.field
                              FROM Ghrs_UserPageSettingQueryColumn a, Ghrs_PageSettingQuery b
                              WHERE     a.PageSettingQueryId = b.PageSettingQueryId
                                    AND a.UserID = '{1}'
                                    AND b.PageNo = '{0}'
                                    AND a.IsEnable = 1
                                    AND b.IsEnable = 1
                                    AND a.isHidden = 'true'
                                    AND b.elementType = 'FnKey') order by fnKeySeq";

        sql = string.Format(sql, param.menuName, App.User.ID, param.langId);
        //result.JM_PageControlT1.Toolbar = await Db.Ado.SqlQueryAsync<Toolbar>(sql);
        result.JM_PageControlT1.Toolbar = DbAccess.QueryList<Toolbar>(sql);

        #endregion

        #region 定义表格页面的栏位, 含  表格栏位, 常用查询栏位, 高级查询栏位,可编辑栏位 


        Db.Ado.BeginTran();
        sql = @"IF OBJECT_ID('tempdb.[dbo].[#TmpInitPageSettingQuery]') IS NOT NULL DROP TABLE [dbo].[#TmpInitPageSettingQuery]
	 CREATE TABLE [dbo].[#TmpInitPageSettingQuery](pageColumnID int) alter TABLE [dbo].[#TmpInitPageSettingQuery]
   add [elementType] [nvarchar](1000) , [field] [nvarchar](1000) ,[label] [nvarchar](1000) ,
	 [meky] [nvarchar](100) ,  [multipleSelect] [nvarchar](1000) , [dataType] [nvarchar](1000) ,
	 [required] [nvarchar](1000) , [palceholder] [nvarchar](1000) , [dataSourceType] [nvarchar](1000) ,
	 [dataSource] [nvarchar](1000) , [sortable] [nvarchar](1000) , [sortOrder] [nvarchar](1000) ,
	 [defaultHidden] [nvarchar](1000) ,[ConfigIsShow] [nvarchar](1000) ,  [filterable] [nvarchar](1000) , [width] int,
	 [align] [nvarchar](1000) , [fixed] [nvarchar](1000) ,
	 [editable] [nvarchar](1000) , [searchable] [nvarchar](1000) , [searchRequired] [nvarchar](1000) ,
	 [searchColumnSeq] int , [multipleSearchValue] [nvarchar](1000) , [maxTagCount] [nvarchar](1000) ,
	 [selfDefine] [nvarchar](2000) , [selectUI] [nvarchar](1000) , [isPrimaryKey] [nvarchar](1000) ,
	 isSorted nvarchar(10),isHidden nvarchar(10),isSearched nvarchar(10),sortNo int,   
	 [searchOperator] nvarchar(max),searchColumnDefaultValue nvarchar(1000),AppColumnType nvarchar(100)";
        int count = Db.Ado.ExecuteCommand(sql);


        sql = @"SELECT count (1) UserHasSetting
                    FROM Ghrs_UserPageSettingQueryColumn a, Ghrs_PageSettingQuery b
                    WHERE     b.PageNo = '{0}'
                          AND b.IsEnable = 1
                          AND b.field ! = 'Muti'
                          AND a.UserID = '{1}'
                          AND a.IsEnable = 1
                          AND a.PageSettingQueryId = b.PageSettingQueryId";
        sql = string.Format(sql, param.menuName, App.User.ID, param.langId);
        int UserHasSetting = Db.Ado.GetInt(sql);
        if (UserHasSetting == 0)
        {
            sql = @"INSERT INTO [dbo].[#TmpInitPageSettingQuery]
                          SELECT PageSettingQueryId,
                               elementType,
                               field,
                               label,
                               Meky,
                               multipleSelect,
                               dataType,
                               required,
                               palceholder,
                               dataSourceType,
                               dbo.FS_GetdataSourceBySet
                               (dataSource, APIDataSourceType, Ghrs_PageSettingQuery.APIDataSourceID)
                                  dataSource,
                               sortable,
                               sortOrder,
                               defaultHidden,
                               ConfigIsShow,
                               filterable,
                               CASE WHEN width = '' THEN '100' ELSE width END,
                               align,
                               fixed,
                               editable,
                               searchable,
                               searchRequired,
                               searchColumnSeq,
                               multipleSearchValue,
                               maxTagCount,
                               selfDefine,
                               selectUI,
                               isPrimaryKey,
                               'false'
                                  isSorted,
                               'false'
                                  isHidden,
                               CASE
                                  WHEN searchColumnSeq IS NULL OR searchColumnSeq = '' THEN 'false'
                                  ELSE 'true'
                               END
                                  isSearched,
                               SortNo,
                               searchCanOperator,
                               ''
                                  searchColumnDefaultValue,
                               ''
                                  AppColumnType
                        FROM Ghrs_PageSettingQuery
                        WHERE     PageNo = '{0}'
                              AND elementType NOT IN ('PageGroup')
                              AND IsEnable = 1
                        ORDER BY SortNo";
            sql = string.Format(sql, param.menuName, App.User.ID, param.langId);
            count = Db.Ado.ExecuteCommand(sql);
        }
        else
        {
            sql = @"INSERT INTO [dbo].[#TmpInitPageSettingQuery]
                           SELECT a.PageSettingQueryId,
                                  elementType,
                                  field,
                                  label,
                                  Meky,
                                  multipleSelect,
                                  dataType,
                                  required,
                                  palceholder,
                                  dataSourceType,
                                  dbo.FS_GetdataSourceBySet
                                  (dataSource, APIDataSourceType, b.APIDataSourceID)
                                     dataSource,
                                  sortable,
                                  isnull (a.sortOrder, b.sortOrder),
                                  defaultHidden,
                                  ConfigIsShow,
                                  filterable,
                                  CASE
                                     WHEN isnull (a.width, b.width) = '' THEN '100'
                                     ELSE isnull (a.width, b.width)
                                  END,
                                  align,
                                  a.fixed,
                                  editable,
                                  searchable,
                                  searchRequired,
                                  isnull (a.searchColumnSeq, b.searchColumnSeq),
                                  multipleSearchValue,
                                  maxTagCount,
                                  selfDefine,
                                  selectUI,
                                  isPrimaryKey,
                                  a.isSorted
                                     isSorted,
                                  isnull (a.isHidden, 'false')
                                     isHidden,
                                  CASE
                                     WHEN a.searchColumnSeq IS NULL OR a.searchColumnSeq = ''
                                     THEN
                                        'false'
                                     ELSE
                                        'true'
                                  END
                                     isSearched,
                                  a.SortNo,
                                  b.searchCanOperator,
                                  ''
                                     searchColumnDefaultValue,
                                  ''
                                     AppColumnType
                           FROM Ghrs_UserPageSettingQueryColumn a, Ghrs_PageSettingQuery b
                           WHERE     b.PageNo = '{0}'
                                 AND b.IsEnable = 1
                                 AND b.elementType NOT IN ('PageGroup')
                                 AND a.UserID = '{1}'
                                 AND a.IsEnable = 1
                                 AND a.PageSettingQueryId = b.PageSettingQueryId
                           ORDER BY a.SortNo, b.SortNo

                        INSERT INTO [dbo].[#TmpInitPageSettingQuery]
                           SELECT PageSettingQueryId,
                                  elementType,
                                  field,
                                  label,
                                  Meky,
                                  multipleSelect,
                                  dataType,
                                  required,
                                  palceholder,
                                  dataSourceType,
                                  dbo.FS_GetdataSourceBySet
                                  (dataSource,
                                   APIDataSourceType,
                                   Ghrs_PageSettingQuery.APIDataSourceID) dataSource,
                                  sortable,
                                  sortOrder,
                                  defaultHidden,
                                  ConfigIsShow,
                                  filterable,
                                  CASE WHEN width = '' THEN '100' ELSE width END,
                                  align,
                                  fixed,
                                  editable,
                                  searchable,
                                  searchRequired,
                                  searchColumnSeq,
                                  multipleSearchValue,
                                  maxTagCount,
                                  selfDefine,
                                  selectUI,
                                  isPrimaryKey,
                                  'false' isSorted,
                                  'false' isHidden,
                                  CASE
                                     WHEN searchColumnSeq IS NULL OR searchColumnSeq = ''
                                     THEN
                                        'false'
                                     ELSE
                                        'true'
                                  END isSearched,
                                  SortNo,
                                  searchCanOperator,
                                  '' searchColumnDefaultValue,
                                  '' AppColumnType
                           FROM Ghrs_PageSettingQuery
                           WHERE     PageNo = '{0}'
                                 AND elementType NOT IN ('PageGroup')
                                 AND IsEnable = 1
                                 AND elementtype = 'FnKey'
                                 AND NOT EXISTS
                                        (SELECT 1
                                         FROM [dbo].[#TmpInitPageSettingQuery] kk
                                         WHERE     kk.pageColumnID =
                                                   Ghrs_PageSettingQuery.PageSettingQueryId
                                               AND kk.field = Ghrs_PageSettingQuery.field
                                               AND kk.elementtype = Ghrs_PageSettingQuery.elementtype)
                           ORDER BY SortNo ";
            sql = string.Format(sql, param.menuName, App.User.ID, param.langId);
            count = Db.Ado.ExecuteCommand(sql);
        }


        sql = @"
	        -- 多语言的栏位的特别更新
            IF OBJECT_ID ('tempdb.[dbo].[#TempInitUserPageFnKey]') IS NOT NULL
               BEGIN
                  INSERT INTO [dbo].[#TmpInitPageSettingQuery]
                     SELECT 0,
                            elementType,
                            field,
                            label,
                            Meky,
                            multipleSelect,
                            dataType,
                            required,
                            palceholder,
                            dataSourceType,
                            dbo.FS_GetdataSourceBySet
                            (dataSource,
                             APIDataSourceType,
                             Ghrs_PageSettingQuery.APIDataSourceID) dataSource,
                            sortable,
                            sortOrder,
                            defaultHidden,
                            ConfigIsShow,
                            filterable,
                            CASE WHEN width = '' THEN '100' ELSE width END,
                            align,
                            fixed,
                            editable,
                            searchable,
                            searchRequired,
                            searchColumnSeq,
                            multipleSearchValue,
                            maxTagCount,
                            selfDefine,
                            selectUI,
                            isPrimaryKey,
                            'false' isSorted,
                            'false' isHidden,
                            CASE
                               WHEN searchColumnSeq IS NULL OR searchColumnSeq = ''
                               THEN
                                  'false'
                               ELSE
                                  'true'
                            END isSearched,
                            SortNo,
                            searchCanOperator,
                            '' searchColumnDefaultValue,
                            '' AppColumnType
                     FROM Ghrs_PageSettingQuery
                     WHERE     field = 'Muti'
                           AND IsEnable = 1
                           AND elementtype = 'FnKey'
                           AND pageno = 'F_Dept'
                           AND EXISTS
                                  (SELECT 1
                                   FROM [dbo].[#TempInitUserPageFnKey]
                                   WHERE fnKey = 'Muti')
                           AND NOT EXISTS
                                  (SELECT 1
                                   FROM [dbo].[#TmpInitPageSettingQuery] kk
                                   WHERE     kk.pageColumnID =
                                             Ghrs_PageSettingQuery.PageSettingQueryId
                                         AND kk.field = Ghrs_PageSettingQuery.field
                                         AND kk.elementtype =
                                             Ghrs_PageSettingQuery.elementtype)
                     ORDER BY SortNo

                  -- 明细按钮的宽度
                  INSERT INTO [dbo].[#TmpInitPageSettingQuery]
                     SELECT 0,
                            elementType,
                            'DetailYN',
                            label,
                            Meky,
                            multipleSelect,
                            dataType,
                            required,
                            palceholder,
                            dataSourceType,
                            dbo.FS_GetdataSourceBySet
                            (dataSource,
                             APIDataSourceType,
                             Ghrs_PageSettingQuery.APIDataSourceID) dataSource,
                            sortable,
                            sortOrder,
                            defaultHidden,
                            ConfigIsShow,
                            filterable,
                            CASE WHEN width = '' THEN '100' ELSE width END,
                            align,
                            fixed,
                            editable,
                            searchable,
                            searchRequired,
                            searchColumnSeq,
                            multipleSearchValue,
                            maxTagCount,
                            selfDefine,
                            selectUI,
                            isPrimaryKey,
                            'false' isSorted,
                            'false' isHidden,
                            CASE
                               WHEN searchColumnSeq IS NULL OR searchColumnSeq = ''
                               THEN
                                  'false'
                               ELSE
                                  'true'
                            END isSearched,
                            SortNo,
                            searchCanOperator,
                            '' searchColumnDefaultValue,
                            '' AppColumnType
                     FROM Ghrs_PageSettingQuery
                     WHERE     field = 'Muti'
                           AND IsEnable = 1
                           AND elementtype = 'FnKey'
                           AND pageno = 'F_Dept'
                           AND EXISTS
                                  (SELECT 1
                                   FROM [dbo].[#TempInitUserPageFnKey]
                                   WHERE fnKey = 'DetailYN')
                           AND NOT EXISTS
                                  (SELECT 1
                                   FROM [dbo].[#TmpInitPageSettingQuery] kk
                                   WHERE field = 'DetailYN' AND elementtype = 'FnKey')
                     ORDER BY SortNo
               END
            ELSE
               BEGIN
                  INSERT INTO [dbo].[#TmpInitPageSettingQuery]
                     SELECT 0,
                            elementType,
                            field,
                            label,
                            Meky,
                            multipleSelect,
                            dataType,
                            required,
                            palceholder,
                            dataSourceType,
                            dbo.FS_GetdataSourceBySet
                            (dataSource,
                             APIDataSourceType,
                             Ghrs_PageSettingQuery.APIDataSourceID) dataSource,
                            sortable,
                            sortOrder,
                            defaultHidden,
                            ConfigIsShow,
                            filterable,
                            CASE WHEN width = '' THEN '100' ELSE width END,
                            align,
                            fixed,
                            editable,
                            searchable,
                            searchRequired,
                            searchColumnSeq,
                            multipleSearchValue,
                            maxTagCount,
                            selfDefine,
                            selectUI,
                            isPrimaryKey,
                            'false' isSorted,
                            'false' isHidden,
                            CASE
                               WHEN searchColumnSeq IS NULL OR searchColumnSeq = ''
                               THEN
                                  'false'
                               ELSE
                                  'true'
                            END isSearched,
                            SortNo,
                            searchCanOperator,
                            '' searchColumnDefaultValue,
                            '' AppColumnType
                     FROM Ghrs_PageSettingQuery
                     WHERE     field = 'Muti'
                           AND IsEnable = 1
                           AND elementtype = 'FnKey'
                           AND pageno = 'F_Dept'
                           AND NOT EXISTS
                                  (SELECT 1
                                   FROM [dbo].[#TmpInitPageSettingQuery] kk
                                   WHERE     kk.pageColumnID =
                                             Ghrs_PageSettingQuery.PageSettingQueryId
                                         AND kk.field = Ghrs_PageSettingQuery.field
                                         AND kk.elementtype =
                                             Ghrs_PageSettingQuery.elementtype)
                     ORDER BY SortNo

                  -- 明细按钮的宽度
                  INSERT INTO [dbo].[#TmpInitPageSettingQuery]
                     SELECT 0,
                            elementType,
                            'DetailYN',
                            label,
                            Meky,
                            multipleSelect,
                            dataType,
                            required,
                            palceholder,
                            dataSourceType,
                            dbo.FS_GetdataSourceBySet
                            (dataSource,
                             APIDataSourceType,
                             Ghrs_PageSettingQuery.APIDataSourceID) dataSource,
                            sortable,
                            sortOrder,
                            defaultHidden,
                            ConfigIsShow,
                            filterable,
                            CASE WHEN width = '' THEN '100' ELSE width END,
                            align,
                            fixed,
                            editable,
                            searchable,
                            searchRequired,
                            searchColumnSeq,
                            multipleSearchValue,
                            maxTagCount,
                            selfDefine,
                            selectUI,
                            isPrimaryKey,
                            'false' isSorted,
                            'false' isHidden,
                            CASE
                               WHEN searchColumnSeq IS NULL OR searchColumnSeq = ''
                               THEN
                                  'false'
                               ELSE
                                  'true'
                            END isSearched,
                            SortNo,
                            searchCanOperator,
                            '' searchColumnDefaultValue,
                            '' AppColumnType
                     FROM Ghrs_PageSettingQuery
                     WHERE     field = 'Muti'
                           AND IsEnable = 1
                           AND elementtype = 'FnKey'
                           AND pageno = 'F_Dept'
                           AND NOT EXISTS
                                  (SELECT 1
                                   FROM [dbo].[#TmpInitPageSettingQuery] kk
                                   WHERE field = 'DetailYN' AND elementtype = 'FnKey')
                     ORDER BY SortNo
               END

            -- 更新可编辑
            IF OBJECT_ID ('tempdb.[dbo].[#TempInitUserPageFnKey]') IS NOT NULL
               BEGIN
                  UPDATE[dbo].[#TmpInitPageSettingQuery]
                  SET editable = 'false'
                  WHERE     (    NOT EXISTS
                                    (SELECT 1
                                     FROM [dbo].[#TempInitUserPageFnKey]
                                     WHERE     fnKey = 'UpdateYN'
                                           AND '{0}' NOT IN ('F_Staff~1',
                                                                 'F_StaffToDo',
                                                                 'F_StaffQuery',
                                                                 'F_StaffChangeToDo',
                                                                 'F_StaffChangeToEnable',
                                                                 'F_StaffChangeQuery',
                                                                 'F_SalaryChangeToDo',
                                                                 'F_SalaryChange',
                                                                 'F_SalaryChangeQuery'))
                             AND NOT EXISTS
                                    (SELECT 1
                                     FROM [dbo].[#TempInitUserPageFnKey]
                                     WHERE     fnKey = 'TBD2YN'
                                           AND '{0}' IN
                                                  ('F_Staff~1',
                                                   'F_StaffToDo',
                                                   'F_StaffQuery'))
                             AND NOT EXISTS
                                    (SELECT 1
                                     FROM [dbo].[#TempInitUserPageFnKey]
                                     WHERE     fnKey = 'TBD5YN'
                                           AND '{0}' IN ('F_StaffChangeToDo',
                                                             'F_StaffChangeToEnable',
                                                             'F_StaffChangeQuery',
                                                             'F_SalaryChangeToDo',
                                                             'F_SalaryChange',
                                                             'F_SalaryChangeQuery')))
                        AND '{0}' NOT IN ('F_SchedulePeriodSetup')
               END

            -- 更新栏位说明(从多语言里面)
            UPDATE[dbo].[#TmpInitPageSettingQuery]
            SET label = [dbo].[FLangKeyToValue] (Meky, {2}, label);

            UPDATE[dbo].[#TmpInitPageSettingQuery]
            SET width = 50
            WHERE elementType = 'FnKey' OR field = 'Muti';";
        sql = string.Format(sql, param.menuName, App.User.ID, param.langId);
        count = Db.Ado.ExecuteCommand(sql);

        sql = @"select pageColumnID,elementType, field,label,meky,  multipleSelect, dataType,
								required, palceholder, dataSourceType,dataSource, sortable, sortOrder,
								defaultHidden, ConfigIsShow, filterable,  width,align,fixed fixed1,editable, searchable, 
								searchRequired,searchColumnSeq, multipleSearchValue, maxTagCount,
								selfDefine, selectUI, isPrimaryKey,isSorted,isHidden,isSearched,sortNo, 
								( select ParaDetailNo operator,
										 [dbo].[FLangKeyToValue](MKey,{2},ParaDetailName) operatorDesc,
										 SqlFunction operatorIcon
									from Ghrs_ParaDetail where ParaMasterId=13 and IsEnable=1 
									 and ParaDetailNo in (select Value from dbo.Fs1_GHR30_SplitString2(searchOperator,','))
									 order by (select positon from  dbo.Fs1_GHR30_SplitString2(searchOperator,',')
									            where value= ParaDetailNo)  
									 FOR JSON Path  ) searchOperator1 ,
									 iif(ISJSON(searchColumnDefaultValue)=1,JSON_QUERY(searchColumnDefaultValue),null) searchColumnDefaultValue ,
									 AppColumnType
	                       from [dbo].[#TmpInitPageSettingQuery] 
						  order by sortno asc";
        sql = string.Format(sql, param.menuName, App.User.ID, param.langId);
        var TableColumn = Db.Ado.SqlQuery<TableColumn1>(sql);
        result.JM_TableColumnT1.TableColumn = Mapper.Map(TableColumn).ToANew<List<TableColumn>>();
        result.JM_TableColumnT1.TableColumn = result.JM_TableColumnT1.TableColumn.Where(x => x.field != "DetailYN" && x.field != "Muti").ToList();
        result.JM_TableColumnT1.TableColumn.ForEach(x =>
        {
            if (x.fixed1.IsNotEmptyOrNull()) x.@fixed = x.fixed1.ObjToBool();
            if (!string.IsNullOrWhiteSpace(x.searchOperator1))
                x.searchOperator = JsonConvert.DeserializeObject<List<searchOperator>>(x.searchOperator1);
            x.searchOperator1 = null;

            if (x.multipleSearchValue == "true")
                x.searchColumnDefaultValue = new List<string>();
            if (x.isPrimaryKey == "false")
                x.isPrimaryKey = null;
        });
        Db.Ado.CommitTran();

        string sqlLang = @"SELECT Langkey field,
                       CASE {2}
                          WHEN 1 THEN isnull (Value01, LangValue)
                          WHEN 2 THEN isnull (Value02, LangValue)
                          WHEN 3 THEN isnull (Value03, LangValue)
                          WHEN 4 THEN isnull (Value04, LangValue)
                          WHEN 5 THEN isnull (Value05, LangValue)
                          WHEN 6 THEN isnull (Value06, LangValue)
                          WHEN 7 THEN isnull (Value07, LangValue)
                          WHEN 8 THEN isnull (Value08, LangValue)
                          WHEN 9 THEN isnull (Value09, LangValue)
                          WHEN 10 THEN isnull (Value10, LangValue)
                       END label
                FROM Ghrs_LangKey
                WHERE     IsEnable = 1
                      AND (LangKey LIKE 'GHR_Page%' OR LangKey LIKE 'GHR_Common%' OR LangKey LIKE '{0}%')";
        sqlLang = string.Format(sqlLang, param.menuName, App.User.ID, param.langId);

        sql = "select QueryProcedure, EditProcedure, IUDProcedure from Ghrs_Menu where MenuNo='{0}'";
        sql = string.Format(sql, param.menuName, App.User.ID, param.langId);
        DataTable dt = Db.Ado.GetDataTable(sql);
        if (dt.Rows.Count > 0)
        {
            result.DT_Procedure.QueryProcedure = dt.Rows[0]["QueryProcedure"].ToString();
            result.DT_Procedure.EditProcedure = dt.Rows[0]["EditProcedure"].ToString();
            result.DT_Procedure.IUDProcedure = dt.Rows[0]["IUDProcedure"].ToString();
            if (!string.IsNullOrWhiteSpace(result.DT_Procedure.EditProcedure))
            {
                result.DT_Procedure.ImportExcel = result.DT_Procedure.EditProcedure.Replace("QueryForm", "ImportExcel");
                result.DT_Procedure.DownExcelTemplate = result.DT_Procedure.EditProcedure.Replace("QueryForm", "DownExcelTemplate?menuName=" + param.menuName);
                result.DT_Procedure.ExportExcel = result.DT_Procedure.EditProcedure.Replace("QueryForm", "ExportExcel");
            }
        }
        #endregion

        #region 特殊处理
        var toolbar = new Toolbar();
        var index = -1;
        switch (param.menuName)
        {
            case "F_CertificationComparison":
                result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                {
                    display = true,
                    fnKey = "TBD5YN",
                    fnTitle = "预览",
                    fnType = "row",
                    icon = "ghr-preview",
                    position = "left"
                });
                break;
            case "F_Training_CourseAndScene_Report":
                {
                    toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "NewYN").FirstOrDefault();
                    if (toolbar != null) { toolbar.fnKey = "TBD1YN"; }
                    toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "UpdateYN").FirstOrDefault();
                    if (toolbar != null) { toolbar.fnKey = "TBD2YN"; }
                    toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "DetailYN").FirstOrDefault();
                    if (toolbar != null) { toolbar.fnKey = "TBD3YN"; toolbar.fnTitle = "分析"; }
                    toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "CopyYN").FirstOrDefault();
                    if (toolbar != null) { toolbar.fnKey = "TBD4YN"; }
                    break;
                }
            case "F_SurveyQuestionPool":
            case "F_QuestionBank":
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "NewYN").FirstOrDefault();
                if (toolbar != null) { toolbar.fnKey = "TBD1YN"; }
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "UpdateYN").FirstOrDefault();
                if (toolbar != null) { toolbar.fnKey = "TBD2YN"; }
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "DetailYN").FirstOrDefault();
                if (toolbar != null) { toolbar.fnKey = "TBD3YN"; }
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "CopyYN").FirstOrDefault();
                if (toolbar != null) { toolbar.fnKey = "TBD4YN"; }
                break;
            case "F_ExamPaperDraft":
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "NewYN").FirstOrDefault();
                if (toolbar != null) { toolbar.fnKey = "TBD1YN"; }
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "UpdateYN").FirstOrDefault();
                if (toolbar != null) { toolbar.fnKey = "TBD2YN"; }
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "DetailYN").FirstOrDefault();
                if (toolbar != null) { toolbar.fnKey = "TBD3YN"; }

                index = result.JM_PageControlT1.Toolbar.FindIndex(x => x.fnKey == "TBD1YN");
                result.JM_PageControlT1.Toolbar.Insert(index + 1, new Toolbar()
                {
                    display = true,
                    fnKey = "TBD4YN",
                    fnTitle = "发布",
                    fnType = "table",
                    icon = "ghr-publish",
                    position = "left"
                });
                result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                {
                    display = true,
                    fnKey = "TBD6YN",
                    fnTitle = "预览",
                    fnType = "row",
                    icon = "ghr-preview",
                    position = "left"
                });
                result.DT_Procedure.ExportExcel = "/api/Ghre_ExamPaper/ExportExcel/Draft";

                break;
            case "F_ExamPaperReleased":
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "DetailYN").FirstOrDefault();
                if (toolbar != null) { toolbar.fnKey = "TBD3YN"; }
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "CopyYN").FirstOrDefault();
                if (toolbar != null) { toolbar.fnKey = "TBD7YN"; }

                result.JM_PageControlT1.Toolbar.Insert(0, new Toolbar()
                {
                    display = true,
                    fnKey = "TBD4YN",
                    fnTitle = "取消发布",
                    fnType = "table",
                    icon = "ghr-publish",
                    position = "left"
                });
                result.JM_PageControlT1.Toolbar.Insert(1, new Toolbar()
                {
                    display = true,
                    fnKey = "TBD5YN",
                    fnTitle = "停用",
                    fnType = "table",
                    icon = "ghr-icon-stop",
                    position = "left"
                });
                result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                {
                    display = true,
                    fnKey = "TBD6YN",
                    fnTitle = "预览",
                    fnType = "row",
                    icon = "ghr-preview",
                    position = "left"
                });

                result.DT_Procedure.ExportExcel = "/api/Ghre_ExamPaper/ExportExcel/Released";
                break;
            case "F_ExamPaperDisabled":
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "DetailYN").FirstOrDefault();
                if (toolbar != null) { toolbar.fnKey = "TBD3YN"; }

                result.JM_PageControlT1.Toolbar.Insert(0, new Toolbar()
                {
                    display = true,
                    fnKey = "TBD4YN",
                    fnTitle = "启用",
                    fnType = "table",
                    icon = "ghr-icon-start",
                    position = "left"
                });
                result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                {
                    display = true,
                    fnKey = "TBD6YN",
                    fnTitle = "预览",
                    fnType = "row",
                    icon = "ghr-preview",
                    position = "left"
                });
                result.DT_Procedure.ExportExcel = "/api/Ghre_ExamPaper/ExportExcel/Disabled";
                break;
            case "F_Training_CoursewWare":
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "NewYN").FirstOrDefault();
                if (toolbar != null) { toolbar.fnKey = "TBD1YN"; }
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "UpdateYN").FirstOrDefault();
                if (toolbar != null) { toolbar.fnKey = "TBD2YN"; }
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "DetailYN").FirstOrDefault();
                if (toolbar != null) { toolbar.fnKey = "TBD3YN"; }
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "CopyYN").FirstOrDefault();
                if (toolbar != null) { toolbar.fnKey = "TBD4YN"; }

                index = result.JM_PageControlT1.Toolbar.FindIndex(x => x.fnKey == "TBD2YN");
                result.JM_PageControlT1.Toolbar.Insert(index + 1, new Toolbar()
                {
                    display = true,
                    fnKey = "TBD5YN",
                    fnTitle = await QueryLangValue("GHR_Common_000254", "下载"),
                    fnType = "row",
                    icon = "ghr-icon-download",
                    position = "left"
                });

                break;

            case "F_Training_Course_Draft":
                index = result.JM_PageControlT1.Toolbar.FindIndex(x => x.fnKey == "NewYN");
                result.JM_PageControlT1.Toolbar.Insert(index + 1, new Toolbar()
                {
                    display = true,
                    fnKey = "TBD4YN",
                    fnTitle = "发布",
                    fnType = "table",
                    icon = "ghr-publish",
                    position = "left"
                });
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "NewYN").FirstOrDefault();
                if (toolbar != null) { toolbar.fnKey = "TBD1YN"; }
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "UpdateYN").FirstOrDefault();
                if (toolbar != null) { toolbar.fnKey = "TBD2YN"; }
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "CopyYN").FirstOrDefault();
                if (toolbar != null) { toolbar.fnKey = "TBD3YN"; }
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "DetailYN").FirstOrDefault();
                if (toolbar != null) { toolbar.fnKey = "TBD5YN"; }
                result.DT_Procedure.ExportExcel = "/api/Ghre_Course/ExportExcel/Draft";
                break;
            case "F_Training_Course_Released":

                result.JM_PageControlT1.Toolbar.Insert(0, new Toolbar()
                {
                    display = true,
                    fnKey = "TBD4YN",
                    fnTitle = "取消发布",
                    fnType = "table",
                    icon = "ghr-publish",
                    position = "left"
                });
                result.JM_PageControlT1.Toolbar.Insert(1, new Toolbar()
                {
                    display = true,
                    fnKey = "TBD5YN",
                    fnTitle = "停用",
                    fnType = "table",
                    icon = "ghr-icon-stop",
                    position = "left"
                });
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "CopyYN").FirstOrDefault();
                if (toolbar != null) { toolbar.fnKey = "TBD6YN"; }
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "DetailYN").FirstOrDefault();
                if (toolbar != null) { toolbar.fnKey = "TBD7YN"; }
                result.DT_Procedure.ExportExcel = "/api/Ghre_Course/ExportExcel/Released";

                break;
            case "F_Training_Course_Disabled":

                result.JM_PageControlT1.Toolbar.Insert(0, new Toolbar()
                {
                    display = true,
                    fnKey = "TBD5YN",
                    fnTitle = "启用",
                    fnType = "table",
                    icon = "ghr-icon-stop",
                    position = "left"
                });
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "CopyYN").FirstOrDefault();
                if (toolbar != null) { toolbar.fnKey = "TBD6YN"; }
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "DetailYN").FirstOrDefault();
                if (toolbar != null) { toolbar.fnKey = "TBD7YN"; }
                result.DT_Procedure.ExportExcel = "/api/Ghre_Course/ExportExcel/Disabled";

                break;

            //case "F_CourseClassification":
            case "F_CourseScene":
                index = result.JM_PageControlT1.Toolbar.FindIndex(x => x.fnKey == "BatchUpdateYN");
                if (index >= 0)
                    result.JM_PageControlT1.Toolbar.RemoveAt(index);
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "NewYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD1YN";
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "UpdateYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD2YN";
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "DetailYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD3YN";
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "CopyYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD4YN";
                result.JM_PageControlT1.Toolbar.Insert(0, new Toolbar()
                {
                    display = true,
                    fnKey = "TBD4YN",
                    fnTitle = "课程顺序",
                    fnType = "row",
                    icon = "ghr-drag",
                    position = "left"
                });
                break;
            case "F_SchoolManage":
            case "F_WorkLicenseManage":
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "NewYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD1YN";
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "UpdateYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD2YN";
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "DetailYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD3YN";
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "CopyYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD4YN";

                result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                {
                    display = true,
                    fnKey = "TBD5YN",
                    fnTitle = "记录",
                    fnType = "row",
                    icon = "ghr-preview",
                    position = "left"
                });
                break;
            case "F_OnlineExamScores":
                result.DT_Procedure.QueryProcedure = dt.Rows[0]["QueryProcedure"].ToString();
                result.DT_Procedure.QueryProcedure += "/" + param.jsonParam.MasterId;
                result.DT_Procedure.ExportExcel += "/" + param.jsonParam.MasterId;
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "DetailYN").FirstOrDefault();
                if (toolbar != null) { toolbar.fnKey = "TBD3YN"; }

                sql = $@"SELECT A.RoleId, B.RoleNo, B.RoleName
                    FROM Ghrs_UserRole A LEFT JOIN Ghrs_Role B ON A.RoleId = B.RoleId
                    WHERE     A.UserID = {App.User.ID}
                          AND A.IsEnable = 1
                          AND B.IsEnable = 1
                          AND B.RoleNo = 'TrainingExamScore'";
                var toolbarRoles = DbAccess.QueryList<ToolbarRole>(sql);
                if (toolbarRoles != null && toolbarRoles.Any())
                    result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                    {
                        display = true,
                        fnKey = "TBD4YN",
                        fnTitle = "评分",
                        fnType = "row",
                        icon = "ghr-preview",
                        position = "left"
                    });
                break;
            case "F_CreditCheck":
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "DetailYN").FirstOrDefault();
                if (toolbar != null) { toolbar.fnKey = "TBD3YN"; }
                break;
            case "F_RequiredElectiveRules":
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "NewYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD1YN";
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "UpdateYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD2YN";
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "DetailYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD3YN";
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "CopyYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD4YN";
                result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                {
                    display = true,
                    fnKey = "TBD5YN",
                    fnTitle = "结果",
                    fnType = "row",
                    icon = "ghr-preview",
                    position = "left"
                });
                break;

            case "F_ESS_StudyRecord":
                result.DT_Procedure.ExportExcel = "/api/Ghre_StudyRecord/ExportStaffExcel";

                break;

            case "F_Training_Demand_ToDo":
            case "F_TeacherManageTemporary":
            case "F_TeacherChangeTemporary":
            case "F_ManReqMaintenTemporary":
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "NewYN").FirstOrDefault();
                if (toolbar != null) { toolbar.fnKey = "TBD1YN"; }
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "UpdateYN").FirstOrDefault();
                if (toolbar != null) { toolbar.fnKey = "TBD2YN"; }
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "DetailYN").FirstOrDefault();
                if (toolbar != null) { toolbar.fnKey = "TBD3YN"; }
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "CopyYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD4YN";
                index = result.JM_PageControlT1.Toolbar.FindIndex(x => x.fnKey == "TBD1YN");
                result.JM_PageControlT1.Toolbar.Insert(index + 1, new Toolbar()
                {
                    display = true,
                    fnKey = "TBD5YN",
                    fnTitle = await QueryLangValue("F_ManReqMaintenTemporary_TransferToConfirmed", param.langId, "转入待确认"),
                    fnType = "table",
                    icon = "ghr-icon-user-wait",
                    position = "left"
                });
                break;
            case "F_Training_Demand_ToConfirm":
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "NewYN").FirstOrDefault();
                if (toolbar != null) { toolbar.fnKey = "TBD1YN"; }
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "UpdateYN").FirstOrDefault();
                if (toolbar != null) { toolbar.fnKey = "TBD2YN"; }
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "DetailYN").FirstOrDefault();
                if (toolbar != null) { toolbar.fnKey = "TBD3YN"; }
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "CopyYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD4YN";
                result.JM_PageControlT1.Toolbar.Insert(0, new Toolbar()
                {
                    display = true,
                    fnKey = "TBD6YN",
                    fnTitle = await QueryLangValue("F_Training_Demand_ToConfirm_Reject", param.langId, "拒绝"),
                    fnType = "table",
                    icon = "ess-icon-reject",
                    position = "left"
                });
                result.JM_PageControlT1.Toolbar.Insert(0, new Toolbar()
                {
                    display = true,
                    fnKey = "TBD5YN",
                    fnTitle = await QueryLangValue("F_Training_Demand_ToConfirm_Agree", param.langId, "同意"),
                    fnType = "table",
                    icon = "ess-icon-approval",
                    position = "left"
                });
                break;
            case "F_Training_Demand_ToEnable":
            case "F_Training_Demand_Query":
            case "F_Training_Demand_VoidQuery":
            case "F_TeacherManage":
            case "F_TeacherManageActive":
            case "F_TeacherChangeManage":
            case "F_TeacherChangeActive":
            case "F_TeacherDisabled":
            case "F_TeacherChangeDisabled":
            case "F_ManReqMainten":
            case "F_ManReqMaintenActive":
            case "F_ManReqMaintenDisabled":
            case "F_InterviewTranscripts":
            case "F_RecommendRecordForm":
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "NewYN").FirstOrDefault();
                if (toolbar != null) { toolbar.fnKey = "TBD1YN"; }
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "UpdateYN").FirstOrDefault();
                if (toolbar != null) { toolbar.fnKey = "TBD2YN"; }
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "DetailYN").FirstOrDefault();
                if (toolbar != null) { toolbar.fnKey = "TBD3YN"; }
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "CopyYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD4YN";
                break;
            case "F_ManReqMaintenWaitConfirm":
            case "F_TeacherChangeWaitConfirm":
            case "F_TeacherManageWaitConfirm":
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "NewYN").FirstOrDefault();
                if (toolbar != null) { toolbar.fnKey = "TBD1YN"; }
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "UpdateYN").FirstOrDefault();
                if (toolbar != null) { toolbar.fnKey = "TBD2YN"; }
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "DetailYN").FirstOrDefault();
                if (toolbar != null) { toolbar.fnKey = "TBD3YN"; }
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "CopyYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD4YN";
                result.JM_PageControlT1.Toolbar.Insert(0, new Toolbar()
                {
                    display = true,
                    fnKey = "TBD7YN",
                    fnTitle = await QueryLangValue("F_Training_Demand_ToConfirm_Reject", param.langId, "拒绝"),
                    fnType = "table",
                    icon = "ess-icon-reject",
                    position = "left"
                });
                result.JM_PageControlT1.Toolbar.Insert(0, new Toolbar()
                {
                    display = true,
                    fnKey = "TBD6YN",
                    fnTitle = await QueryLangValue("F_Training_Demand_ToConfirm_Agree", param.langId, "同意"),
                    fnType = "table",
                    icon = "ess-icon-approval",
                    position = "left"
                });
                break;

            case "F_ResumeMaintenance_All":

                sql = $@"SELECT A.RoleId, B.RoleNo, B.RoleName
                    FROM Ghrs_UserRole A LEFT JOIN Ghrs_Role B ON A.RoleId = B.RoleId
                    WHERE     A.UserID = {App.User.ID}
                          AND A.IsEnable = 1
                          AND B.IsEnable = 1
                          AND B.RoleNo LIKE 'RecruitResume%'";
                toolbarRoles = DbAccess.QueryList<ToolbarRole>(sql);
                if (toolbarRoles != null && toolbarRoles.Any())
                {
                    if (toolbarRoles.Where(x => x.RoleNo == "RecruitResumeRecommend").Any())
                        result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                        {
                            display = true,
                            fnKey = "TBD5YN",
                            fnTitle = await QueryLangValue("F_ResumeMaintenance_0024", "推荐"),
                            fnType = "row",
                            icon = "ess-icon-reject",
                            position = "left"
                        });
                    if (toolbarRoles.Where(x => x.RoleNo == "RecruitResumeRemind").Any())
                        result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                        {
                            display = true,
                            fnKey = "TBD11YN",
                            fnTitle = await QueryLangValue("F_ResumeMaintenance_0001", "提醒"),
                            fnType = "row",
                            icon = "ess-icon-reject",
                            position = "left"
                        });
                    if (toolbarRoles.Where(x => x.RoleNo == "RecruitResumeScheduleInterview").Any())
                        result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                        {
                            display = true,
                            fnKey = "TBD25YN",
                            fnTitle = await QueryLangValue("F_ResumeMaintenance_0096", "安排面试"),
                            fnType = "row",
                            icon = "ess-icon-reject",
                            position = "left"
                        });
                    result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                    {
                        display = true,
                        fnKey = "TBD26YN",
                        fnTitle = await QueryLangValue("F_ResumeMaintenance_0006", "转入待发offer"),
                        fnType = "row",
                        icon = "ess-icon-reject",
                        position = "left"
                    });
                    if (toolbarRoles.Where(x => x.RoleNo == "RecruitResumeTag").Any())
                        result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                        {
                            display = true,
                            fnKey = "TBD6YN",
                            fnTitle = await QueryLangValue("Table|Ghrh_Resume|Tag", "标签"),
                            fnType = "row",
                            icon = "ess-icon-reject",
                            position = "left"
                        });
                    if (toolbarRoles.Where(x => x.RoleNo == "RecruitResumeRecycle").Any())
                        result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                        {
                            display = true,
                            fnKey = "TBD7YN",
                            fnTitle = await QueryLangValue("F_ResumeMaintenance_0027", "回收"),
                            fnType = "row",
                            icon = "ess-icon-reject",
                            position = "left"
                        });
                    if (toolbarRoles.Where(x => x.RoleNo == "RecruitResumeTalentPool").Any())
                        result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                        {
                            display = true,
                            fnKey = "TBD8YN",
                            fnTitle = await QueryLangValue("F_ResumeMaintenance_0016", "加入人才库"),
                            fnType = "row",
                            icon = "ess-icon-reject",
                            position = "left"
                        });
                    if (toolbarRoles.Where(x => x.RoleNo == "RecruitResumeBlacklist").Any())
                        result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                        {
                            display = true,
                            fnKey = "TBD9YN",
                            fnTitle = await QueryLangValue("F_ResumeMaintenance_0018", "加入黑名单"),
                            fnType = "row",
                            icon = "ess-icon-reject",
                            position = "left"
                        });
                    if (toolbarRoles.Where(x => x.RoleNo == "RecruitResumeDownLoad").Any())
                        result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                        {
                            display = true,
                            fnKey = "TBD10YN",
                            fnTitle = await QueryLangValue("GHR_Common_000254", "下载"),
                            fnType = "row",
                            icon = "ess-icon-reject",
                            position = "left"
                        });
                }
                break;

            case "F_ResumeMaintenance_Process":
                sql = $@"SELECT A.RoleId, B.RoleNo, B.RoleName
                    FROM Ghrs_UserRole A LEFT JOIN Ghrs_Role B ON A.RoleId = B.RoleId
                    WHERE     A.UserID = {App.User.ID}
                          AND A.IsEnable = 1
                          AND B.IsEnable = 1
                          AND B.RoleNo LIKE 'RecruitResume%'";
                toolbarRoles = DbAccess.QueryList<ToolbarRole>(sql);
                if (toolbarRoles != null && toolbarRoles.Any())
                {

                    if (toolbarRoles.Where(x => x.RoleNo == "RecruitResumeProcessRemind").Any())
                        result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                        {
                            display = true,
                            fnKey = "TBD12YN",
                            fnTitle = await QueryLangValue("F_ResumeMaintenance_0001", "提醒"),
                            fnType = "row",
                            icon = "ess-icon-reject",
                            position = "left"
                        });
                    if (toolbarRoles.Where(x => x.RoleNo == "RecruitResumeReScheduleInterview").Any())
                        result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                        {
                            display = true,
                            fnKey = "TBD5YN",
                            fnTitle = await QueryLangValue("F_ResumeMaintenance_0095", "重新推荐"),
                            fnType = "row",
                            icon = "ess-icon-reject",
                            position = "left"
                        });
                    if (toolbarRoles.Where(x => x.RoleNo == "RecruitResumeScheduleInterview").Any())
                    {
                        var name11 = await QueryLangValue("F_ResumeMaintenance_0096", "安排面试");
                        result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                        {
                            display = true,
                            fnKey = "TBD13YN",
                            fnTitle = name11,
                            fnType = "row",
                            icon = "ess-icon-reject",
                            position = "left"
                        });
                        result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                        {
                            display = true,
                            fnKey = "TBD14YN",
                            fnTitle = name11,
                            fnType = "row",
                            icon = "ess-icon-reject",
                            position = "left"
                        });
                        result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                        {
                            display = true,
                            fnKey = "TBD25YN",
                            fnTitle = name11,
                            fnType = "row",
                            icon = "ess-icon-reject",
                            position = "left"
                        });
                    }
                    if (toolbarRoles.Where(x => x.RoleNo == "RecruitResumeApplyOffer").Any())
                        result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                        {
                            display = true,
                            fnKey = "TBD15YN",
                            fnTitle = await QueryLangValue("F_ResumeMaintenance_0097", "发起录用审批"),
                            fnType = "row",
                            icon = "ess-icon-reject",
                            position = "left"
                        });
                    result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                    {
                        display = true,
                        fnKey = "TBD26YN",
                        fnTitle = await QueryLangValue("F_ResumeMaintenance_0006", "转入待发offer"),
                        fnType = "row",
                        icon = "ess-icon-reject",
                        position = "left"
                    });
                    result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                    {
                        display = true,
                        fnKey = "TBD22YN",
                        fnTitle = await QueryLangValue("F_ResumeMaintenance_0098", "评估"),
                        fnType = "row",
                        icon = "ess-icon-reject",
                        position = "left"
                    });
                    if (toolbarRoles.Where(x => x.RoleNo == "RecruitResumeTag").Any())
                        result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                        {
                            display = true,
                            fnKey = "TBD6YN",
                            fnTitle = await QueryLangValue("Table|Ghrh_Resume|Tag", "标签"),
                            fnType = "row",
                            icon = "ess-icon-reject",
                            position = "left"
                        });
                    if (toolbarRoles.Where(x => x.RoleNo == "RecruitResumeRecycle").Any())
                        result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                        {
                            display = true,
                            fnKey = "TBD7YN",
                            fnTitle = await QueryLangValue("F_ResumeMaintenance_0027", "回收"),
                            fnType = "row",
                            icon = "ess-icon-reject",
                            position = "left"
                        });
                    if (toolbarRoles.Where(x => x.RoleNo == "RecruitResumeTalentPool").Any())
                        result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                        {
                            display = true,
                            fnKey = "TBD8YN",
                            fnTitle = await QueryLangValue("F_ResumeMaintenance_0016", "加入人才库"),
                            fnType = "row",
                            icon = "ess-icon-reject",
                            position = "left"
                        });
                    if (toolbarRoles.Where(x => x.RoleNo == "RecruitResumeBlacklist").Any())
                        result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                        {
                            display = true,
                            fnKey = "TBD9YN",
                            fnTitle = await QueryLangValue("F_ResumeMaintenance_0018", "加入黑名单"),
                            fnType = "row",
                            icon = "ess-icon-reject",
                            position = "left"
                        });
                    if (toolbarRoles.Where(x => x.RoleNo == "RecruitResumeDownLoad").Any())
                        result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                        {
                            display = true,
                            fnKey = "TBD10YN",
                            fnTitle = await QueryLangValue("GHR_Common_000254", "下载"),
                            fnType = "row",
                            icon = "ess-icon-reject",
                            position = "left"
                        });
                }
                break;
            case "F_ResumeMaintenance_Hire"://录用
                sql = $@"SELECT A.RoleId, B.RoleNo, B.RoleName
                    FROM Ghrs_UserRole A LEFT JOIN Ghrs_Role B ON A.RoleId = B.RoleId
                    WHERE     A.UserID = {App.User.ID}
                          AND A.IsEnable = 1
                          AND B.IsEnable = 1
                          AND B.RoleNo LIKE 'RecruitResume%'";
                toolbarRoles = DbAccess.QueryList<ToolbarRole>(sql);
                if (toolbarRoles != null && toolbarRoles.Any())
                {

                    if (toolbarRoles.Where(x => x.RoleNo == "RecruitResumeSendOffer").Any())
                        result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                        {
                            display = true,
                            fnKey = "TBD16YN",
                            fnTitle = await QueryLangValue("F_ResumeMaintenance_0025", "发offer"),
                            fnType = "row",
                            icon = "ess-icon-reject",
                            position = "left"
                        });
                    if (toolbarRoles.Where(x => x.RoleNo == "RecruitResumeOfferRemind").Any())
                        result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                        {
                            display = true,
                            fnKey = "TBD17YN",
                            fnTitle = await QueryLangValue("F_ResumeMaintenance_0001", "提醒"),
                            fnType = "row",
                            icon = "ess-icon-reject",
                            position = "left"
                        });
                    if (toolbarRoles.Where(x => x.RoleNo == "RecruitResumeOfferHasWork").Any())
                        result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                        {
                            display = true,
                            fnKey = "TBD18YN",
                            fnTitle = await QueryLangValue("F_ResumeMaintenance_0207", "已报到"),
                            fnType = "row",
                            icon = "ess-icon-reject",
                            position = "left"
                        });
                    if (toolbarRoles.Where(x => x.RoleNo == "RecruitResumeOfferNoWork").Any())
                        result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                        {
                            display = true,
                            fnKey = "TBD19YN",
                            fnTitle = await QueryLangValue("F_ResumeMaintenance_0010", "未报到"),
                            fnType = "row",
                            icon = "ess-icon-reject",
                            position = "left"
                        });

                    if (toolbarRoles.Where(x => x.RoleNo == "RecruitResumeOfferDownLoad").Any())
                        result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                        {
                            display = true,
                            fnKey = "TBD27YN",
                            fnTitle = await QueryLangValue("F_ResumeMaintenance_0010", "F_ResumeMaintenance_0060"),
                            fnType = "row",
                            icon = "ess-icon-reject",
                            position = "left"
                        });
                    if (toolbarRoles.Where(x => x.RoleNo == "RecruitResumeTag").Any())
                        result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                        {
                            display = true,
                            fnKey = "TBD6YN",
                            fnTitle = await QueryLangValue("Table|Ghrh_Resume|Tag", "标签"),
                            fnType = "row",
                            icon = "ess-icon-reject",
                            position = "left"
                        });
                    if (toolbarRoles.Where(x => x.RoleNo == "RecruitResumeRecycle").Any())
                        result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                        {
                            display = true,
                            fnKey = "TBD7YN",
                            fnTitle = await QueryLangValue("F_ResumeMaintenance_0027", "回收"),
                            fnType = "row",
                            icon = "ess-icon-reject",
                            position = "left"
                        });
                    if (toolbarRoles.Where(x => x.RoleNo == "RecruitResumeTalentPool").Any())
                        result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                        {
                            display = true,
                            fnKey = "TBD8YN",
                            fnTitle = await QueryLangValue("F_ResumeMaintenance_0016", "加入人才库"),
                            fnType = "row",
                            icon = "ess-icon-reject",
                            position = "left"
                        });
                    if (toolbarRoles.Where(x => x.RoleNo == "RecruitResumeBlacklist").Any())
                        result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                        {
                            display = true,
                            fnKey = "TBD9YN",
                            fnTitle = await QueryLangValue("F_ResumeMaintenance_0018", "加入黑名单"),
                            fnType = "row",
                            icon = "ess-icon-reject",
                            position = "left"
                        });
                    if (toolbarRoles.Where(x => x.RoleNo == "RecruitResumeDownLoad").Any())
                        result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                        {
                            display = true,
                            fnKey = "TBD10YN",
                            fnTitle = await QueryLangValue("GHR_Common_000254", "下载"),
                            fnType = "row",
                            icon = "ess-icon-reject",
                            position = "left"
                        });
                }
                break;

            case "F_ResumeMaintenance_Talent_Pool"://人才库
                sql = $@"SELECT A.RoleId, B.RoleNo, B.RoleName
                    FROM Ghrs_UserRole A LEFT JOIN Ghrs_Role B ON A.RoleId = B.RoleId
                    WHERE     A.UserID = {App.User.ID}
                          AND A.IsEnable = 1
                          AND B.IsEnable = 1
                          AND B.RoleNo LIKE 'RecruitResume%'";
                toolbarRoles = DbAccess.QueryList<ToolbarRole>(sql);
                if (toolbarRoles != null && toolbarRoles.Any())
                {

                    if (toolbarRoles.Where(x => x.RoleNo == "RecruitResumeRecommend").Any())
                        result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                        {
                            display = true,
                            fnKey = "TBD5YN",
                            fnTitle = await QueryLangValue("F_ResumeMaintenance_0024", "推荐"),
                            fnType = "row",
                            icon = "ess-icon-reject",
                            position = "left"
                        });
                    if (toolbarRoles.Where(x => x.RoleNo == "RecruitResumeTag").Any())
                        result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                        {
                            display = true,
                            fnKey = "TBD6YN",
                            fnTitle = await QueryLangValue("Table|Ghrh_Resume|Tag", "标签"),
                            fnType = "row",
                            icon = "ess-icon-reject",
                            position = "left"
                        });
                    if (toolbarRoles.Where(x => x.RoleNo == "RecruitResumeRecycle").Any())
                        result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                        {
                            display = true,
                            fnKey = "TBD7YN",
                            fnTitle = await QueryLangValue("F_ResumeMaintenance_0027", "回收"),
                            fnType = "row",
                            icon = "ess-icon-reject",
                            position = "left"
                        });
                    if (toolbarRoles.Where(x => x.RoleNo == "RecruitResumeBlacklist").Any())
                        result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                        {
                            display = true,
                            fnKey = "TBD9YN",
                            fnTitle = await QueryLangValue("F_ResumeMaintenance_0018", "加入黑名单"),
                            fnType = "row",
                            icon = "ess-icon-reject",
                            position = "left"
                        });
                    if (toolbarRoles.Where(x => x.RoleNo == "RecruitResumeDownLoad").Any())
                        result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                        {
                            display = true,
                            fnKey = "TBD10YN",
                            fnTitle = await QueryLangValue("GHR_Common_000254", "下载"),
                            fnType = "row",
                            icon = "ess-icon-reject",
                            position = "left"
                        });
                }
                break;
            case "F_ResumeMaintenance_Recycled"://回收站
                sql = $@"SELECT A.RoleId, B.RoleNo, B.RoleName
                    FROM Ghrs_UserRole A LEFT JOIN Ghrs_Role B ON A.RoleId = B.RoleId
                    WHERE     A.UserID = {App.User.ID}
                          AND A.IsEnable = 1
                          AND B.IsEnable = 1
                          AND B.RoleNo LIKE 'RecruitResume%'";
                toolbarRoles = DbAccess.QueryList<ToolbarRole>(sql);
                if (toolbarRoles != null && toolbarRoles.Any())
                {

                    if (toolbarRoles.Where(x => x.RoleNo == "RecruitResumeTag").Any())
                        result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                        {
                            display = true,
                            fnKey = "TBD6YN",
                            fnTitle = await QueryLangValue("Table|Ghrh_Resume|Tag", "标签"),
                            fnType = "row",
                            icon = "ess-icon-reject",
                            position = "left"
                        });
                    if (toolbarRoles.Where(x => x.RoleNo == "RecruitResumeTalentPool").Any())
                        result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                        {
                            display = true,
                            fnKey = "TBD8YN",
                            fnTitle = await QueryLangValue("F_ResumeMaintenance_0016", "加入人才库"),
                            fnType = "row",
                            icon = "ess-icon-reject",
                            position = "left"
                        });
                    if (toolbarRoles.Where(x => x.RoleNo == "RecruitResumeBlacklist").Any())
                        result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                        {
                            display = true,
                            fnKey = "TBD9YN",
                            fnTitle = await QueryLangValue("F_ResumeMaintenance_0018", "加入黑名单"),
                            fnType = "row",
                            icon = "ess-icon-reject",
                            position = "left"
                        });
                    if (toolbarRoles.Where(x => x.RoleNo == "RecruitResumeDownLoad").Any())
                        result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                        {
                            display = true,
                            fnKey = "TBD10YN",
                            fnTitle = await QueryLangValue("GHR_Common_000254", "下载"),
                            fnType = "row",
                            icon = "ess-icon-reject",
                            position = "left"
                        });
                }
                break;
            case "F_ResumeMaintenance_Blacklist"://黑名单
                sql = $@"SELECT A.RoleId, B.RoleNo, B.RoleName
                    FROM Ghrs_UserRole A LEFT JOIN Ghrs_Role B ON A.RoleId = B.RoleId
                    WHERE     A.UserID = {App.User.ID}
                          AND A.IsEnable = 1
                          AND B.IsEnable = 1
                          AND B.RoleNo LIKE 'RecruitResume%'";
                toolbarRoles = DbAccess.QueryList<ToolbarRole>(sql);
                if (toolbarRoles != null && toolbarRoles.Any())
                {

                    if (toolbarRoles.Where(x => x.RoleNo == "RecruitResumeTag").Any())
                        result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                        {
                            display = true,
                            fnKey = "TBD6YN",
                            fnTitle = await QueryLangValue("Table|Ghrh_Resume|Tag", "标签"),
                            fnType = "row",
                            icon = "ess-icon-reject",
                            position = "left"
                        });
                    if (toolbarRoles.Where(x => x.RoleNo == "RecruitResumeTalentPool").Any())
                        result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                        {
                            display = true,
                            fnKey = "TBD8YN",
                            fnTitle = await QueryLangValue("F_ResumeMaintenance_0016", "加入人才库"),
                            fnType = "row",
                            icon = "ess-icon-reject",
                            position = "left"
                        });
                    if (toolbarRoles.Where(x => x.RoleNo == "RecruitResumeRecycle").Any())
                        result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                        {
                            display = true,
                            fnKey = "TBD7YN",
                            fnTitle = await QueryLangValue("F_ResumeMaintenance_0027", "回收"),
                            fnType = "row",
                            icon = "ess-icon-reject",
                            position = "left"
                        });
                    if (toolbarRoles.Where(x => x.RoleNo == "RecruitResumeDownLoad").Any())
                        result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                        {
                            display = true,
                            fnKey = "TBD10YN",
                            fnTitle = await QueryLangValue("GHR_Common_000254", "下载"),
                            fnType = "row",
                            icon = "ess-icon-reject",
                            position = "left"
                        });
                }
                break;
            case "F_ESS_Candidate":// 
                result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                {
                    display = true,
                    fnKey = "TBD20YN",
                    fnTitle = await QueryLangValue("F_ResumeMaintenance_0034", "约面"),
                    fnType = "row",
                    icon = "ess-icon-reject",
                    position = "left"
                });
                result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                {
                    display = true,
                    fnKey = "TBD21YN",
                    fnTitle = await QueryLangValue("F_ResumeMaintenance_0003", "不合适"),
                    fnType = "row",
                    icon = "ess-icon-reject",
                    position = "left"
                });
                break;
            case "F_ESS_Interview":// 
                result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                {
                    display = true,
                    fnKey = "TBD22YN",
                    fnTitle = await QueryLangValue("F_ResumeMaintenance_0098", "评估"),
                    fnType = "row",
                    icon = "ess-icon-reject",
                    position = "left"
                });
                //sql = $@"SELECT A.RoleId, B.RoleNo, B.RoleName
                //    FROM Ghrs_UserRole A LEFT JOIN Ghrs_Role B ON A.RoleId = B.RoleId
                //    WHERE     A.UserID = {App.User.ID}
                //          AND A.IsEnable = 1
                //          AND B.IsEnable = 1
                //          AND B.RoleNo LIKE 'RecruitResume%'";
                //toolbarRoles = DbAccess.QueryList<ToolbarRole>(sql);
                //if (toolbarRoles != null && toolbarRoles.Any())
                //{
                //    if (toolbarRoles.Where(x => x.RoleNo == "RecruitResumeESSChangeDate").Any())
                //        result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                //        {
                //            display = true,
                //            fnKey = "TBD23YN",
                //            fnTitle = "改期",
                //            fnType = "row",
                //            icon = "ess-icon-reject",
                //            position = "left"
                //        });
                //    if (toolbarRoles.Where(x => x.RoleNo == "RecruitResumeESSCancel").Any())
                //        result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                //        {
                //            display = true,
                //            fnKey = "TBD24YN",
                //            fnTitle = "取消",
                //            fnType = "row",
                //            icon = "ess-icon-reject",
                //            position = "left"
                //        });
                //}
                break;
            case "F_OfferTemplate":
            case "F_CreditRule":
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "NewYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD1YN";
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "UpdateYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD2YN";
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "DetailYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD3YN";
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "CopyYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD4YN";
                break;
            case "F_AnnualManpower":

                var config = await Db.Queryable<Ghrh_Config>().Where(x => x.ConfigCode == "ESS_Recruit_Year_Human_Start_Month").FirstAsync();
                var startMonth = config != null ? config.ConfigValue.ObjToInt() : 1;
                var months = new List<string>();
                List<int> numbers = new();
                for (int i = 1; i <= 12; i++)
                {
                    if (i < 10)
                        months.Add("0" + i);
                    else
                        months.Add(i.ObjToString());
                    numbers.Add(i);
                }
                var curentYear = DateTime.Now.Year;
                var curentMonth = DateTime.Now.Month;
                // 指定要打头的数字
                int startNumber = startMonth;


                if (curentMonth < startMonth)
                    curentYear--;
                // 创建一个新的列表用于存储重新排序后的结果
                List<int> reorderedNumbers = new();

                var sort = result.JM_TableColumnT1.TableColumn.Where(x => x.field == "M1").SingleOrDefault()?.SortNo ?? 5;
                var name1 = await QueryLangValue("F_ResumeMaintenance_0216", "预算编制数");
                result.JM_TableColumnT1.TableColumn?.ForEach(x =>
                {
                    if (months.Where(o => o == x.label).Any())
                        x.GroupName = name1;

                    if (x.field == "Year")
                        x.searchColumnDefaultValue = curentYear;
                });

                // 找到指定数字的索引
                int index1 = numbers.IndexOf(startNumber);
                if (index1 != -1)
                {
                    // 从指定数字开始，按照循环顺序添加数字
                    for (int i = 0; i < numbers.Count; i++)
                    {
                        int currentIndex = (index1 + i) % numbers.Count;
                        reorderedNumbers.Add(numbers[currentIndex]);
                    }

                    foreach (var num in reorderedNumbers)
                    {
                        result.JM_TableColumnT1.TableColumn?.ForEach(x =>
                        {
                            if (x.label.ObjToInt() == num)
                            {
                                x.SortNo = sort;
                                x.label = curentYear + "-" + x.label;
                            }
                        });
                        if (num == 12)
                            curentYear++;
                        sort++;
                    }
                }
                result.JM_TableColumnT1.TableColumn = result.JM_TableColumnT1.TableColumn.OrderBy(x => x.SortNo).ToList();

                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "NewYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD1YN";
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "UpdateYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD2YN";
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "DetailYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD3YN";
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "CopyYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD4YN";
                break;

            case "F_InterviewRequestSummary":
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "NewYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD1YN";
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "UpdateYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD2YN";
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "DetailYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD3YN";
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "CopyYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD4YN";

                result.DT_Procedure.ExportExcel = "/api/Ghrh_HumanRequest/ExportSummaryExcel";
                break;
            case "F_InterviewHireList":
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "NewYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD1YN";
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "UpdateYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD2YN";
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "DetailYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD3YN";
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "CopyYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD4YN";

                result.DT_Procedure.ExportExcel = "/api/Ghrh_Resume/ExportHireExcel";
                break;
            case "F_InterviewCompleteStatistical":
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "NewYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD1YN";
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "UpdateYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD2YN";
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "DetailYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD3YN";
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "CopyYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD4YN";

                result.DT_Procedure.ExportExcel = "/api/Ghrh_HumanRequest/ExportCompleteExcel";

                var name2 = await QueryLangValue("F_ResumeMaintenance_0226", "编制内");
                var name3 = await QueryLangValue("F_ResumeMaintenance_0227", "编制外");
                result.JM_TableColumnT1.TableColumn?.ForEach(x =>
                {
                    if (x.label.Contains("编制内"))
                    {
                        x.GroupName = name2;
                        x.label = x.label.Replace("编制内", null);
                    }

                    if (x.label.Contains("编制外"))
                    {
                        x.GroupName = name3;
                        x.label = x.label.Replace("编制外", null);
                    }
                });
                result.JM_TableColumnT1.TableColumn = result.JM_TableColumnT1.TableColumn.OrderBy(x => x.SortNo).ToList();

                break;
            case "F_OpenCLassTemporary":
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "NewYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD1YN";
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "UpdateYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD2YN";
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "DetailYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD3YN";
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "CopyYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD4YN";

                index = result.JM_PageControlT1.Toolbar.FindIndex(x => x.fnKey == "TBD1YN");
                result.JM_PageControlT1.Toolbar.Insert(index + 1, new Toolbar()
                {
                    display = true,
                    fnKey = "TBD5YN",
                    fnTitle = "发布",
                    fnType = "table",
                    icon = "ghr-publish",
                    position = "left"
                });
                break;
            case "F_OpenCLassPublish":
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "NewYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD1YN";
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "UpdateYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD2YN";
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "DetailYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD3YN";
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "CopyYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD4YN";
                index = result.JM_PageControlT1.Toolbar.FindIndex(x => x.fnKey == "TBD1YN");
                result.JM_PageControlT1.Toolbar.Insert(index + 1, new Toolbar()
                {
                    display = true,
                    fnKey = "TBD5YN",
                    fnTitle = "开课",
                    fnType = "table",
                    icon = "ghr-icon-start",
                    position = "left"
                }); result.JM_PageControlT1.Toolbar.Insert(index + 2, new Toolbar()
                {
                    display = true,
                    fnKey = "TBD6YN",
                    fnTitle = "取消发布",
                    fnType = "table",
                    icon = "ghr-clear",
                    position = "left"
                });
                break;
            case "F_OpenCLassOpening":
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "NewYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD1YN";
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "UpdateYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD2YN";
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "DetailYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD3YN";
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "CopyYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD4YN";

                index = result.JM_PageControlT1.Toolbar.FindIndex(x => x.fnKey == "TBD1YN");
                result.JM_PageControlT1.Toolbar.Insert(index + 1, new Toolbar()
                {
                    display = true,
                    fnKey = "TBD5YN",
                    fnTitle = "结案",
                    fnType = "table",
                    icon = "ghr-icon-stop",
                    position = "left"
                });
                result.JM_PageControlT1.Toolbar.Insert(index + 2, new Toolbar()
                {
                    display = true,
                    fnKey = "TBD6YN",
                    fnTitle = "取消开课",
                    fnType = "table",
                    icon = "ghr-clear",
                    position = "left"
                });
                break;
            case "F_OpenCLassClose":
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "NewYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD1YN";
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "UpdateYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD2YN";
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "DetailYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD3YN";
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "CopyYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD4YN";

                index = result.JM_PageControlT1.Toolbar.FindIndex(x => x.fnKey == "TBD1YN");
                result.JM_PageControlT1.Toolbar.Insert(index + 1, new Toolbar()
                {
                    display = true,
                    fnKey = "TBD5YN",
                    fnTitle = "取消结案",
                    fnType = "table",
                    icon = "ghr-clear",
                    position = "left"
                });
                break;
            case "F_StaffGroup":
                result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                {
                    display = true,
                    fnKey = "TBD5YN",
                    fnTitle = "人员",
                    fnType = "row",
                    icon = "ghr-preview",
                    position = "left"
                });
                break;

            //case "F_TrainPlan_Temporary":
            //    sql = $@"SELECT A.RoleId, B.RoleNo, B.RoleName
            //        FROM Ghrs_UserRole A LEFT JOIN Ghrs_Role B ON A.RoleId = B.RoleId
            //        WHERE     A.UserID = {App.User.ID}
            //              AND A.IsEnable = 1
            //              AND B.IsEnable = 1
            //              AND B.RoleNo = 'F_TrainPlanTransferToConfirmed'";
            //    toolbarRoles = DbAccess.QueryList<ToolbarRole>(sql);
            //    if (toolbarRoles != null && toolbarRoles.Any())
            //    {
            //        index = result.JM_PageControlT1.Toolbar.FindIndex(x => x.fnKey == "NewYN");
            //        result.JM_PageControlT1.Toolbar.Insert(index + 1, new Toolbar()
            //        {
            //            display = true,
            //            fnKey = "TBD5YN",
            //            fnTitle = await QueryLangValue("F_ManReqMaintenTemporary_TransferToConfirmed", param.langId, "转入待确认"),
            //            fnType = "table",
            //            icon = "ghr-icon-user-wait",
            //            position = "left"
            //        });
            //    }
            //    break;
            //case "F_TrainPlan_WaitConfirm":
            //    result.JM_PageControlT1.Toolbar.Insert(0, new Toolbar()
            //    {
            //        display = true,
            //        fnKey = "TBD7YN",
            //        fnTitle = await QueryLangValue("F_Training_Demand_ToConfirm_Reject", param.langId, "拒绝"),
            //        fnType = "table",
            //        icon = "ess-icon-reject",
            //        position = "left"
            //    });
            //    result.JM_PageControlT1.Toolbar.Insert(0, new Toolbar()
            //    {
            //        display = true,
            //        fnKey = "TBD6YN",
            //        fnTitle = await QueryLangValue("F_Training_Demand_ToConfirm_Agree", param.langId, "同意"),
            //        fnType = "table",
            //        icon = "ess-icon-approval",
            //        position = "left"
            //    });
            //    break;

            case "F_TrainPlan_Wait":
            case "F_TrainPlan_Active":
            case "F_TrainPlan_Disable":
            case "F_TrainPlan_Temporary":
            case "F_TrainPlan_WaitConfirm":
            case "F_UshioTrainPlan_Wait":
            case "F_UshioTrainPlan_Active":
            case "F_UshioTrainPlan_Disable":
            case "F_UshioTrainPlan_Temporary":
            case "F_UshioTrainPlan_WaitConfirm":

                config = await Db.Queryable<Ghrh_Config>().Where(x => x.ConfigCode == "ESS_Recruit_Year_Human_Start_Month").FirstAsync();
                startMonth = config != null ? config.ConfigValue.ObjToInt() : 1;
                months = new List<string>();
                numbers = new();
                for (int i = 1; i <= 12; i++)
                {
                    if (i < 10)
                        months.Add("0" + i);
                    else
                        months.Add(i.ObjToString());
                    numbers.Add(i);
                }
                curentYear = DateTime.Now.Year;
                curentMonth = DateTime.Now.Month;
                // 指定要打头的数字
                startNumber = startMonth;


                if (curentMonth < startMonth)
                    curentYear--;
                // 创建一个新的列表用于存储重新排序后的结果
                reorderedNumbers = new();

                sort = result.JM_TableColumnT1.TableColumn.Where(x => x.field == "M1").SingleOrDefault()?.SortNo ?? 5;
                name1 = "计划年月";
                result.JM_TableColumnT1.TableColumn?.ForEach(x =>
                {
                    if (months.Where(o => o == x.label).Any())
                        x.GroupName = name1;

                    if (x.field == "Year")
                        x.searchColumnDefaultValue = curentYear;
                });

                // 找到指定数字的索引
                index1 = numbers.IndexOf(startNumber);
                if (index1 != -1)
                {
                    // 从指定数字开始，按照循环顺序添加数字
                    for (int i = 0; i < numbers.Count; i++)
                    {
                        int currentIndex = (index1 + i) % numbers.Count;
                        reorderedNumbers.Add(numbers[currentIndex]);
                    }

                    foreach (var num in reorderedNumbers)
                    {
                        result.JM_TableColumnT1.TableColumn?.ForEach(x =>
                        {
                            if (x.label.ObjToInt() == num)
                            {
                                x.SortNo = sort;
                                x.label = curentYear + "-" + x.label;
                            }
                        });
                        if (num == 12)
                            curentYear++;
                        sort++;
                    }
                }
                result.JM_TableColumnT1.TableColumn = result.JM_TableColumnT1.TableColumn.OrderBy(x => x.SortNo).ToList();

                if (param.menuName == "F_UshioTrainPlan_WaitConfirm" || param.menuName == "F_TrainPlan_WaitConfirm")
                {

                    result.JM_PageControlT1.Toolbar.Insert(0, new Toolbar()
                    {
                        display = true,
                        fnKey = "TBDDoReject",
                        fnTitle = await QueryLangValue("F_Training_Demand_ToConfirm_Reject", param.langId, "拒绝"),
                        fnType = "table",
                        icon = "ess-icon-reject",
                        position = "left"
                    });
                    result.JM_PageControlT1.Toolbar.Insert(0, new Toolbar()
                    {
                        display = true,
                        fnKey = "TBDDoAgree",
                        fnTitle = await QueryLangValue("F_Training_Demand_ToConfirm_Agree", param.langId, "同意"),
                        fnType = "table",
                        icon = "ess-icon-approval",
                        position = "left"
                    });
                }
                else if (param.menuName == "F_UshioTrainPlan_Temporary" || param.menuName == "F_TrainPlan_Temporary")
                {
                    sql = $@"SELECT A.RoleId, B.RoleNo, B.RoleName
                    FROM Ghrs_UserRole A LEFT JOIN Ghrs_Role B ON A.RoleId = B.RoleId
                    WHERE     A.UserID = {App.User.ID}
                          AND A.IsEnable = 1
                          AND B.IsEnable = 1
                          AND B.RoleNo = 'F_TrainPlanTransferToConfirmed'";
                    toolbarRoles = DbAccess.QueryList<ToolbarRole>(sql);
                    if (toolbarRoles != null && toolbarRoles.Any())
                    {
                        index = result.JM_PageControlT1.Toolbar.FindIndex(x => x.fnKey == "NewYN");
                        result.JM_PageControlT1.Toolbar.Insert(index + 1, new Toolbar()
                        {
                            display = true,
                            fnKey = "TBDToConfirm",
                            fnTitle = await QueryLangValue("F_ManReqMaintenTemporary_TransferToConfirmed", param.langId, "转入待确认"),
                            fnType = "table",
                            icon = "ghr-icon-user-wait",
                            position = "left"
                        });
                    }
                }
                break;
            case "F_TrainSurvey_Publish":
            case "F_TrainSurvey_Temporary":
            case "F_TrainSurvey_Disable":
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "NewYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD1YN";
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "UpdateYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD2YN";
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "DetailYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD3YN";
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "CopyYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD4YN";

                break;
            case "F_UshioTrainPlanReport":

                config = await Db.Queryable<Ghrh_Config>().Where(x => x.ConfigCode == "ESS_Recruit_Year_Human_Start_Month").FirstAsync();
                startMonth = config != null ? config.ConfigValue.ObjToInt() : 1;
                months = new List<string>();
                numbers = new();
                for (int i = 1; i <= 12; i++)
                {
                    if (i < 10)
                        months.Add("0" + i);
                    else
                        months.Add(i.ObjToString());
                    numbers.Add(i);
                }
                curentYear = DateTime.Now.Year;
                curentMonth = DateTime.Now.Month;
                // 指定要打头的数字
                startNumber = startMonth;


                if (curentMonth < startMonth)
                    curentYear--;
                // 创建一个新的列表用于存储重新排序后的结果
                reorderedNumbers = new();

                sort = result.JM_TableColumnT1.TableColumn.Where(x => x.field == "M1_Count").SingleOrDefault()?.SortNo ?? 5;
                name1 = "计划年月";
                result.JM_TableColumnT1.TableColumn?.ForEach(x =>
                {

                    for (int i = 1; i < 13; i++)
                    {
                        if (x.label.Contains(i.ObjToString()))
                        {
                            if (x.label == $"实际合计人天{i}" || x.label == $"进展率{i}")
                            {
                                x.label = x.label.Replace($"实际合计人天{i}", "实际合计人天");
                                x.label = x.label.Replace($"进展率{i}", "进展率");

                            }
                            x.GroupName = i + "月";
                        }
                    }
                    if (x.field == "Year")
                        x.searchColumnDefaultValue = curentYear;
                });

                // 找到指定数字的索引
                index1 = numbers.IndexOf(startNumber);
                if (index1 != -1)
                {
                    // 从指定数字开始，按照循环顺序添加数字
                    for (int i = 0; i < numbers.Count; i++)
                    {
                        int currentIndex = (index1 + i) % numbers.Count;
                        reorderedNumbers.Add(numbers[currentIndex]);
                    }

                    foreach (var num in reorderedNumbers)
                    {
                        result.JM_TableColumnT1.TableColumn?.ForEach(x =>
                        {
                            if (x.label == "实际合计人天" && x.GroupName == num + "月")
                                x.SortNo = sort;
                            if (x.label == "进展率" && x.GroupName == num + "月")
                                x.SortNo = sort + 1;

                        });
                        if (num == 12)
                            curentYear++;
                        sort = sort + 2;
                    }
                }
                result.JM_TableColumnT1.TableColumn = result.JM_TableColumnT1.TableColumn.OrderBy(x => x.SortNo).ToList();

                if (param.menuName == "F_UshioTrainPlan_WaitConfirm" || param.menuName == "F_TrainPlan_WaitConfirm")
                {

                    result.JM_PageControlT1.Toolbar.Insert(0, new Toolbar()
                    {
                        display = true,
                        fnKey = "TBDDoReject",
                        fnTitle = await QueryLangValue("F_Training_Demand_ToConfirm_Reject", param.langId, "拒绝"),
                        fnType = "table",
                        icon = "ess-icon-reject",
                        position = "left"
                    });
                    result.JM_PageControlT1.Toolbar.Insert(0, new Toolbar()
                    {
                        display = true,
                        fnKey = "TBDDoAgree",
                        fnTitle = await QueryLangValue("F_Training_Demand_ToConfirm_Agree", param.langId, "同意"),
                        fnType = "table",
                        icon = "ess-icon-approval",
                        position = "left"
                    });
                }
                else if (param.menuName == "F_UshioTrainPlan_Temporary" || param.menuName == "F_TrainPlan_Temporary")
                {
                    sql = $@"SELECT A.RoleId, B.RoleNo, B.RoleName
                    FROM Ghrs_UserRole A LEFT JOIN Ghrs_Role B ON A.RoleId = B.RoleId
                    WHERE     A.UserID = {App.User.ID}
                          AND A.IsEnable = 1
                          AND B.IsEnable = 1
                          AND B.RoleNo = 'F_TrainPlanTransferToConfirmed'";
                    toolbarRoles = DbAccess.QueryList<ToolbarRole>(sql);
                    if (toolbarRoles != null && toolbarRoles.Any())
                    {
                        index = result.JM_PageControlT1.Toolbar.FindIndex(x => x.fnKey == "NewYN");
                        result.JM_PageControlT1.Toolbar.Insert(index + 1, new Toolbar()
                        {
                            display = true,
                            fnKey = "TBDToConfirm",
                            fnTitle = await QueryLangValue("F_ManReqMaintenTemporary_TransferToConfirmed", param.langId, "转入待确认"),
                            fnType = "table",
                            icon = "ghr-icon-user-wait",
                            position = "left"
                        });
                    }
                }
                break;

            case "F_TitleSkillMatrix":

                var column = result.JM_TableColumnT1.TableColumn.Where(x => x.field == "Title_A01").SingleOrDefault();
                sort = column.SortNo;
                result.JM_TableColumnT1.TableColumn = result.JM_TableColumnT1.TableColumn.Where(x => x.field != "Title_A01").ToList();
                var titles = await Db.Queryable<Ghra_Title>().OrderBy(x => x.SortNo).ToListAsync();
                if (param.jsonParam1 != null)
                    foreach (JProperty jProperty in param.jsonParam1.Properties())
                    {
                        var name = jProperty.Name;
                        var value = jProperty.Value.ToString();
                        if (name == "page" || name == "pageSize")
                            continue;
                        if (value.IsNotEmptyOrNull())
                        {
                            var jsonParam = JsonHelper.JsonToObj<JsonParam>(value);

                            switch (name)
                            {
                                case "TitleId":
                                    switch (jsonParam.operationKey)
                                    {
                                        case "Equal":
                                            if (jsonParam.columnValue != null)
                                                titles = titles.Where(x => x.TitleID == jsonParam.columnValue.ObjToInt()).ToList();
                                            break;
                                        case "NotEqual":
                                            if (jsonParam.columnValue != null)
                                                titles = titles.Where(x => x.TitleID != jsonParam.columnValue.ObjToInt()).ToList();
                                            break;
                                        default:
                                            break;
                                    }
                                    break;

                                default:
                                    break;
                            }
                        }
                    }
                index = 0;
                titles.ForEach(x =>
                {
                    var copyColumn = Mapper.Map(column).ToANew<TableColumn>();
                    copyColumn.field = "Title_" + x.TitleNo;
                    copyColumn.label = x.TitleName;
                    result.JM_TableColumnT1.TableColumn.Insert(index + sort, copyColumn);
                    index++;
                });
                break;

            case "F_TrainingDemandStatistics_Year":
            case "F_TrainingDemandStatistics_Month":
                if (!string.IsNullOrWhiteSpace(result.DT_Procedure.EditProcedure))
                    result.DT_Procedure.ExportExcel = result.DT_Procedure.EditProcedure.Replace("QueryGroupForm", "ExportGroupExcel");

                break;
            case "F_PerformancePeriodType":
            case "F_GhraStaffGroup":
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "NewYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD1YN";
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "UpdateYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD2YN";
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "DetailYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD3YN";
                toolbar = result.JM_PageControlT1.Toolbar.Where(x => x.fnKey == "CopyYN").FirstOrDefault();
                if (toolbar != null) toolbar.fnKey = "TBD4YN";

                if (param.menuName == "F_GhraStaffGroup")
                    result.JM_PageControlT1.Toolbar.Add(new Toolbar()
                    {
                        display = true,
                        fnKey = "TBD5YN",
                        fnTitle = "人员",
                        fnType = "row",
                        icon = "ghr-preview",
                        position = "left"
                    });

                break;
            case "F_PerformancePeriod":
                result.JM_PageControlT1.Toolbar.Insert(0, new Toolbar()
                {
                    display = true,
                    fnKey = "TBD1YN",
                    fnTitle = "考核期间展开",
                    fnType = "table",
                    icon = "ghr-batch-update",
                    position = "left"
                });
                break;
        }

        #endregion

        result.DT_PageMutiMsg = await _caching.GetAsync<List<DT_PageMutiMsg>>(param.menuName + "_DT_PageMutiMsg");

        #region 多语返回处理
        if (param.menuName == "F_ResumeMaintenance_All" ||
            param.menuName == "F_ResumeMaintenance_Process" ||
            param.menuName == "F_ResumeMaintenance_Hire" ||
            param.menuName == "F_ResumeMaintenance_Talent_Pool" ||
            param.menuName == "F_ResumeMaintenance_Recycled" ||
            param.menuName == "F_ResumeMaintenance_Blacklist" ||
            param.menuName == "F_ESS_Candidate" ||
            param.menuName == "F_ESS_Interview" ||
            param.menuName == "F_ESS_Hire" ||
            param.menuName == "F_ResumeMaintenance_Talent_Pool")
        {

            sqlLang = @"SELECT Langkey field,
                       CASE {2}
                          WHEN 1 THEN isnull (Value01, LangValue)
                          WHEN 2 THEN isnull (Value02, LangValue)
                          WHEN 3 THEN isnull (Value03, LangValue)
                          WHEN 4 THEN isnull (Value04, LangValue)
                          WHEN 5 THEN isnull (Value05, LangValue)
                          WHEN 6 THEN isnull (Value06, LangValue)
                          WHEN 7 THEN isnull (Value07, LangValue)
                          WHEN 8 THEN isnull (Value08, LangValue)
                          WHEN 9 THEN isnull (Value09, LangValue)
                          WHEN 10 THEN isnull (Value10, LangValue)
                       END label
                FROM Ghrs_LangKey
                WHERE     IsEnable = 1
                      AND (LangKey LIKE 'F_ResumeMaintenance_%')";
            sqlLang = string.Format(sqlLang, param.menuName, App.User.ID, param.langId);
        }
        #endregion

        if (result.DT_PageMutiMsg is null)
        {
            result.DT_PageMutiMsg = Db.Ado.SqlQuery<DT_PageMutiMsg>(sqlLang);
            await _caching.SetAsync(param.menuName + "_DT_PageMutiMsg", result.DT_PageMutiMsg, TimeSpan.FromMinutes(5));
        }

        return new ServiceResult<ModuleReturn>() { Success = true, Message = "查询成功", Data = result, };
    }

    /// <summary>
    /// 获取模块信息
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<ServiceResult<ModuleESSReturn>> GetESSModuleInfoAsync([FromBody] ModuleParam param)
    {
        var result = new ModuleESSReturn();

        var result1 = await GetModuleInfoAsync(param);
        result.JM_PageControlT1 = result1.Data.JM_PageControlT1;
        result.DT_TableColumnT1 = result1.Data.JM_TableColumnT1.TableColumn;
        result.DT_PageMutiMsg = result1.Data.DT_PageMutiMsg;
        result.DT_Procedure = result1.Data.DT_Procedure;
        result.DT_TableDataSearchT1 = result.DT_TableColumnT1.ToList();

        result.DT_TableDataSearchT1 = result.DT_TableDataSearchT1.OrderBy(x => x.searchColumnSeq).Where(x => x.searchable == true).ToList();

        result.DT_TableDataSearchT1.ForEach(x =>
        {
            if (x.searchOperator != null && x.searchOperator.Where(o => o.@operator == "Range").Any())
                x.IsRange = 1;
        });
        return new ServiceResult<ModuleESSReturn>() { Success = true, Message = "查询成功", Data = result, };
    }
    #endregion

    #region 获取通用列表下拉
    /// <summary>
    /// 获取通用列表下拉
    /// </summary>
    /// <param name="type"></param>
    /// <returns></returns>
    public async Task<ServiceResult<CommonSelect>> GetSelectAsync(string type, string keyWords)
    {
        var result = new CommonSelect();
        JArray TableColumn = new JArray();
        JArray DT_TablePageInfoT1 = new JArray();
        JArray DT_TableDataT1 = new JArray();
        JObject searchItem = new JObject();
        JObject item;
        DataTable dt;
        string sql;
        switch (type)
        {
            case "Ghre_Course":
                searchItem = new JObject
                {
                    new JProperty("defaultHidden", true),
                    new JProperty("field","value"),
                    new JProperty("label","课程ID"),
                };
                TableColumn.Add(searchItem);
                searchItem = new JObject
                {
                    new JProperty("field","label"),
                    new JProperty("label","课程编号"),
                };
                TableColumn.Add(searchItem);

                sql = $"SELECT Id, CourseNo, CourseName FROM Ghre_Course WHERE IsEnable=1 AND Status='Released' AND dbo.FUserDataBelongPriv ({App.User.ID}, DataBelongID, NULL) = 1";
                if (!string.IsNullOrWhiteSpace(keyWords))
                    sql += $"AND ( CourseNo like '%{keyWords}%' or CourseName like '%{keyWords}%')";
                dt = await Db.Ado.GetDataTableAsync(sql);

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    item = new JObject {
                        new JProperty("value",long.Parse(dt.Rows[i]["Id"].ToString())),
                        new JProperty("label",dt.Rows[i]["CourseNo"].ToString()+"-"+dt.Rows[i]["CourseName"].ToString())
                  };
                    DT_TableDataT1.Add(item);
                }

                item = new JObject
                {
                    new JProperty("ListMax",100),
                    new JProperty("ListMin",10),
                    new JProperty("PageNum",1),
                    new JProperty("PageSize",99999),
                    new JProperty("TotalCount",dt.Rows.Count),
                    new JProperty("UIType","Auto")
                 };
                DT_TablePageInfoT1.Add(item);
                break;
            case "Ghre_CourseScene":
                searchItem = new JObject
                {
                    new JProperty("defaultHidden", true),
                    new JProperty("field","value"),
                    new JProperty("label","场景ID"),
                };
                TableColumn.Add(searchItem);
                searchItem = new JObject
                {
                    new JProperty("field","label"),
                    new JProperty("label","场景"),
               };
                TableColumn.Add(searchItem);

                sql = $"SELECT Id, SceneNo, SceneName FROM Ghre_CourseScene  WHERE IsEnable=1 AND dbo.FUserDataBelongPriv ({App.User.ID}, DataBelongID, NULL) = 1";
                if (!string.IsNullOrWhiteSpace(keyWords))
                    sql += $"AND ( SceneNo like '%{keyWords}%' or SceneName like '%{keyWords}%')";
                dt = await Db.Ado.GetDataTableAsync(sql);

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    item = new JObject
                    {
                        new JProperty("value",long.Parse(dt.Rows[i]["Id"].ToString())),
                        new JProperty("label",dt.Rows[i]["SceneNo"].ToString()+"-"+dt.Rows[i]["SceneName"].ToString())
                    };
                    DT_TableDataT1.Add(item);
                }

                item = new JObject
                {
                    new JProperty("ListMax",100),
                    new JProperty("ListMin",10),
                    new JProperty("PageNum",1),
                    new JProperty("PageSize",99999),
                    new JProperty("TotalCount",dt.Rows.Count),
                    new JProperty("UIType","Auto")
                };
                DT_TablePageInfoT1.Add(item);
                break;
            case "ScoreMethod":
                searchItem = new JObject {
                    new JProperty("defaultHidden", true),
                    new JProperty("field","value"),
                    new JProperty("label","value")
                };
                TableColumn.Add(searchItem);
                searchItem = new JObject
                {
                    new JProperty("field","label"),
                    new JProperty("label","label")
                };
                TableColumn.Add(searchItem);
                item = new JObject {
                    new JProperty("value","Manual"),
                    new JProperty("label","人工评分")
                };
                DT_TableDataT1.Add(item);
                item = new JObject {
                    new JProperty("value","System"),
                    new JProperty("label","系统评分")
                    };
                DT_TableDataT1.Add(item);

                item = new JObject
                {
                    new JProperty("ListMax",100),
                    new JProperty("ListMin",10),
                    new JProperty("PageNum",1),
                    new JProperty("PageSize",99999),
                    new JProperty("TotalCount",2),
                    new JProperty("UIType","Auto")
                };
                DT_TablePageInfoT1.Add(item);
                break;
            case "DifficultyLevel":
                searchItem = new JObject {
                    new JProperty("defaultHidden", true),
                    new JProperty("field","value"),
                    new JProperty("label","value")
                };
                TableColumn.Add(searchItem);
                searchItem = new JObject {
                    new JProperty("field","label"),
                    new JProperty("label","label")
                };
                TableColumn.Add(searchItem);
                item = new JObject {
                    new JProperty("value","Easy"),
                    new JProperty("label","简单")
                };
                DT_TableDataT1.Add(item);
                item = new JObject {
                    new JProperty("value","Normal"),
                    new JProperty("label","普通")
                };
                DT_TableDataT1.Add(item);
                item = new JObject {
                    new JProperty("value","Hard"),
                    new JProperty("label","困难")
                };
                DT_TableDataT1.Add(item);

                item = new JObject {
                    new JProperty("ListMax",100),
                    new JProperty("ListMin",10),
                    new JProperty("PageNum",1),
                    new JProperty("PageSize",99999),
                    new JProperty("TotalCount",3),
                    new JProperty("UIType","Auto")
                };
                DT_TablePageInfoT1.Add(item);
                break;
            case "QuestionType":
                searchItem = new JObject {
                    new JProperty("defaultHidden", true),
                    new JProperty("field","value"),
                    new JProperty("label","value")
               };
                TableColumn.Add(searchItem);
                searchItem = new JObject {
                    new JProperty("field","label"),
                    new JProperty("label","label")
                    };
                TableColumn.Add(searchItem);
                item = new JObject {
                    new JProperty("value","Single"),
                    new JProperty("label","单选题")
                  };
                DT_TableDataT1.Add(item);
                item = new JObject {
                    new JProperty("value","Multiple"),
                    new JProperty("label","多选题")
                    };
                DT_TableDataT1.Add(item);
                item = new JObject {
                    new JProperty("value","TrueOrFalse"),
                    new JProperty("label","判断题")
                    };
                DT_TableDataT1.Add(item);
                item = new JObject {
                    new JProperty("value","Completion"),
                    new JProperty("label","填空题")
                    };
                DT_TableDataT1.Add(item);
                item = new JObject {
                    new JProperty("value","ShortAnswer"),
                    new JProperty("label","简答题")
                };
                DT_TableDataT1.Add(item);

                item = new JObject {
                    new JProperty("ListMax",100),
                    new JProperty("ListMin",10),
                    new JProperty("PageNum",1),
                    new JProperty("PageSize",99999),
                    new JProperty("TotalCount",5),
                    new JProperty("UIType","Auto")
                };
                DT_TablePageInfoT1.Add(item);
                break;
        }
        result.JM_TableColumnT1.TableColumn = TableColumn;
        result.DT_TableDataT1 = DT_TableDataT1;
        result.DT_TablePageInfoT1 = DT_TablePageInfoT1;
        return new ServiceResult<CommonSelect>() { Success = true, Message = "查询成功", Data = result, };
    }
    #endregion

    #region Excel导出
    /// <summary>
    /// Excel导出
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<ServiceResult<QueryExportReturn>> ExportExcelAsync(QueryExport param)
    {
        var result = new QueryExportReturn();

        var tableNmae = string.Empty;
        string sql = "select QueryProcedure, EditProcedure, IUDProcedure from Ghrs_Menu where MenuNo='{0}'";
        sql = string.Format(sql, param.menuName);
        var dt = await Db.Ado.GetDataTableAsync(sql);
        if (dt.Rows.Count > 0)
        {
            string queryProcedure = dt.Rows[0]["QueryProcedure"].ToString();

            string[] aaa = queryProcedure.Split('/');
            tableNmae = aaa[1];
        }

        sql = $@"SELECT Row_Number ()
                              OVER (ORDER BY CONVERT (INT, rowNum), CONVERT (INT, colNum))
                              sortNum,
                           field,
                           [dbo].[FLangKeyToValue] (mkey, 1, label)
                              label,
                           dbo.FS_GetdataSourceBySet
                           (dataSource, APIDataSourceType, Ghrs_PageSettingEdit.APIDataSourceID)
                              dataSource,
                           required,
                           dataType,
                           CONVERT (NVARCHAR (1000), '')
                              commentText                                             -- StaffWith
                                         ,
                             elementType
                           + CASE WHEN multipleSelect = 'true' THEN '_multiple' ELSE '' END
                              elementType                                                -- 增加多选判断
                    FROM Ghrs_PageSettingEdit
                    WHERE     IsEnable = 1
                          AND elementType NOT IN ('FnKey', 'PageGroup')
                          AND pageNo = 'F_Training_Course'
                          --and editable = 'true'
                          AND defaultHidden ! = 'true'
                          AND elementType ! = 'FileUpload'
                          AND dataType ! = ''";

        var columns = await Db.Ado.SqlQueryAsync<QueryExportColumn>(sql);
        columns = columns.WhereIF(param.exportSet.ExFields.Any(), x => param.exportSet.ExFields.Contains(x.field)).ToList();

        dt = await Db.Ado.GetDataTableAsync("SELECT * FROM " + tableNmae + " WHERE IsEnable=1");

        // 获取所有列名
        var dtColumns = dt.Columns;

        var convertColumns = columns.Where(x => !string.IsNullOrEmpty(x.dataSource) && !string.IsNullOrEmpty(x.elementType)).ToList();
        for (int i = 0; i < convertColumns.Count; i++)
        {
            dt.Columns.Add(convertColumns[i].field + "1", typeof(string));
            //var values = dt.AsEnumerable().Select(row => row.Field<string>(column.field)).Distinct().ToList();
            sql = $@"SELECT SelectSql from Ghrs_ListCommonSql WHERE ListCommonSqlNo=REPLACE('{convertColumns[i].dataSource}','CommonList_','')  and IsEnable=1 ";

            sql = await Db.Ado.GetScalarAsync(sql) as string;
            sql = sql.Replace("{@KeyWords}", null);
            var dtSelect = await Db.Ado.SqlQueryAsync<CommonSelectItem>(sql);

            foreach (DataColumn column in dtColumns)
            {
                if (column.ColumnName == convertColumns[i].field)
                    for (int j = 0; j < dt.Rows.Count; j++)
                        dt.Rows[j][column.ColumnName + "1"] = dtSelect.FirstOrDefault(x => x.value == dt.Rows[j][column.ColumnName].ToString())?.label;
            }
        }
        var fieldDescs = columns.ToDictionary(item => item.label, item => convertColumns.Any(x => x.field == item.field) ? item.field + "1" : item.field);


        //var fileId = await ReportHelper.SendFile(dt, param.exportSet.TitleName, fieldDescs, null, null, null);

        return new ServiceResult<QueryExportReturn>() { Success = true, Message = "查询成功", Data = result, };
    }
    #endregion 

    #region Excel数据导入

    public async Task<ServiceResult<QueryExportReturn>> ImportExcelAsync(IFormFile file, string menuName, int langId, int userId)
    {
        var fid = SnowFlakeSingle.Instance.NextId();
        var path = $"{$"{Environment.CurrentDirectory}{Path.DirectorySeparatorChar}wwwroot{Path.DirectorySeparatorChar}files{Path.DirectorySeparatorChar}upload{Path.DirectorySeparatorChar}{fid}{Path.DirectorySeparatorChar}"}";
        if (!Directory.Exists(path))
            Directory.CreateDirectory(path);
        using (var stream = new FileStream(path + file.FileName, FileMode.Create))
        {
            await file.CopyToAsync(stream);
        }

        var result = new QueryExportReturn();

        await ReportHelper.ExcelToDataTable(Db, path, menuName, langId, userId);
        return new ServiceResult<QueryExportReturn>() { Success = true, Message = "查询成功", Data = result, };
    }
    #endregion

    #region 获取流程信息
    /// <summary>
    /// 获取流程信息
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<ServiceResult<FlowReturn>> GetFlowInfoAsync(FlowParam param)
    {
        var flowReturn = new FlowReturn();




        #region JM_PageFormT1
        var sql = $@"DECLARE
                   @SQL      NVARCHAR (MAX) = '',
                   @DoType   NVARCHAR (MAX) = '{param.doType}'

                BEGIN
                   SET @SQL =
                          [dbo].[Fs_UserMenuFnKeyPriv2] ({param.langId},
                                                         {param.userId},
                                                         '{param.menuName}',
                                                         9)
                   SET @SQL =
                          replace (@SQL,
                                   '""layout"":""horizontal""',
                                     '""layout"":""horizontal"",""FlowPageStyle"":""'
                                   + (SELECT isnull (FlowPageStyle, 'All')
                                      FROM Ghrw_Flow
                                      WHERE FlowID = {param.jsonParam.FlowID})
                                   + '""')
                   SET @SQL =
                          replace
                          (@SQL,
                           '<DoTypeTrueOrFalse>',
                           CASE WHEN @DoType = 'Query' THEN 'true' ELSE +'""false""' END)

                   EXECUTE (@SQL)
                END";
        var result = await Db.Ado.GetStringAsync(sql);

        flowReturn.JM_PageFormT1.PageForm = JsonHelper.JsonToObj<List<PageForm>>(result);
        #endregion

        #region DT_PageMutiMsg

        sql = @"SELECT Langkey field,
                       CASE {2}
                          WHEN 1 THEN isnull (Value01, LangValue)
                          WHEN 2 THEN isnull (Value02, LangValue)
                          WHEN 3 THEN isnull (Value03, LangValue)
                          WHEN 4 THEN isnull (Value04, LangValue)
                          WHEN 5 THEN isnull (Value05, LangValue)
                          WHEN 6 THEN isnull (Value06, LangValue)
                          WHEN 7 THEN isnull (Value07, LangValue)
                          WHEN 8 THEN isnull (Value08, LangValue)
                          WHEN 9 THEN isnull (Value09, LangValue)
                          WHEN 10 THEN isnull (Value10, LangValue)
                       END label
                FROM Ghrs_LangKey
                WHERE     IsEnable = 1
                      AND (LangKey LIKE 'GHR_Page%' OR LangKey LIKE 'GHR_Common%')";
        sql = string.Format(sql, param.menuName, App.User.ID, param.langId);
        flowReturn.DT_PageMutiMsg = await Db.Ado.SqlQueryAsync<DT_PageMutiMsg>(sql);
        #endregion

        #region JM_PageFormActionsT1
        sql = $@"SELECT field fnKey, [dbo].[FLangKeyToValue] (mkey, {param.langId}, label) fnTitle, icon
                    FROM Ghrs_PageSettingEdit
                    WHERE     IsEnable = 1
                          AND pageNo = '{param.menuName}'
                          AND elementType = 'FnKey'";
        flowReturn.JM_PageFormActionsT1.Toolbar = await Db.Ado.SqlQueryAsync<Toolbar>(sql);
        #endregion

        var flowId = param.jsonParam.FlowID;
        sql = $"SELECT FlowId FROM Ghrw_Flow where FlowNo='{param.menuName}'";
        flowId = Convert.ToInt16(DbAccess.ExecuteScalar(sql));
        #region JM_TableColumnT1
        sql = $@"DECLARE
               @SQL           NVARCHAR (MAX) = '',
               @FlowID        INT = {flowId},
               @DoType        NVARCHAR (MAX) = '{param.doType}',
               @SQL2          NVARCHAR (MAX) = '',
               @JsonString    NVARCHAR (MAX) = '',
               @JsonString1   NVARCHAR (MAX) = '',
               @JsonString2   NVARCHAR (MAX) = ''

            BEGIN
               IF OBJECT_ID ('tempdb.[dbo].[#TempInitUserPageEditColumn]') IS NOT NULL
                  DROP TABLE [dbo].[#TempInitUserPageEditColumn]

               CREATE TABLE [dbo].[#TempInitUserPageEditColumn]
               (
                  InitID                 INT IDENTITY (1,1),
                  field                  NVARCHAR (100),
                  label                  NVARCHAR (100),
                  required               NVARCHAR (100),
                  editable               NVARCHAR (100),
                  rowNum                 INT,
                  colNum                 INT,
                  elementType            NVARCHAR (100),
                  dataSource             NVARCHAR (100),
                  defaultHidden          NVARCHAR (100),
                  isPrimaryKey           NVARCHAR (100),
                  isSingleColumn         INT,
                  dataType               NVARCHAR (100),
                  columnWidth            NVARCHAR (100),
                  dynamicShow            INT,
                  PrivFlag               INT,
                  multipleSelect         NVARCHAR (100),
                  isFullWidth            INT,
                  hasMarginLeft          INT,
                  canBatchPageDisplay    NVARCHAR (100)
               )

               INSERT INTO [#TempInitUserPageEditColumn]
                  SELECT pp.ColumnName field,
                         pp.ColumnLabel label,
                         iif (pp.IsRequired = 1, 'true', 'false') required,
                         iif
                         (pp.Editable = 1 AND isnull (kk.PrivFlag, 1) = 2,
                          'true',
                          'false') editable,
                         pp.SortNo rowNum,
                         1  colNum,
                         pp.ColumnType elementType,
                         CASE
                            WHEN pp.ColumnType = 'StaffSelect'
                            THEN
                               isnull (DataSourceType, 'StaffWithoutPriv')
                            WHEN pp.ColumnType = 'OrgTreeSelect'
                            THEN
                               isnull (DataSourceType, 'OrgTreeWithPriv')
                            ELSE
                               dbo.FS_GetdataSourceBySet
                               ('', pp.DataSourceType, pp.DataSource)
                         END dataSource,
                         'false' defaultHidden,
                         'true' isPrimaryKey,
                         0  isSingleColumn,
                         pp.dataType,
                         pp.columnWidth,
                         pp.dynamicShow,
                         isnull (kk.PrivFlag, 1) PrivFlag,                 -- 申请页默认都是可以编辑的
                         iif (pp.IsMultipleSelect = 1, 'true', 'false'),
                         pp.isFullWidth, pp.hasMarginLeft,
                         iif (pp.IsBatchPageDisplay = 1, 'true', 'false')
                  FROM Ghrw_FlowPageDesign pp
                       LEFT JOIN Ghrw_FlowNodesColumnPriv kk
                          ON     pp.FlowID = kk.FlowID
                             AND pp.FlowPageDesignId = kk.FlowPageDesignId
                             AND kk.IsEnable = 1
                             AND kk.NodeID = 'sid-start-node'
                  WHERE     pp.FlowID = @FlowID
                        AND pp.IsEnable = 1
                        AND isnull (kk.PrivFlag, 1) ! = 0                      -- 隐藏的栏位不显示
                  ORDER BY pp.SortNo

               IF @DoType = 'Import'
                  BEGIN
                     SELECT Row_Number () OVER (ORDER BY rowNum, colNum) SortNum,
                            field,
                            label,
                            dataSource,
                            required,
                            dataType,
                            CONVERT (NVARCHAR (1000), '') commentText,
                            elementType
                     FROM [#TempInitUserPageEditColumn]
                     WHERE field ! = 'AttachmentIDs' AND dynamicShow ! = 0

                     RETURN
                  END



               SET @JsonString1 =
                      (SELECT field,
                              label,
                              required,
                              editable,
                              rowNum,
                              colNum,
                              elementType,
                              dataSource,
                              defaultHidden,
                              isPrimaryKey,
                              isSingleColumn,
                              dataType,
                              CONVERT (INT, columnWidth) columnWidth,
                              dynamicShow,
                              multipleSelect,
                              isFullWidth, 
                              hasMarginLeft,
                              canBatchPageDisplay
                       FROM [dbo].[#TempInitUserPageEditColumn]
                       FOR JSON PATH)
               SET @JsonString1 =
                      replace
                      (replace (@JsonString1, '""true""', 'true'), '""false""', 'false')
               SET @SQL = 'select ''' + @JsonString1 + ''' [#Json#TableColumn]'
               EXEC sp_executesql @SQL
            END";

        result = await Db.Ado.GetStringAsync(sql);

        flowReturn.JM_TableColumnT1.TableColumn = JsonHelper.JsonToObj<List<FlowTableColumn>>(result);
        #endregion

        #region 特殊处理 
        switch (param.menuName)
        {
            case "F_ESS_VN_BenefitApply":
                sql = @$"DECLARE
                           @SQL           NVARCHAR (MAX) = '',
                           @FlowID        INT = {param.jsonParam.FlowID},
                           @langId        INT = {param.langId},
                           @DoType        NVARCHAR (MAX) = '{param.doType}',
                           @SQL2          NVARCHAR (MAX) = '',
                           @JsonString    NVARCHAR (MAX) = '',
                           @JsonString1   NVARCHAR (MAX) = '',
                           @JsonString2   NVARCHAR (MAX) = '',
                           @ID            INT = '{param.id}',
                           @userId        INT = {param.userId}

                        BEGIN
                           IF @DoType IN ('Update', 'Copy')                                    -- 读取修改
                              BEGIN
                                 SELECT StaffID,
                                        ApplyDate,
                                        Reverse1,
                                        BenefitType,
                                        ConnectDate,
                                        Family,
                                        ToDoType,
                                        WorkID,
                                        JSON_QUERY
                                        (
                                           dbo.FS_GetTableAttachment
                                           ('Ghrz_VN_BenefitApply', BenefitID, @langId))
                                           #Json#AttachmentIDs,
                                        SortNo,
                                        IsDefault,
                                        RemarkSz,
                                        BenefitID,
                                          isnull
                                          (
                                             (SELECT CASE
                                                        WHEN @langId = 1 THEN UserName
                                                        ELSE UserEname
                                                     END
                                              FROM Ghrs_User kk
                                              WHERE kk.UserId = a.CreateBy),
                                             '')
                                        + ' '
                                        + [dbo].[FLangKeyToValue]
                                          ('GHR_Common_000078', @langId, '于 ')
                                        + ' '
                                        + CONVERT (NVARCHAR (16), CreateTime, 121)
                                        + ' '
                                        + [dbo].[FLangKeyToValue]
                                          ('GHR_Common_000079', @langId, ' 创建')
                                           CreateDataInfo,
                                          isnull
                                          (
                                             (SELECT CASE
                                                        WHEN @langId = 1 THEN UserName
                                                        ELSE UserEname
                                                     END
                                              FROM Ghrs_User kk
                                              WHERE kk.UserId = a.UpdateBy),
                                             '')
                                        + ' '
                                        + [dbo].[FLangKeyToValue]
                                          ('GHR_Common_000078', @langId, '于')
                                        + ' '
                                        + CONVERT (NVARCHAR (16), UpdateTime, 121)
                                        + ' '
                                        + [dbo].[FLangKeyToValue]
                                          ('GHR_Common_000080', @langId, ' 最后修改')
                                           UpdateDataInfo
                                 FROM Ghrz_VN_BenefitApply a
                                 WHERE BenefitID = @ID
                              END

                           IF @DoType = 'Insert'                                               -- 空白新增
                              BEGIN
                                 SELECT (SELECT UserStaffID
                                         FROM dbo.Ghrs_User
                                         WHERE UserId = @userId) StaffID,
                                        CONVERT (NVARCHAR (10), getdate (), 23) ApplyDate,
                                        (SELECT DeptID
                                         FROM dbo.Ghra_Staff
                                         WHERE StaffID = (SELECT UserStaffID
                                                          FROM dbo.Ghrs_User
                                                          WHERE UserId = @userId)) Reverse1,
                                        NULL BenefitType,
                                        NULL ConnectDate,
                                        NULL Family,
                                        NULL ToDoType,
                                        NULL WorkID,
                                        NULL AttachmentIDs,
                                        NULL SortNo,
                                        0  IsDefault,
                                        0  BenefitID,
                                        '' RemarkSz
                              END

                           IF @DoType = 'ReApply'                                      -- ReApply:重新发起
                              BEGIN
                                 SELECT StaffID,
                                        ApplyDate,
                                        Reverse1,
                                        BenefitType,
                                        ConnectDate,
                                        Family,
                                        ToDoType,
                                        NULL WorkID,
                                        AttachmentIDs,
                                        SortNo,
                                        IsDefault,
                                        0  BenefitID,
                                        RemarkSz
                                 FROM Ghrz_VN_BenefitApply
                                 WHERE WorkID = @ID                                        -- 根据流程单号读取
                              END
                        END";
                flowReturn.DT_TableDataT1 = await Db.Ado.GetDataTableAsync(sql);
                break;
            case "F_ESS_TrainRequestApply":
                sql = @$"DECLARE
                           @SQL           NVARCHAR (MAX) = '',
                           @FlowID        INT = {param.jsonParam.FlowID},
                           @langId        INT = {param.langId},
                           @DoType        NVARCHAR (MAX) = '{param.doType}',
                           @SQL2          NVARCHAR (MAX) = '',
                           @JsonString    NVARCHAR (MAX) = '',
                           @JsonString1   NVARCHAR (MAX) = '',
                           @JsonString2   NVARCHAR (MAX) = '',
                           @ID            INT = '{param.id}',
                           @userId        INT = {param.userId}

                        BEGIN
                           IF @DoType IN ('Update', 'Copy')                                    -- 读取修改
                              BEGIN
                                 SELECT a.Id,
                                        a.CreateBy,
                                        a.CreateTime,
                                        a.CreateProg,
                                        a.CreateIP,
                                        a.UpdateBy,
                                        a.UpdateTime,
                                        a.UpdateProg,
                                        a.UpdateIP,
                                        a.OperateLogID,
                                        a.CourseSource,
                                        a.RequestNo,
                                        a.CourseName,
                                        a.CourseId,
                                        a.YearMonth,
                                        a.RequestSource,
                                        a.DeptId,
                                        a.ApplicantId,
                                        a.RequestNum,
                                        a.TrainStaffId,
                                        a.TrainClass,
                                        a.TrainLevel,
                                        a.InOrOut,
                                        a.TeacherClass,
                                        a.Reason,
                                        a.PerCapitaBudget,
                                        a.TotalBudget,
                                        a.SponsorId,
                                        a.Status,
                                        a.RemarkSz,
                                        a.IsDefault,
                                        a.IsEnable,
                                        a.WorkID,
                                        a.WorkNo,
                                        a.ToDoType,
                                        a.BatchSID,
                                        a.WorkState,
                                        a.ShiftID,
                                        a.ConfirmUserID,
                                        a.ConfirmTime,
                                        a.ConfirmComment,
                                        a.Reverse1,
                                        a.Reverse2,
                                        a.Reverse3,
                                        a.Reverse4,
                                        a.Reverse5,
                                        a.Reverse6,
                                        a.Reverse7,
                                        a.Reverse8,
                                        a.Reverse9,
                                        a.Reverse10,
                                        a.ReverseI1,
                                        a.ReverseI2,
                                          isnull
                                          (
                                             (SELECT CASE
                                                        WHEN @langId = 1 THEN UserName
                                                        ELSE UserEname
                                                     END
                                              FROM Ghrs_User kk
                                              WHERE kk.UserId = a.CreateBy),
                                             '')
                                        + ' '
                                        + [dbo].[FLangKeyToValue]
                                          ('GHR_Common_000078', @langId, '于 ')
                                        + ' '
                                        + CONVERT (NVARCHAR (16), CreateTime, 121)
                                        + ' '
                                        + [dbo].[FLangKeyToValue]
                                          ('GHR_Common_000079', @langId, ' 创建') CreateDataInfo,
                                          isnull
                                          (
                                             (SELECT CASE
                                                        WHEN @langId = 1 THEN UserName
                                                        ELSE UserEname
                                                     END
                                              FROM Ghrs_User kk
                                              WHERE kk.UserId = a.UpdateBy),
                                             '')
                                        + ' '
                                        + [dbo].[FLangKeyToValue]
                                          ('GHR_Common_000078', @langId, '于')
                                        + ' '
                                        + CONVERT (NVARCHAR (16), UpdateTime, 121)
                                        + ' '
                                        + [dbo].[FLangKeyToValue]
                                          ('GHR_Common_000080', @langId, ' 最后修改') UpdateDataInfo
                                 FROM Ghre_Request a
                                 WHERE a.Id = @ID
                              END

                           IF @DoType = 'Insert'                                               -- 空白新增
                              BEGIN
                                 SELECT (SELECT UserStaffID
                                         FROM dbo.Ghrs_User
                                         WHERE UserId = @userId) ApplicantId,
                                        NULL CourseSource,
                                        NULL RequestNo,
                                        NULL CourseName,
                                        NULL CourseId,
                                        NULL YearMonth,
                                        'Dept' RequestSource,
                                        NULL DeptId,
                                        NULL RequestNum,
                                        NULL TrainStaffId,
                                        NULL TrainClass,
                                        NULL TrainLevel,
                                        NULL InOrOut,
                                        NULL TeacherClass,
                                        NULL Reason,
                                        NULL PerCapitaBudget,
                                        NULL TotalBudget,
                                        NULL SponsorId,
                                        'Wait' Status,
                                        0  IsDefault,
                                        0  Id,
                                        '' RemarkSz
                              END

                           IF @DoType = 'ReApply'                                      -- ReApply:重新发起
                              BEGIN
                                 SELECT Id,
                                        CreateBy,
                                        CreateTime,
                                        CreateProg,
                                        CreateIP,
                                        UpdateBy,
                                        UpdateTime,
                                        UpdateProg,
                                        UpdateIP,
                                        OperateLogID,
                                        CourseSource,
                                        RequestNo,
                                        CourseName,
                                        CourseId,
                                        YearMonth,
                                        RequestSource,
                                        DeptId,
                                        ApplicantId,
                                        RequestNum,
                                        TrainStaffId,
                                        TrainClass,
                                        TrainLevel,
                                        InOrOut,
                                        TeacherClass,
                                        Reason,
                                        PerCapitaBudget,
                                        TotalBudget,
                                        SponsorId,
                                        Status,
                                        RemarkSz,
                                        IsDefault,
                                        IsEnable,
                                        WorkID,
                                        WorkNo,
                                        ToDoType,
                                        BatchSID,
                                        WorkState,
                                        ShiftID,
                                        ConfirmUserID,
                                        ConfirmTime,
                                        ConfirmComment,
                                        Reverse1,
                                        Reverse2,
                                        Reverse3,
                                        Reverse4,
                                        Reverse5,
                                        Reverse6,
                                        Reverse7,
                                        Reverse8,
                                        Reverse9,
                                        Reverse10,
                                        ReverseI1,
                                        ReverseI2
                                 FROM Ghre_Request
                                 WHERE WorkID = @ID                                        -- 根据流程单号读取
                              END
                        END";
                flowReturn.DT_TableDataT1 = await Db.Ado.GetDataTableAsync(sql);
                break;
            case "F_ESS_TrainRequestPersonalApply":
                sql = @$"DECLARE
                           @SQL           NVARCHAR (MAX) = '',
                           @FlowID        INT = {param.jsonParam.FlowID},
                           @langId        INT = {param.langId},
                           @DoType        NVARCHAR (MAX) = '{param.doType}',
                           @SQL2          NVARCHAR (MAX) = '',
                           @JsonString    NVARCHAR (MAX) = '',
                           @JsonString1   NVARCHAR (MAX) = '',
                           @JsonString2   NVARCHAR (MAX) = '',
                           @ID            INT = '{param.id}',
                           @userId        INT = {param.userId}

                        BEGIN
                           IF @DoType IN ('Update', 'Copy')                                    -- 读取修改
                              BEGIN
                                 SELECT a.Id,
                                        a.CreateBy,
                                        a.CreateTime,
                                        a.CreateProg,
                                        a.CreateIP,
                                        a.UpdateBy,
                                        a.UpdateTime,
                                        a.UpdateProg,
                                        a.UpdateIP,
                                        a.OperateLogID,
                                        a.CourseSource,
                                        a.RequestNo,
                                        a.CourseName,
                                        a.CourseId,
                                        a.YearMonth,
                                        a.RequestSource,
                                        a.DeptId,
                                        a.ApplicantId,
                                        a.RequestNum,
                                        a.TrainStaffId,
                                        a.TrainClass,
                                        a.TrainLevel,
                                        a.InOrOut,
                                        a.TeacherClass,
                                        a.Reason,
                                        a.PerCapitaBudget,
                                        a.TotalBudget,
                                        a.SponsorId,
                                        a.Status,
                                        a.RemarkSz,
                                        a.IsDefault,
                                        a.IsEnable,
                                        a.WorkID,
                                        a.WorkNo,
                                        a.ToDoType,
                                        a.BatchSID,
                                        a.WorkState,
                                        a.ShiftID,
                                        a.ConfirmUserID,
                                        a.ConfirmTime,
                                        a.ConfirmComment,
                                        a.Reverse1,
                                        a.Reverse2,
                                        a.Reverse3,
                                        a.Reverse4,
                                        a.Reverse5,
                                        a.Reverse6,
                                        a.Reverse7,
                                        a.Reverse8,
                                        a.Reverse9,
                                        a.Reverse10,
                                        a.ReverseI1,
                                        a.ReverseI2,
                                          isnull
                                          (
                                             (SELECT CASE
                                                        WHEN @langId = 1 THEN UserName
                                                        ELSE UserEname
                                                     END
                                              FROM Ghrs_User kk
                                              WHERE kk.UserId = a.CreateBy),
                                             '')
                                        + ' '
                                        + [dbo].[FLangKeyToValue]
                                          ('GHR_Common_000078', @langId, '于 ')
                                        + ' '
                                        + CONVERT (NVARCHAR (16), CreateTime, 121)
                                        + ' '
                                        + [dbo].[FLangKeyToValue]
                                          ('GHR_Common_000079', @langId, ' 创建') CreateDataInfo,
                                          isnull
                                          (
                                             (SELECT CASE
                                                        WHEN @langId = 1 THEN UserName
                                                        ELSE UserEname
                                                     END
                                              FROM Ghrs_User kk
                                              WHERE kk.UserId = a.UpdateBy),
                                             '')
                                        + ' '
                                        + [dbo].[FLangKeyToValue]
                                          ('GHR_Common_000078', @langId, '于')
                                        + ' '
                                        + CONVERT (NVARCHAR (16), UpdateTime, 121)
                                        + ' '
                                        + [dbo].[FLangKeyToValue]
                                          ('GHR_Common_000080', @langId, ' 最后修改') UpdateDataInfo
                                 FROM Ghre_Request a
                                 WHERE a.Id = @ID
                              END

                           IF @DoType = 'Insert'                                               -- 空白新增
                              BEGIN
                                 SELECT (SELECT UserStaffID
                                         FROM dbo.Ghrs_User
                                         WHERE UserId = @userId) ApplicantId,
                                        NULL CourseSource,
                                        NULL RequestNo,
                                        NULL CourseName,
                                        NULL CourseId,
                                        NULL YearMonth,
                                        'Person' RequestSource,
                                        (SELECT DeptID
                                         FROM Ghra_Staff
                                         WHERE StaffID = (SELECT UserStaffID
                                                          FROM dbo.Ghrs_User
                                                          WHERE UserId = @userId)) DeptId,
                                        NULL RequestNum,
                                        NULL TrainStaffId,
                                        NULL TrainClass,
                                        NULL TrainLevel,
                                        NULL InOrOut,
                                        NULL TeacherClass,
                                        NULL Reason,
                                        NULL PerCapitaBudget,
                                        NULL TotalBudget,
                                        NULL SponsorId,
                                        'Wait' Status,
                                        0  IsDefault,
                                        0  Id,
                                        '' RemarkSz
                              END

                           IF @DoType = 'ReApply'                                      -- ReApply:重新发起
                              BEGIN
                                 SELECT Id,
                                        CreateBy,
                                        CreateTime,
                                        CreateProg,
                                        CreateIP,
                                        UpdateBy,
                                        UpdateTime,
                                        UpdateProg,
                                        UpdateIP,
                                        OperateLogID,
                                        CourseSource,
                                        RequestNo,
                                        CourseName,
                                        CourseId,
                                        YearMonth,
                                        RequestSource,
                                        DeptId,
                                        ApplicantId,
                                        RequestNum,
                                        TrainStaffId,
                                        TrainClass,
                                        TrainLevel,
                                        InOrOut,
                                        TeacherClass,
                                        Reason,
                                        PerCapitaBudget,
                                        TotalBudget,
                                        SponsorId,
                                        Status,
                                        RemarkSz,
                                        IsDefault,
                                        IsEnable,
                                        WorkID,
                                        WorkNo,
                                        ToDoType,
                                        BatchSID,
                                        WorkState,
                                        ShiftID,
                                        ConfirmUserID,
                                        ConfirmTime,
                                        ConfirmComment,
                                        Reverse1,
                                        Reverse2,
                                        Reverse3,
                                        Reverse4,
                                        Reverse5,
                                        Reverse6,
                                        Reverse7,
                                        Reverse8,
                                        Reverse9,
                                        Reverse10,
                                        ReverseI1,
                                        ReverseI2
                                 FROM Ghre_Request
                                 WHERE WorkID = @ID                                        -- 根据流程单号读取
                              END
                        END";
                flowReturn.DT_TableDataT1 = await Db.Ado.GetDataTableAsync(sql);
                break;

            case "F_ESS_TrainTeacherApply":
                sql = @$"DECLARE
                           @SQL           NVARCHAR (MAX) = '',
                           @FlowID        INT = {param.jsonParam.FlowID},
                           @langId        INT = {param.langId},
                           @DoType        NVARCHAR (MAX) = '{param.doType}',
                           @SQL2          NVARCHAR (MAX) = '',
                           @JsonString    NVARCHAR (MAX) = '',
                           @JsonString1   NVARCHAR (MAX) = '',
                           @JsonString2   NVARCHAR (MAX) = '',
                           @ID            INT = '{param.id}',
                           @userId        INT = {param.userId}

                        BEGIN
                       IF @DoType IN ('Update', 'Copy')                                    -- 读取修改
                          BEGIN
                             SELECT a.Id,
                                    a.CreateBy,
                                    a.CreateTime,
                                    a.CreateProg,
                                    a.CreateIP,
                                    a.UpdateBy,
                                    a.UpdateTime,
                                    a.UpdateProg,
                                    a.UpdateIP,
                                    a.OperateLogID,
                                    a.CourseSource,
                                    a.RequestNo,
                                    a.CourseName,
                                    a.CourseId,
                                    a.YearMonth,
                                    a.RequestSource,
                                    a.DeptId,
                                    a.ApplicantId,
                                    a.RequestNum,
                                    a.TrainStaffId,
                                    a.TrainClass,
                                    a.TrainLevel,
                                    a.InOrOut,
                                    a.TeacherClass,
                                    a.Reason,
                                    a.PerCapitaBudget,
                                    a.TotalBudget,
                                    a.SponsorId,
                                    a.Status,
                                    a.RemarkSz,
                                    a.IsDefault,
                                    a.IsEnable,
                                    a.WorkID,
                                    a.WorkNo,
                                    a.ToDoType,
                                    a.BatchSID,
                                    a.WorkState,
                                    a.ShiftID,
                                    a.ConfirmUserID,
                                    a.ConfirmTime,
                                    a.ConfirmComment,
                                    a.AgreeUserId,
                                    a.AgreeTime,
                                    a.AgreeReason,
                                    a.RefuseUserId,
                                    a.RefuseTime,
                                    a.RefuseReason,
                                    a.Reverse1,
                                    a.Reverse2,
                                    a.Reverse3,
                                    a.Reverse4,
                                    a.Reverse5,
                                    a.Reverse6,
                                    a.Reverse7,
                                    a.Reverse8,
                                    a.Reverse9,
                                    a.Reverse10,
                                    a.ReverseI1,
                                    a.ReverseI2,
                                      isnull
                                      (
                                         (SELECT CASE
                                                    WHEN @langId = 1 THEN UserName
                                                    ELSE UserEname
                                                 END
                                          FROM Ghrs_User kk
                                          WHERE kk.UserId = a.CreateBy),
                                         '')
                                    + ' '
                                    + [dbo].[FLangKeyToValue]
                                      ('GHR_Common_000078', @langId, '于 ')
                                    + ' '
                                    + CONVERT (NVARCHAR (16), CreateTime, 121)
                                    + ' '
                                    + [dbo].[FLangKeyToValue]
                                      ('GHR_Common_000079', @langId, ' 创建') CreateDataInfo,
                                      isnull
                                      (
                                         (SELECT CASE
                                                    WHEN @langId = 1 THEN UserName
                                                    ELSE UserEname
                                                 END
                                          FROM Ghrs_User kk
                                          WHERE kk.UserId = a.UpdateBy),
                                         '')
                                    + ' '
                                    + [dbo].[FLangKeyToValue]
                                      ('GHR_Common_000078', @langId, '于')
                                    + ' '
                                    + CONVERT (NVARCHAR (16), UpdateTime, 121)
                                    + ' '
                                    + [dbo].[FLangKeyToValue]
                                      ('GHR_Common_000080', @langId, ' 最后修改') UpdateDataInfo
                             FROM Ghre_Request a
                             WHERE a.Id = @ID
                          END

                       IF @DoType = 'Insert'                                               -- 空白新增
                          BEGIN
                             SELECT (SELECT UserStaffID
                                     FROM dbo.Ghrs_User
                                     WHERE UserId = @userId) CreateBy,
                                    NULL SchoolId,
                                    (SELECT DeptID
                                     FROM Ghra_Staff
                                     WHERE StaffID = (SELECT UserStaffID
                                                      FROM dbo.Ghrs_User
                                                      WHERE UserId = @userId)) DeptID,
                                    NULL StaffId,
                                    NULL TeacherType,
                                    NULL TeacherNo,
                                    NULL TeacherName,
                                    NULL PhotoUrl,
                                    NULL Gender,
                                    NULL Email,
                                    NULL Mobile,
                                    NULL TeacherLevel,
                                    NULL Price,
                                    NULL SkillPoints,
                                    NULL ApplyReason,
                                    'Wait' Status,
                                    0  IsDefault,
                                    0  Id,
                                    NULL RemarkSz
                          END

                       IF @DoType = 'ReApply'                                      -- ReApply:重新发起
                          BEGIN
                             SELECT Id,
                                    CreateBy,
                                    CreateTime,
                                    CreateProg,
                                    CreateIP,
                                    UpdateBy,
                                    UpdateTime,
                                    UpdateProg,
                                    UpdateIP,
                                    OperateLogID,
                                    SchoolId,
                                    DeptID,
                                    StaffId,
                                    TeacherType,
                                    TeacherNo,
                                    TeacherName,
                                    PhotoUrl,
                                    Gender,
                                    Email,
                                    Mobile,
                                    TeacherLevel,
                                    Price,
                                    SkillPoints,
                                    RemarkSz,
                                    IsDefault,
                                    IsEnable,
                                    WorkID,
                                    WorkNo,
                                    ToDoType,
                                    BatchSID,
                                    WorkState,
                                    ShiftID,
                                    ConfirmUserID,
                                    ConfirmTime,
                                    ConfirmComment,
                                    AgreeUserId,
                                    AgreeTime,
                                    AgreeReason,
                                    RefuseUserId,
                                    RefuseTime,
                                    RefuseReason,
                                    Reverse1,
                                    Reverse2,
                                    Reverse3,
                                    Reverse4,
                                    Reverse5,
                                    Reverse6,
                                    Reverse7,
                                    Reverse8,
                                    Reverse9,
                                    Reverse10,
                                    ReverseI1,
                                    ReverseI2,
                                    Status, 
                                    ApplyReason
                             FROM Ghre_Teacher
                             WHERE WorkID = @ID                                        -- 根据流程单号读取
                          END
                    END";
                var data = await Db.Ado.SqlQueryAsync<Ghre_TeacherDto>(sql);
                data.ForEach(x => x.TeacherAttachments = new List<Ghre_TeacherAttachmentDto>());
                flowReturn.DT_TableDataT1 = data;
                break;

            case "F_ESS_TrainTeacherChangeApply":
                //sql = @$"DECLARE
                //           @SQL           NVARCHAR (MAX) = '',
                //           @FlowID        INT = {param.jsonParam.FlowID},
                //           @langId        INT = {param.langId},
                //           @DoType        NVARCHAR (MAX) = '{param.doType}',
                //           @SQL2          NVARCHAR (MAX) = '',
                //           @JsonString    NVARCHAR (MAX) = '',
                //           @JsonString1   NVARCHAR (MAX) = '',
                //           @JsonString2   NVARCHAR (MAX) = '',
                //           @ID            INT = '{param.id}',
                //           @userId        INT = {param.userId}

                //         ";

                if (param.doType == "Insert")
                {
                    var data1 = new List<Ghre_TeacherChangeDto>
                    {
                        new Ghre_TeacherChangeDto()
                        {
                            CreateBy = GetStaffId(),
                            Id = 0,
                            Status = "Wait"
                        }
                    };
                    data1.ForEach(x => x.TeacherAttachments = new List<Ghre_TeacherChangeAttachmentDto>());
                    flowReturn.DT_TableDataT1 = data1;

                }
                break;
            case "F_ESS_RecruitYearManpowerApply":
                if (param.doType == "Insert")
                {
                    var config = await Db.Queryable<Ghrh_Config>().Where(x => x.ConfigCode == "ESS_Recruit_Year_Human_Start_Month").FirstAsync();

                    var startMonth = config != null ? config.ConfigValue.ObjToInt() : 1;


                    var data1 = new InsertGhrh_YearHumanApplyOrderInput()
                    {
                        StartMonth = startMonth,
                    };

                    #region 处理起始月 
                    var months = new List<string>();
                    List<int> numbers = new();
                    for (int i = 1; i <= 12; i++)
                    {
                        if (i < 10)
                            months.Add("0" + i);
                        else
                            months.Add(i.ObjToString());
                        numbers.Add(i);
                    }
                    var curentYear = DateTime.Now.Year;
                    var curentMonth = DateTime.Now.Month;
                    // 指定要打头的数字
                    int startNumber = startMonth;


                    if (curentMonth < startMonth)
                        curentYear = -1;

                    data1.Year = curentYear;
                    var sort = flowReturn.JM_TableColumnT1.TableColumn.Where(x => x.field == "M1").SingleOrDefault()?.rowNum ?? 5;
                    // 创建一个新的列表用于存储重新排序后的结果
                    var name1 = await QueryLangValue("F_ResumeMaintenance_0216", "预算编制数");
                    List<int> reorderedNumbers = new();
                    flowReturn.JM_TableColumnT1.TableColumn?.ForEach(x =>
                    {
                        if (months.Where(o => o == x.label).Any())
                            x.GroupName = name1;

                    });

                    // 找到指定数字的索引
                    int index1 = numbers.IndexOf(startNumber);
                    if (index1 != -1)
                    {
                        // 从指定数字开始，按照循环顺序添加数字
                        for (int i = 0; i < numbers.Count; i++)
                        {
                            int currentIndex = (index1 + i) % numbers.Count;
                            reorderedNumbers.Add(numbers[currentIndex]);
                        }

                        foreach (var num in reorderedNumbers)
                        {
                            flowReturn.JM_TableColumnT1.TableColumn?.ForEach(x =>
                            {
                                if (x.label.ObjToInt() == num)
                                {
                                    x.rowNum = sort;
                                    x.label = curentYear + "-" + x.label;
                                }
                            });
                            if (num == 12)
                                curentYear++;
                            sort++;
                        }
                    }
                    flowReturn.JM_TableColumnT1.TableColumn = flowReturn.JM_TableColumnT1.TableColumn.OrderBy(x => x.rowNum).ToList();
                    #endregion
                    data1.Items.Add(new Ghrh_YearHumanSettings() { });
                    var list = new List<InsertGhrh_YearHumanApplyOrderInput>
                    {
                        data1
                    };
                    flowReturn.DT_TableDataT1 = list;
                }
                break;
            case "F_ESS_RecruitManpowerRequestApply":
                if (param.doType == "Insert")
                {
                    flowReturn.DT_TableDataT1 = new List<InsertGhrh_HumanRequestInput>()
                    {
                        new InsertGhrh_HumanRequestInput()
                        {
                        }
                    };
                }
                break;

            case "F_ESS_ExternalTrainApplyOrder_Boltone":
                if (param.doType == "Insert")
                {
                    flowReturn.DT_TableDataT1 = new List<InsertGhre_ExternalTrainApplyOrder_BoltoneInput>()
                    {
                        new InsertGhre_ExternalTrainApplyOrder_BoltoneInput()
                    {
                        ApplicantId = App.User.StaffId,
                        ApplicantDeptId = GetStaffDeptId(),
                        ApplicantTime = DateTime.Now
                    }
                    };
                }
                break;

            case "F_ESS_TrainFeeApplyOrder_Boltone":
                if (param.doType == "Insert")
                {
                    flowReturn.DT_TableDataT1 = new List<InsertGhre_TrainFeeApplyOrder_BoltoneInput>()
                    {
                        new InsertGhre_TrainFeeApplyOrder_BoltoneInput()
                    {
                        ApplicantId = App.User.StaffId,
                        ApplicantDeptId = GetStaffDeptId(),
                        ApplicantTime = DateTime.Now
                    }
                    };
                }
                break;
        }

        #endregion

        return new ServiceResult<FlowReturn>() { Success = true, Message = "查询成功", result = flowReturn };
    }
    #endregion

    #region 流程提交处理
    /// <summary>
    /// 流程提交处理
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<ServiceResult> CommitFlowAsync(FlowCommitParam param)
    {
        var @InitmenuName = param.menuName;
        int @FlowID = 0;

        #region 写入日志
        var sql = $@"DECLARE @return_value int;

                    DECLARE @OperateLogID bigint;


                    SET @OperateLogID = NULL;

                    EXEC  @return_value = dbo.[PS_OperateLog] 
                        @OpUserID = {param.userId},
                        @OpType = {param.doType},
                        @OpMenuNo = {param.menuName},
                        @OpTableName = {param.menuName},
                        @OpTableID = {param.id},
                        @OpDetailInfo = '{param.jsonParam.ToString()}',
                        @OperateLogID = @OperateLogID out;

                    SELECT @OperateLogID as N'@OperateLogID', @return_value as N'@Return Value';";
        await Db.Ado.ExecuteCommandAsync(sql);
        #endregion

        sql = $"SELECT FlowID FROM Ghrs_Menu b WHERE b.Menuno = '{param.menuName}' AND b.IsEnable = 1";
        @FlowID = await Db.Ado.GetIntAsync(sql);

        long id = 0;

        switch (param.menuName)
        {
            case "F_ESS_TrainRequestPersonalApply":
            case "F_ESS_TrainRequestApply":

                #region  写入数据,并判断是否有错误
                switch (param.doType)
                {
                    case "Apply":
                    case "BatchApply":

                        #region  写入数据,并判断是否有错误
                        string json = param.jsonParam.ToString();
                        var dict = JsonHelper.JsonToObj<Ghre_Request>(json);

                        dict.SponsorId = GetStaffId();
                        dict.RequestNo = await GenerateContinuousSequence("Ghre_Request", "RequestNo", "R");
                        id = await Db.Insertable(dict).ExecuteReturnSnowflakeIdAsync();

                        #region 根据参数 处理数据默认状态
                        var config = await Db.Queryable<Ghre_Config>().FirstAsync(x => x.ConfigCode == "ESS_Request_Apply_Status");
                        if (config != null)
                        {
                            sql = $"UPDATE Ghre_Request SET Status='{config.ConfigValue}' WHERE  Id ='{id}'";
                            await Db.Ado.ExecuteCommandAsync(sql);
                        }
                        #endregion

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

                        id = id1;
                        #endregion

                        break;
                }
                #endregion

                break;
            case "F_ESS_TrainTeacherApply":

                #region  写入数据,并判断是否有错误
                switch (param.doType)
                {
                    case "Apply":
                    case "BatchApply":

                        #region  写入数据,并判断是否有错误
                        string json = param.jsonParam.ToString();
                        var dict = JsonHelper.JsonToObj<Ghre_Teacher>(json);
                        var staffId = dict.StaffId;

                        var staff = await Db.Queryable<Ghra_Staff>().FirstAsync(x => x.StaffID == staffId);
                        if (staff != null)
                        {
                            dict.TeacherNo = staff.StaffNo;
                            dict.TeacherName = staff.StaffName;
                        }

                        if (await Db.Queryable<Ghre_Teacher>().AnyAsync(x => x.StaffId == staffId))
                            throw new Exception($"员工【{staff.StaffName}({staff.StaffNo})】已在讲师列表中！");
                        //dict.StaffId = GetStaffId();

                        id = await Db.Insertable(dict).ExecuteReturnSnowflakeIdAsync();

                        #region 根据参数 处理数据默认状态
                        var config = await Db.Queryable<Ghre_Config>().FirstAsync(x => x.ConfigCode == "ESS_Teacher_Apply_Status");
                        if (config != null)
                        {
                            sql = $"UPDATE Ghre_Teacher SET Status='{config.ConfigValue}' WHERE  Id ='{id}'";
                            await Db.Ado.ExecuteCommandAsync(sql);
                        }
                        #endregion

                        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;
                        #endregion

                        #region 生成流程数据
                        sql = @$"DECLARE @return_value int;

                                DECLARE @ErrorMsg nvarchar(2000);

                                SET @ErrorMsg = NULL;

                                EXEC  @return_value = dbo.[PT_GHR30_FlowApply] 
                                    @ID = {id},
                                    @FlowID = {@FlowID},
                                    @UserID = {param.userId},
                                    @LangID = {param.langId},
                                    @ErrorMsg = @ErrorMsg out;

                                SELECT @ErrorMsg as N'@ErrorMsg', @return_value as N'@Return Value';";

                        var message = await Db.Ado.GetStringAsync(sql);

                        if (message.IsNotEmptyOrNull())
                            return new ServiceResult() { Success = false, Message = message };
                        #endregion

                        sql = $"UPDATE Ghre_Teacher SET StaffId={staffId} WHERE  Id ='{id}'";
                        await Db.Ado.ExecuteCommandAsync(sql);
                        break;
                }
                #endregion

                break;
            case "F_ESS_TrainTeacherChangeApply":

                #region  写入数据,并判断是否有错误
                switch (param.doType)
                {
                    case "Apply":
                    case "BatchApply":

                        #region  写入数据,并判断是否有错误
                        string json = param.jsonParam.ToString();
                        var dict = JsonHelper.JsonToObj<Ghre_TeacherChange>(json);
                        dict.SponsorId = GetStaffId();
                        dict.StaffId = GetStaffId();

                        id = await Db.Insertable(dict).ExecuteReturnSnowflakeIdAsync();

                        #region 根据参数 处理数据默认状态
                        var config = await Db.Queryable<Ghre_Config>().FirstAsync(x => x.ConfigCode == "ESS_Teacher_Change_Apply_Status");
                        if (config != null)
                        {
                            sql = $"UPDATE Ghre_TeacherChange SET Status='{config.ConfigValue}' WHERE  Id ='{id}'";
                            await Db.Ado.ExecuteCommandAsync(sql);
                        }
                        #endregion

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

                        id = id1;
                        #endregion 

                        break;
                }
                #endregion

                break;

            case "F_ESS_RecruitYearManpowerApply":

                #region  写入数据,并判断是否有错误
                switch (param.doType)
                {
                    case "Apply":
                    case "BatchApply":

                        #region  写入数据,并判断是否有错误
                        string json = param.jsonParam.ToString();
                        var dict = JsonHelper.JsonToObj<InsertGhrh_YearHumanApplyOrderInput>(json);
                        var dict1 = JsonHelper.JsonToObj<Ghrh_YearHumanApplyOrder>(json);

                        #region 校验数据是否重复
                        dict.Items.ForEach(x =>
                        {
                            x.Year = dict1.Year;
                        });
                        for (int i = 0; i < dict.Items.Count; i++)
                        {
                            var item = dict.Items[i];
                            if (item.DeptId.IsNullOrEmpty())
                                return ServiceResult.OprateFailed($"第{i + 1}行，部门不可为空");
                            if (item.TitleId.IsNullOrEmpty())
                                return ServiceResult.OprateFailed($"第{i + 1}行，岗位不可为空");

                            if (await Db.Queryable<Ghrh_YearHumanSettings>()
                                .WhereIF(item.GradeId.IsNotEmptyOrNull(), x => x.GradeId == item.GradeId)
                                .WhereIF(item.JobId.IsNotEmptyOrNull(), x => x.JobId == item.JobId)
                                .AnyAsync(x => x.Year == item.Year && x.DeptId == item.DeptId && x.TitleId == item.TitleId))
                                return ServiceResult.OprateFailed($" {item.Year}年度，已存在相同数据！");
                        }
                        #endregion



                        dict1.ApplicantId = GetStaffId();
                        dict1.ApplicantTime = DateTime.Now;
                        id = await Db.Insertable(dict1).ExecuteReturnSnowflakeIdAsync();

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

                        id = id1;

                        dict.Items.ForEach(x =>
                        {
                            x.OrderId = id;
                            x.WorkState = 0;
                            x.Year = dict1.Year;
                            x.Id = SnowFlakeSingle.Instance.NextId();
                        });
                        await Db.Insertable(dict.Items).ExecuteCommandAsync();

                        #endregion

                        break;
                }
                #endregion

                break;
            case "F_ESS_RecruitManpowerRequestApply":

                #region  写入数据,并判断是否有错误
                switch (param.doType)
                {
                    case "Apply":
                    case "BatchApply":

                        #region  写入数据,并判断是否有错误
                        string json = param.jsonParam.ToString();
                        var dict = JsonHelper.JsonToObj<Ghrh_HumanRequest>(json);

                        #region 根据参数 处理数据默认状态
                        var config = await Db.Queryable<Ghrh_Config>().FirstAsync(x => x.ConfigCode == "ESS_Human_Request_Apply_Status");
                        if (config != null)
                            dict.Status = config.ConfigValue;
                        else
                            dict.Status = "WaitConfirm";
                        #endregion 
                        dict.ApplicantId = GetStaffId();
                        dict.RequestNo = await GenerateContinuousSequence("Ghrh_HumanRequest", "RequestNo", "R");
                        id = await Db.Insertable(dict).ExecuteReturnSnowflakeIdAsync();

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

                        id = id1;
                        #endregion

                        break;
                }
                #endregion

                break;
            case "F_ESS_RecruitOfferApply":

                #region  写入数据,并判断是否有错误
                switch (param.doType)
                {
                    case "Apply":
                    case "BatchApply":

                        #region  写入数据,并判断是否有错误
                        string json = param.jsonParam.ToString();
                        var dict = JsonHelper.JsonToObj<Ghrh_OfferApplyOrder>(json);
                        //dict.RequestNo = await GenerateContinuousSequence("Ghrh_HumanRequest", "RequestNo", "R");
                        id = await Db.Insertable(dict).ExecuteReturnSnowflakeIdAsync();

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

                        id = id1;
                        #endregion

                        break;
                }
                #endregion

                break;

            case "F_ESS_ExternalTrainApplyOrder_Boltone": //外训申请_宝连通

                #region  写入数据,并判断是否有错误
                switch (param.doType)
                {
                    case "Apply":
                    case "BatchApply":

                        #region  写入数据,并判断是否有错误
                        string json = param.jsonParam.ToString();
                        var dict = JsonHelper.JsonToObj<Ghre_ExternalTrainApplyOrder_Boltone>(json);
                        var dict1 = JsonHelper.JsonToObj<Ghre_ExternalTrainApplyOrder_BoltoneBase>(json);
                        //dict.RequestNo = await GenerateContinuousSequence("Ghrh_HumanRequest", "RequestNo", "R");
                        id = await Db.Insertable(dict).ExecuteReturnSnowflakeIdAsync();

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

                        id = id1;

                        if (dict1.Attachments.Any())
                        {
                            var ids = dict1.Attachments.Select(x => x.AttachmentID).ToList();
                            await Db.Updateable<Ghre_Attachment>()
                               .SetColumns(it => new Ghre_Attachment()
                               {
                                   TableName = "Ghre_ExternalTrainApplyOrder_Boltone",
                                   TableKeyID = id.ObjToInt(),
                                   Reverse1 = "Attachments"
                               })
                               .Where(it => ids.Contains(it.Id))
                               .ExecuteCommandAsync();
                        }
                        if (dict1.ContractAttachments.Any())
                        {
                            var ids = dict1.ContractAttachments.Select(x => x.AttachmentID).ToList();
                            await Db.Updateable<Ghre_Attachment>()
                               .SetColumns(it => new Ghre_Attachment()
                               {
                                   TableName = "Ghre_ExternalTrainApplyOrder_Boltone",
                                   TableKeyID = id.ObjToInt(),
                                   Reverse1 = "ContractAttachments"
                               })
                               .Where(it => ids.Contains(it.Id))
                               .ExecuteCommandAsync();
                        }

                        if (dict1.ExternalAttachments.Any())
                        {
                            var ids = dict1.ExternalAttachments.Select(x => x.AttachmentID).ToList();
                            await Db.Updateable<Ghre_Attachment>()
                               .SetColumns(it => new Ghre_Attachment()
                               {
                                   TableName = "Ghre_ExternalTrainApplyOrder_Boltone",
                                   TableKeyID = id.ObjToInt(),
                                   Reverse1 = "ExternalAttachments"
                               })
                               .Where(it => ids.Contains(it.Id))
                               .ExecuteCommandAsync();
                        }
                        if (dict1.ReflectionAttachments.Any())
                        {
                            var ids = dict1.ReflectionAttachments.Select(x => x.AttachmentID).ToList();
                            await Db.Updateable<Ghre_Attachment>()
                               .SetColumns(it => new Ghre_Attachment()
                               {
                                   TableName = "Ghre_ExternalTrainApplyOrder_Boltone",
                                   TableKeyID = id.ObjToInt(),
                                   Reverse1 = "ReflectionAttachments"
                               })
                               .Where(it => ids.Contains(it.Id))
                               .ExecuteCommandAsync();
                        }
                        #endregion

                        break;
                }
                #endregion

                break;

            case "F_ESS_TrainFeeApplyOrder_Boltone": //培训费用_宝连通

                #region  写入数据,并判断是否有错误
                switch (param.doType)
                {
                    case "Apply":
                    case "BatchApply":


                        #region  写入数据,并判断是否有错误
                        string json = param.jsonParam.ToString();
                        var dict = JsonHelper.JsonToObj<Ghre_TrainFeeApplyOrder_Boltone>(json);
                        var dict1 = JsonHelper.JsonToObj<Ghre_TrainFeeApplyOrder_BoltoneBase>(json);
                        //dict.RequestNo = await GenerateContinuousSequence("Ghrh_HumanRequest", "RequestNo", "R");

                        if (dict1.PlanIds != null && dict1.PlanIds.Any())
                            dict.PlanId = JsonHelper.ObjToJson(dict1.PlanIds);
                        id = await Db.Insertable(dict).ExecuteReturnSnowflakeIdAsync();


                        //var StaffUserId = await Db.Queryable<Ghrs_User>().Where(x => x.UserStaffID == dict.TeacherId).Select(x => x.UserId).FirstAsync();
                        //if (StaffUserId > 0)
                        //    param.userId = StaffUserId;

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

                        id = id1;


                        dict1.Details.ForEach(x =>
                        {
                            x.OrderId = id;
                            x.Id = SnowFlakeSingle.Instance.NextId();
                        });
                        await Db.Insertable(dict1.Details).ExecuteCommandAsync();

                        if (dict1.Attachments.Any())
                        {
                            var ids = dict1.Attachments.Select(x => x.AttachmentID).ToList();
                            await Db.Updateable<Ghre_Attachment>()
                               .SetColumns(it => new Ghre_Attachment()
                               {
                                   TableName = "Ghre_TrainFeeApplyOrder_Boltone",
                                   TableKeyID = id.ObjToInt(),
                                   Reverse1 = "Attachments"
                               })
                               .Where(it => ids.Contains(it.Id))
                               .ExecuteCommandAsync();
                        }

                        #endregion

                        break;
                }
                #endregion

                break;
        }

        if (param.menuName != "F_ESS_TrainTeacherApply")
        {

            #region 生成流程数据
            sql = @$"DECLARE @return_value int;

                DECLARE @ErrorMsg nvarchar(2000);

                SET @ErrorMsg = NULL;

                EXEC  @return_value = dbo.[PT_GHR30_FlowApply] 
                    @ID = {id},
                    @FlowID = {@FlowID},
                    @UserID = {param.userId},
                    @LangID = {param.langId},
                    @ErrorMsg = @ErrorMsg out;

                SELECT @ErrorMsg as N'@ErrorMsg', @return_value as N'@Return Value';";

            var message = await Db.Ado.GetStringAsync(sql);

            if (message.IsNotEmptyOrNull())
                return new ServiceResult() { Success = false, Message = message };

            #endregion
        }

        return new ServiceResult() { Success = true, Message = "提交成功" };
    }
    #endregion

    #region MyRegion
    public int? GetStaffId()
    {
        int? StaffId = null;
        string sql = $"SELECT UserStaffID FROM Ghrs_User WHERE UserId='{App.User.ID}'";
        string StaffId1 = Convert.ToString(DbAccess.ExecuteScalar(sql));
        if (!StaffId1.IsNull())
            StaffId = Convert.ToInt32(StaffId1);
        return StaffId;
    }
    public int? GetStaffDeptId()
    {
        int? StaffId = null;
        string sql = $"SELECT DeptID FROM Ghra_Staff where StaffID='{App.User.StaffId}'";
        string StaffId1 = Convert.ToString(DbAccess.ExecuteScalar(sql));
        if (!StaffId1.IsNull())
            StaffId = Convert.ToInt32(StaffId1);
        return StaffId;
    }
    #endregion

    #region 自动编号
    /// <summary>
    /// 自动编号
    /// </summary>
    /// <param name="tableCode">表名</param>
    /// <param name="columnCode">栏位名</param>
    /// <param name="prefixTemp">前缀</param>
    /// <returns></returns>
    public async Task<string> GenerateContinuousSequence(string tableCode, string columnCode, string prefixTemp, int length = 7, int tempLength = 6)
    {
        try
        {
            string result = string.Empty;
            int sequence;

            #region 查询
            DbSelect dbSelect = new DbSelect(tableCode + " A", "A", null);
            dbSelect.IsInitDefaultValue = false;

            if (!string.IsNullOrEmpty(prefixTemp))
                dbSelect.Select("MAX(SUBSTRING(A." + columnCode + "," + (prefixTemp.Length + 1).ToString() + "," + tempLength.ToString() + "))");
            else
                dbSelect.Select("MAX(A." + columnCode + ")");
            //}
            //dbSelect.Select("MAX(CONVERT(DECIMAL,SUBSTRING(A.ISSUE_NO," + (prefix.Length + dateString.Length + 1).ToString() + "," + tempLength.ToString() + ")))");
            if (!string.IsNullOrEmpty(prefixTemp))
                dbSelect.Where("SUBSTRING(A." + columnCode + ",1," + (prefixTemp.Length).ToString() + ")", " = ", prefixTemp);
            dbSelect.Where("LEN(A." + columnCode + ")", "=", length);
            string sql = dbSelect.GetSql();
            //await Db.Ado.GetScalarAsync(sql)
            string maxSequence = Convert.ToString(await Db.Ado.GetScalarAsync(sql));
            #endregion
            //tempLength = tempLength - dateString.Length;
            if (string.IsNullOrEmpty(maxSequence))
                result = prefixTemp + Convert.ToString(1).PadLeft(tempLength, '0');
            else
            {
                if (!string.IsNullOrEmpty(prefixTemp))
                {
                    if (int.TryParse(maxSequence, out sequence))
                    {
                        sequence += 1;
                        if (sequence.ToString().Length > tempLength)
                            throw new Exception("自动生成字串长度已经超过设定长度!");
                    }
                    else
                        throw new Exception("表中的数据无法进行自动编号,请联系软件开发商!");
                    result = prefixTemp + sequence.ToString().PadLeft(tempLength, '0');
                }
                else
                {
                    if (int.TryParse(maxSequence, out sequence))
                    {
                        sequence += 1;
                        if (sequence.ToString().Length > length)
                            throw new Exception("自动生成字串长度已经超过设定长度!");
                    }
                    else
                        throw new Exception("表中的数据无法进行自动编号,请联系软件开发商!");
                    result = sequence.ToString().PadLeft(length, '0');
                }
            }
            return result;
        }
        catch (Exception) { throw; }
    }
    #endregion

    public async Task<Dictionary<string, object>> getPostCommonAES(JObject param)
    {
        try
        {
            string procName = "";
            string _commonType = ""; // 类别
            string userID = "";
            bool hasUserIDPara = false;
            string sqlCompanyKey = "SELECT CompanyKey FROM Ghro_company WHERE IsEnable=1";
            DataTable dtCompanyKey = await Db.Ado.GetDataTableAsync(sqlCompanyKey);
            string tokenKey = "Tiobon";
            if (dtCompanyKey.Rows.Count > 0)
                tokenKey = dtCompanyKey.Rows[0][0].ToString();
            string token = "";
            string menuName = "";  // 页面别
            string exportSet = ""; // 导出配置

            var dic = new Dictionary<string, object>();
            string NewTokenstring = "";
            var sortedObj = new JObject(param.Properties().OrderBy(p => (string)p.Name));
            IEnumerable<JProperty> properties = sortedObj.Properties();
            foreach (JProperty item in properties)
            {
                if (item.Name == "token")
                {
                    token = item.Value.ToString();
                    continue;
                }
                else
                {
                    if (item.Name.ToLower() == "timestamp")
                    {
                        NewTokenstring = NewTokenstring + tokenKey + item.Value.ToString();
                        continue;
                    }
                    else
                    {
                        NewTokenstring = NewTokenstring + item.Value.ToString();
                    }
                }
                if (item.Name == "procName")
                {
                    procName = item.Value.ToString();
                    continue;
                }
                if (item.Name == "commonType")
                {
                    _commonType = item.Value.ToString();
                    continue;
                }
                if (item.Name == "userId")
                {
                    userID = item.Value.ToString();
                    hasUserIDPara = true;
                }
                if (item.Name == "menuName")
                {
                    menuName = item.Value.ToString();
                }
                if (item.Name == "exportSet")
                {
                    exportSet = item.Value.ToString();
                }

                string jokey = item.Name;
                object joValue = item.Value;

                dic.Add(jokey, joValue);
            }
            NewTokenstring = NewTokenstring.Replace("\r", "").Replace("\n", "").Replace(" ", "");
            NewTokenstring = Regex.Replace(NewTokenstring, @"\s+", "");
            //if (DBCommon.sha256(NewTokenstring).ToLower() != token.ToLower())
            //{
            //    //throw new Exception("token验证错误->" + NewTokenstring + "->" + DBCommon.sha256(NewTokenstring).ToLower());

            //}
            if (hasUserIDPara && (userID == "0" || string.IsNullOrEmpty(userID)) && procName != "PT_GHR30_Login_IUD" && procName != "PT_GHR30_UserPasswordReset_IUD")
            {
                throw new Exception("页面已失效,请重新登陆");
            }
            DataSet ds = await Db.Ado.UseStoredProcedure().GetDataSetAllAsync(procName, dic);
            // 导出Excel  ExportExcel 直接下载     ExportExcel2 预下载
            if (_commonType == "ExportExcel" || _commonType == "ExportExcel2")
            {
            }

            // 此块为存储过程返回的信息  DT_ProcedureResult
            DataTable DT_ProcedureResult = null;
            DataTable dt = ds.Tables[0];
            string strJson = "{";
            int i = 1;
            foreach (DataColumn dc in dt.Columns)
            {
                if (dt.Rows[0][dc.ColumnName].ToString() == "DT_ProcedureResult")
                {
                    DT_ProcedureResult = ds.Tables[i];
                }
                else
                {
                    strJson = strJson + "\"" + dt.Rows[0][dc.ColumnName].ToString() + "\":";
                    String json = JsonConvert.SerializeObject(ds.Tables[i]);

                    bool tableIsJson = false;
                    // 根据 table 的栏位名是否为 #Json#开头来判断,是否有Json对象 
                    foreach (DataColumn dcDetail in ds.Tables[i].Columns)
                    {
                        if (dcDetail.ColumnName.StartsWith("#Json#"))
                        {
                            tableIsJson = true;
                            break;
                        }
                    }
                    if (tableIsJson)
                    {
                        dynamic dyn = JsonConvert.DeserializeObject(json);
                        // DT_TableDataT1
                        if (ds.Tables[i].Rows.Count == 1 && (!dt.Rows[0][dc.ColumnName].ToString().StartsWith("DT_TableData")))// 单行数据
                        {
                            var obj = dyn[0];
                            foreach (DataColumn dcDetail in ds.Tables[i].Columns)
                            {
                                if (dcDetail.ColumnName.StartsWith("#Json#"))
                                {
                                    try
                                    {
                                        obj[dcDetail.ColumnName] = (JToken)JsonConvert.DeserializeObject((string)obj[dcDetail.ColumnName]);
                                    }
                                    catch { }
                                }
                            }
                            dyn = obj;
                        }
                        else
                        {
                            foreach (var obj in dyn)  // 逐行逐列判断
                            {
                                foreach (DataColumn dcDetail in ds.Tables[i].Columns)
                                {
                                    if (dcDetail.ColumnName.StartsWith("#Json#"))
                                    {
                                        try
                                        {
                                            obj[dcDetail.ColumnName] = (JToken)JsonConvert.DeserializeObject((string)obj[dcDetail.ColumnName]);
                                        }
                                        catch { }
                                    }
                                }
                            }
                        }
                        json = JsonConvert.SerializeObject(dyn);
                        json = json.Replace("#Json#", "");
                    }
                    strJson = strJson + json;
                    if (i < ds.Tables.Count - 1) // 第一个table定义 各表的内容
                        strJson = strJson + ",";
                }
                i = i + 1;
            }
            strJson = strJson + "}";
            string isOK = "0";
            string ErrorMsg = "";
            string WarnMsg = "";
            string SuccessMsg = "";
            string type = "success";
            string message = "";
            if (DT_ProcedureResult.Rows.Count == 1)
            {
                isOK = DT_ProcedureResult.Rows[0]["IsOK"].ToString();
                ErrorMsg = DT_ProcedureResult.Rows[0]["ErrorMsg"].ToString();
                WarnMsg = DT_ProcedureResult.Rows[0]["WarnMsg"].ToString();
                SuccessMsg = DT_ProcedureResult.Rows[0]["SuccessMsg"].ToString();
                if (isOK == "0")
                {
                    if (!string.IsNullOrEmpty(WarnMsg))
                    {
                        type = "warning";
                        message = WarnMsg;
                    }
                    else
                    {
                        type = "success";
                        message = SuccessMsg;
                    }
                }
                else
                {
                    type = "error";
                    message = ErrorMsg;
                }
            }
            var data = new Dictionary<string, object>
                {
                {"result", JObject.Parse(strJson)},
                {"message",message},
                {"type",type},
                {"code",int.Parse(isOK)}
                };
            foreach (DataColumn dcProcedureResult in DT_ProcedureResult.Columns)
            {
                if (dcProcedureResult.ColumnName != "IsOK" && dcProcedureResult.ColumnName != "ErrorMsg" &&
                    dcProcedureResult.ColumnName != "WarnMsg" && dcProcedureResult.ColumnName != "SuccessMsg")
                    data.Add(dcProcedureResult.ColumnName, DT_ProcedureResult.Rows[0][dcProcedureResult.ColumnName].ToString());
            }
            return data;
        }
        catch (Exception e)
        {
            var data = new Dictionary<string, object>
                {
                {"result", "{}"},
                {"message",e.Message},
                {"type","error"},
                {"code",1}
                };
            return data;
        }
    }

    public async Task<Dictionary<string, object>> getPostCommon(JObject param)
    {
        try
        {
            string procName = "";
            string _commonType = ""; // 类别
            string userID = "";
            IEnumerable<JProperty> properties = param.Properties();
            var dic = new Dictionary<string, object>();
            foreach (JProperty item in properties)
            {
                if (item.Name == "procName")
                {
                    procName = item.Value.ToString();
                    continue;
                }

                if (item.Name == "commonType")
                {
                    _commonType = item.Value.ToString();
                    continue;
                }
                if (item.Name == "userId")
                {
                    userID = item.Value.ToString();
                }

                string jokey = item.Name;
                string joValue = item.Value.ToString();
                dic.Add(jokey, joValue);
            }

            // procName = "PT_GHR30_Menu_GetWhere";
            // DataTable dtResult = DataAccess.SelectDate("Demo", procName, spParaList);                 
            // DataSet ds = GetProcedureDateSet("Demo", procName, "63", "1", "", "", "", "N", "", "1", "100", "3");
            DataSet ds = await Db.Ado.UseStoredProcedure().GetDataSetAllAsync(procName, dic);
            // 导出Excel  ExportExcel 直接下载     ExportExcel2 预下载

            // 此块为存储过程返回的信息  DT_ProcedureResult
            DataTable DT_ProcedureResult = null;
            DataTable dt = ds.Tables[0];
            string strJson = "{";
            int i = 1;
            foreach (DataColumn dc in dt.Columns)
            {
                if (dt.Rows[0][dc.ColumnName].ToString() == "DT_ProcedureResult")
                {
                    DT_ProcedureResult = ds.Tables[i];
                }
                else
                {
                    strJson = strJson + "\"" + dt.Rows[0][dc.ColumnName].ToString() + "\":";
                    String json = JsonConvert.SerializeObject(ds.Tables[i]);

                    bool tableIsJson = false;
                    // 根据 table 的栏位名是否为 #Json#开头来判断,是否有Json对象 
                    foreach (DataColumn dcDetail in ds.Tables[i].Columns)
                    {
                        if (dcDetail.ColumnName.StartsWith("#Json#"))
                        {
                            tableIsJson = true;
                            break;
                        }
                    }
                    if (tableIsJson)
                    {
                        dynamic dyn = JsonConvert.DeserializeObject(json);
                        // DT_TableDataT1
                        if (ds.Tables[i].Rows.Count == 1 && (!dt.Rows[0][dc.ColumnName].ToString().StartsWith("DT_TableData")))// 单行数据
                        {
                            var obj = dyn[0];
                            foreach (DataColumn dcDetail in ds.Tables[i].Columns)
                            {
                                if (dcDetail.ColumnName.StartsWith("#Json#"))
                                {
                                    try
                                    {
                                        obj[dcDetail.ColumnName] = (JToken)JsonConvert.DeserializeObject((string)obj[dcDetail.ColumnName]);
                                    }
                                    catch
                                    { }
                                }
                            }
                            dyn = obj;
                        }
                        else
                        {
                            foreach (var obj in dyn)  // 逐行逐列判断
                            {
                                foreach (DataColumn dcDetail in ds.Tables[i].Columns)
                                {
                                    if (dcDetail.ColumnName.StartsWith("#Json#"))
                                    {
                                        try
                                        {
                                            obj[dcDetail.ColumnName] = (JToken)JsonConvert.DeserializeObject((string)obj[dcDetail.ColumnName]);
                                        }
                                        catch
                                        { }
                                    }
                                }
                            }
                        }
                        json = JsonConvert.SerializeObject(dyn);
                        json = json.Replace("#Json#", "");
                    }
                    strJson = strJson + json;
                    if (i < ds.Tables.Count - 1) // 第一个table定义 各表的内容
                        strJson = strJson + ",";
                }
                i = i + 1;
            }
            strJson = strJson + "}";
            string isOK = "0";
            string ErrorMsg = "";
            string WarnMsg = "";
            string SuccessMsg = "";
            string type = "success";
            string message = "";
            if (DT_ProcedureResult.Rows.Count == 1)
            {
                isOK = DT_ProcedureResult.Rows[0]["IsOK"].ToString();
                ErrorMsg = DT_ProcedureResult.Rows[0]["ErrorMsg"].ToString();
                WarnMsg = DT_ProcedureResult.Rows[0]["WarnMsg"].ToString();
                SuccessMsg = DT_ProcedureResult.Rows[0]["SuccessMsg"].ToString();
                if (isOK == "0")
                {
                    if (!string.IsNullOrEmpty(WarnMsg))
                    {
                        type = "warning";
                        message = WarnMsg;
                    }
                    else
                    {
                        type = "success";
                        message = SuccessMsg;
                    }
                }
                else
                {
                    type = "error";
                    message = ErrorMsg;
                }
                /*
                if (!string.IsNullOrEmpty(isOK))
                {
                    type = "error";
                    message = ErrorMsg;
                }
                else if (!string.IsNullOrEmpty(WarnMsg))
                {
                    type = "warning";
                    message = WarnMsg;
                }
                if (!string.IsNullOrEmpty(SuccessMsg))
                {
                    type = "success";
                    message = SuccessMsg;
                } */
            }
            var data = new Dictionary<string, object>
            {
                {"result", JObject.Parse(strJson)},
                {"message",message},
                {"type",type},
                {"code",int.Parse(isOK)}
            };
            foreach (DataColumn dcProcedureResult in DT_ProcedureResult.Columns)
            {
                if (dcProcedureResult.ColumnName != "IsOK" && dcProcedureResult.ColumnName != "ErrorMsg" &&
                    dcProcedureResult.ColumnName != "WarnMsg" && dcProcedureResult.ColumnName != "SuccessMsg")
                    data.Add(dcProcedureResult.ColumnName, DT_ProcedureResult.Rows[0][dcProcedureResult.ColumnName].ToString());
            }
            return data;
        }
        catch (Exception e)
        {
            var data = new Dictionary<string, object>
            {
                {"result", "{}"},
                {"message",e.Message},
                {"type","error"},
                {"code",1}
            };
            return data;
        }
    }

    #region 获取多语
    public async Task<string> QueryLangValue(string key, int? langId, string defaultValue)
    {
        string sql = $"select [dbo].[FLangKeyToValue]('{key}',{langId},null)";
        string value = await Db.Ado.GetStringAsync(sql);
        if (value.IsNullOrEmpty()) value = defaultValue;
        return value;
    }
    public async Task<string> QueryLangValue(string key, string defaultValue)
    {
        return await QueryLangValue(key, App.User.GetLangId(), defaultValue);
    }
    #endregion

    #region 自动清理log
    public async Task AutoClearLog()
    {
        var list = new List<string>
        {
            "GlobalErrorLog",
            "GlobalInformationLog",
            "GlobalWarningLog",
            "AuditSqlLog"
        };
        var dt = DateTime.Now.AddMonths(-3);

        for (int i = 0; i < list.Count; i++)
        {
            var tableName = $"{list[i]}_{dt.Year}";
            if (dt.Month < 10)
                tableName += $"0{dt.Month}01";
            else
                tableName += $"{dt.Month}01";

            var sql = @$"IF EXISTS
                          (SELECT 1
                           FROM sysobjects
                           WHERE id = object_id ('{tableName}') AND type = 'U')
                    DROP TABLE {tableName}";
            await Db.Ado.ExecuteCommandAsync(sql);
        }
    }
    #endregion
}
