using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using Foresight.Data;
using IronIntel.Contractor.Users;
using IronIntel.Services;

namespace IronIntel.Contractor.Users
{
    class AppModulesManagement
    {
        private const string FITracker = "FITracker";
        private const string Inspect = "Inspection";
        private const string TeamIntelligence = "TeamIntelligence";
        public static AppModuleInfo[] GetAvailableAppModuleInfos(UserInfo user)
        {
            const string SQL = @"select ID,APPMODULENAME,APPMODULEDESC,URL,ICONPATH,BACKCOLOR,FORECOLOR,OPENINNEWWINDOW from APPMODULES where VISIBLE>0 and (isnull(SITETYPE,'All')='All' or SITETYPE={0}) ";

            if (user == null)
            {
                return new AppModuleInfo[0];
            }

            string sql = SQL;
            switch (user.UserType)
            {
                case UserTypes.Readonly:
                    sql = SQL + " and SECURITYLEVEL=0";
                    break;
                case UserTypes.Common:
                    sql = SQL + " and SECURITYLEVEL<=1";
                    break;
                case UserTypes.Admin:
                    sql = SQL + " and SECURITYLEVEL<=2";
                    break;
                case UserTypes.SupperAdmin:
                    sql = SQL + " and SECURITYLEVEL<=3";
                    break;
                default:
                    sql = SQL;
                    break;
            }

            sql = sql + " order by ORDERINDEX ";

            FIDbAccess db = SystemParams.GetDbInstance();
            DataTable dt = db.GetDataTableBySQL(sql, SystemParams.CustomerDetail.CustomerType);

            CustUIStyle style = SystemParams.GetUIStyle(user.IID);//获取样式设置
            string moudleBackgroundColor = "#0078D7";
            if (style != null && !string.IsNullOrEmpty(style.MenuBackgroundColor))
                moudleBackgroundColor = style.MenuBackgroundColor;

            List<AppModuleInfo> list = new List<AppModuleInfo>();
            bool fitracter = SystemParams.HasLicense(FITracker);
            bool inspect = SystemParams.HasLicense(Inspect);
            bool teamintelligence = SystemParams.HasLicense(TeamIntelligence);
            foreach (DataRow dr in dt.Rows)
            {
                AppModuleInfo ami = ConvertToAppModule(dr);
                ami.BackColor = moudleBackgroundColor;
                if (ami.ID.Equals(FITracker, StringComparison.OrdinalIgnoreCase))
                {
                    if (fitracter)
                        list.Add(ami);
                }
                else if (ami.ID.Equals(Inspect, StringComparison.OrdinalIgnoreCase))
                {
                    if (inspect)
                        list.Add(ami);
                }
                else if (ami.ID.Equals(TeamIntelligence, StringComparison.OrdinalIgnoreCase))
                {
                    if (teamintelligence)
                        list.Add(ami);
                }
                else
                    list.Add(ami);
            }
            AppModuleInfo[] wsps = GetFICWorkspace(user);
            foreach (AppModuleInfo ap in wsps)
            {
                if (!Exists(ap.Url, list))
                {
                    ap.BackColor = moudleBackgroundColor;
                    list.Add(ap);
                }
            }
            return list.ToArray();
        }

        private static bool Exists(string url, IEnumerable<AppModuleInfo> items)
        {
            foreach (AppModuleInfo item in items)
            {
                if (string.Compare(url, item.Url, true) == 0)
                {
                    return true;
                }
            }
            return false;
        }

        private static AppModuleInfo ConvertToAppModule(DataRow dr)
        {
            AppModuleInfo ai = new AppModuleInfo();
            ai.ID = FIDbAccess.GetFieldString(dr["ID"], string.Empty);
            ai.Name = FIDbAccess.GetFieldString(dr["APPMODULENAME"], string.Empty);
            ai.Description = FIDbAccess.GetFieldString(dr["APPMODULEDESC"], string.Empty);
            ai.Url = FIDbAccess.GetFieldString(dr["URL"], string.Empty);
            ai.IconPath = FIDbAccess.GetFieldString(dr["ICONPATH"], string.Empty);
            ai.BackColor = FIDbAccess.GetFieldString(dr["BACKCOLOR"], string.Empty);
            ai.ForeColor = FIDbAccess.GetFieldString(dr["FORECOLOR"], string.Empty);
            ai.OpenInNewWindow = FIDbAccess.GetFieldInt(dr["OPENINNEWWINDOW"], 0) == 1;
            ai.Visible = true;
            ai.ModuleType = AppModuleType.System;
            return ai;
        }

        private static AppModuleInfo[] GetFICWorkspace(UserInfo user)
        {
            if (string.IsNullOrWhiteSpace(SystemParams.FICDbConnectionString))
            {
                return new AppModuleInfo[0];
            }

            string SQL = @"select w.IID,isnull(l.WorkSpaceName,w.WSPNAME) as WSPNAME,w.WSPDESCRIPTION from WORKSPACE w
                left join WorkSpaceLanguage l on w.IID=l.WorkspaceIID and l.LanguageCode='en-us'
                where (ISPUBLIC=1 or ISPUBLIC>10)";

            FISqlConnection db = new FISqlConnection(SystemParams.FICDbConnectionString);
            if (user.UserType == UserTypes.Readonly)
            {
                SQL += " and w.IID in( select ObjectValue from UserDefaultInfo where UserID='" + user.IID + "' and UserDefaultType=0)";
            }
            SQL += " order by isnull(l.WorkspaceName,w.WSPNAME)";



            DataTable tb = db.GetDataTableBySQL(SQL);
            List<AppModuleInfo> ls = new List<AppModuleInfo>();
            foreach (DataRow dr in tb.Rows)
            {
                AppModuleInfo ap = new AppModuleInfo();
                ap.ID = dr["IID"].ToString();
                ap.Name = FIDbAccess.GetFieldString(dr["WSPNAME"], string.Empty);
                ap.OpenInNewWindow = false;
                ap.Description = FIDbAccess.GetFieldString(dr["WSPDESCRIPTION"], string.Empty);
                ap.Visible = true;
                if (string.IsNullOrWhiteSpace(ap.Description))
                {
                    ap.Description = ap.Name;
                }
                ap.ForeColor = "white";
                ap.Url = @"fic/Workspace.aspx?IID=" + ap.ID;
                ap.IconPath = @"img/modules/pie1.png?t=0";
                ap.ModuleType = AppModuleType.Workspace;
                ls.Add(ap);
            }
            return ls.ToArray();
        }

        public static SecurityNavigateItem[] GetSecurityNavigateItems(UserInfo user)
        {
            const string SQL = "select * from SECURITYNAVNODE where (isnull(SITETYPE,'All')='All' or SITETYPE={0}) order by ORDERINDEX";

            if ((user == null) || (user.UserType == UserTypes.Readonly) || (user.UserType == UserTypes.Common))
            {
                return new SecurityNavigateItem[0];
            }

            FIDbAccess db = SystemParams.GetDbInstance();
            DataTable dt = db.GetDataTableBySQL(SQL, SystemParams.CustomerDetail.CustomerType);
            List<SecurityNavigateItem> ls = new List<SecurityNavigateItem>();
            foreach (DataRow dr in dt.Rows)
            {
                SecurityNavigateItem si = new SecurityNavigateItem();
                si.ID = FIDbAccess.GetFieldString(dr["NODEID"], string.Empty);
                si.Title = FIDbAccess.GetFieldString(dr["TITLE"], string.Empty);
                si.IconPath = FIDbAccess.GetFieldString(dr["ICONPATH"], string.Empty);
                si.Url = FIDbAccess.GetFieldString(dr["TARGETURL"], string.Empty);

                if ("nav_dts" == si.ID.ToLower())
                    si.Url = "../fic/fic/Management/DataTablePermission.aspx";
                if ("nav_filters" == si.ID.ToLower())
                    si.Url = "../fic/fic/Management/FiltersManagement.aspx";
                ls.Add(si);
            }
            return ls.ToArray();
        }
    }
}
