using System.Data;
using AgileObjects.AgileMapper;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SqlSugar;
using Tiobon.Core.Common;
using Tiobon.Core.Common.DB.Dapper;
using Tiobon.Core.DataAccess;
using Tiobon.Core.IServices;
using Tiobon.Core.Model;
using Tiobon.Core.Services.BASE;

namespace Tiobon.Core.Services;

public partial class CommonServices : BaseServices<RootEntityTkey<int>>, ICommonServices
{
    IHttpContextAccessor _httpContextAccessor;
    ILogger<PayServices> _logger;
    public CommonServices(ILogger<PayServices> logger, IHttpContextAccessor httpContextAccessor)
    {
        _logger = logger;
        _httpContextAccessor = httpContextAccessor;
    }

    #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
                        ) 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 = 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,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.ForEach(x =>
        {
            if (!string.IsNullOrWhiteSpace(x.searchOperator1))
                x.searchOperator = JsonConvert.DeserializeObject<List<searchOperator>>(x.searchOperator1);
            x.searchOperator1 = null;
        });
        Db.Ado.CommitTran();

        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);
        result.DT_PageMutiMsg = Db.Ado.SqlQuery<DT_PageMutiMsg>(sql);

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

        #endregion

        #region 特殊处理
        var toolbar = new Toolbar();
        var index = -1;
        switch (param.menuName)
        {
            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"; }
                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"
                });

                break;
            case "F_ExamPaperReleased":
                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-publish",
                    position = "left"
                });
                result.JM_PageControlT1.Toolbar.Insert(1, new Toolbar()
                {
                    display = true,
                    fnKey = "TBD5YN",
                    fnTitle = "停用",
                    fnType = "table",
                    icon = "ghr-icon-stop",
                    position = "left"
                });

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

                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 = "TBD4YN"; }
                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"
                });

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

                break;

            case "F_CourseClassification":
            case "F_CourseScene":
                index = result.JM_PageControlT1.Toolbar.FindIndex(x => x.fnKey == "BatchUpdateYN");
                result.JM_PageControlT1.Toolbar.RemoveAt(index);
                break;

        }

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

    #region 获取通用列表下拉
    /// <summary>
    /// 获取通用列表下拉
    /// </summary>
    /// <param name="type"></param>
    /// <returns></returns>
    public async Task<ServiceResult<CommonSelect>> GetSelectAsync(string type)
    {
        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 JProperty("defaultHidden", true),
                new JProperty("field","value"),
                new JProperty("label","课程ID"),
            ];
                TableColumn.Add(searchItem);
                searchItem = [
                    new JProperty("field","label"),
                new JProperty("label","课程编号"),
            ];
                TableColumn.Add(searchItem);

                sql = "SELECT Id, CourseNo, CourseName FROM Ghre_Course WHERE IsEnable=1 AND Status='Released'";
                dt = await Db.Ado.GetDataTableAsync(sql);

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    item = [
                        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 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 JProperty("defaultHidden", true),
                new JProperty("field","value"),
                new JProperty("label","场景ID"),
            ];
                TableColumn.Add(searchItem);
                searchItem = [
                    new JProperty("field","label"),
                new JProperty("label","场景"),
            ];
                TableColumn.Add(searchItem);

                sql = "SELECT Id, SceneNo, SceneName FROM Ghre_CourseScene";
                dt = await Db.Ado.GetDataTableAsync(sql);

                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    item = [
                        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 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 JProperty("defaultHidden", true),
                    new JProperty("field","value"),
                    new JProperty("label","value")
                ];
                TableColumn.Add(searchItem);
                searchItem = [
                    new JProperty("field","label"),
                    new JProperty("label","label")
                    ];
                TableColumn.Add(searchItem);
                item = [
                    new JProperty("value","Manual"),
                    new JProperty("label","人工评分")
                  ];
                DT_TableDataT1.Add(item);
                item = [
                    new JProperty("value","System"),
                    new JProperty("label","系统评分")
                    ];
                DT_TableDataT1.Add(item);

                item = [
                    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 JProperty("defaultHidden", true),
                    new JProperty("field","value"),
                    new JProperty("label","value")
                ];
                TableColumn.Add(searchItem);
                searchItem = [
                    new JProperty("field","label"),
                    new JProperty("label","label")
                    ];
                TableColumn.Add(searchItem);
                item = [
                    new JProperty("value","Easy"),
                    new JProperty("label","简单")
                  ];
                DT_TableDataT1.Add(item);
                item = [
                    new JProperty("value","Normal"),
                    new JProperty("label","普通")
                    ];
                DT_TableDataT1.Add(item);
                item = [
                    new JProperty("value","Hard"),
                    new JProperty("label","困难")
                    ];
                DT_TableDataT1.Add(item);

                item = [
                    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 JProperty("defaultHidden", true),
                    new JProperty("field","value"),
                    new JProperty("label","value")
                ];
                TableColumn.Add(searchItem);
                searchItem = [
                    new JProperty("field","label"),
                    new JProperty("label","label")
                    ];
                TableColumn.Add(searchItem);
                item = [
                    new JProperty("value","Single"),
                    new JProperty("label","单选题")
                  ];
                DT_TableDataT1.Add(item);
                item = [
                    new JProperty("value","Multiple"),
                    new JProperty("label","多选题")
                    ];
                DT_TableDataT1.Add(item);
                item = [
                    new JProperty("value","TrueOrFalse"),
                    new JProperty("label","判断题")
                    ];
                DT_TableDataT1.Add(item);
                item = [
                    new JProperty("value","Completion"),
                    new JProperty("label","填空题")
                    ];
                DT_TableDataT1.Add(item);
                item = [
                    new JProperty("value","ShortAnswer"),
                    new JProperty("label","简答题")
                    ];
                DT_TableDataT1.Add(item);

                item = [
                    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导入模板
    /// <summary>
    /// Excel导入模板
    /// </summary>
    /// <param name="param"></param>
    /// <returns></returns>
    public async Task<ServiceResult<QueryExportReturn>> DownImportTemplateAsync(QueryExport param)
    {
        var result = new QueryExportReturn();

        var tableNmae = string.Empty;
        var menuName = string.Empty;
        string sql = "select QueryProcedure, EditProcedure, IUDProcedure, MenuName 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();
            menuName = dt.Rows[0]["MenuName"].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");
        await ReportHelper.ImportTemplate(Db, columns, dt, menuName);


        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
}
