using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using Foresight.Data;
using Foresight.Fleet.Services.User;
using Foresight.Fleet.Services.Styles;

namespace IronIntel.Contractor.Users
{
    class AppModulesManagement
    {
        private const string FITracker = "FITracker";
        private const string Inspect = "Inspection";
        private const string TeamIntelligence = "TeamIntelligence";
        private const string FilterQ = "FilterQ";

        public static AppModuleInfo[] GetAvailableAppModuleInfos(UserInfo user)
        {
            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>();

            var pc = FleetServiceClientHelper.CreateClient<PermissionProvider>();
            FeatureModule[] ms = pc.GetAvailableModules(SystemParams.CompanyID, user.IID);
            Tuple<Feature, Permissions>[] pmss = pc.GetUserPermissions(SystemParams.CompanyID, user.IID);

            List<FeatureModule> moudles = new List<FeatureModule>();
            moudles.AddRange(ms);
            if (ms.FirstOrDefault(m => m.Id == FeatureModule.MODULE_MAPVIEW) == null)
                moudles.Insert(0, FeatureModule.Modules[0]);
            foreach (var m in moudles)
            {
                if (m.Id == FeatureModule.MODULE_TEAM && user.UserType != UserTypes.SupperAdmin)
                    continue;

                if (m.Id == FeatureModule.MODULE_MANAGEASSETS && pmss.FirstOrDefault(p => p.Item1.Id == Feature.MANAGE_ASSETS) == null)
                    continue;
                //if (m.Id == FeatureModule.MODULE_JOBSITES && pmss.FirstOrDefault(p => p.Item1.Id == Feature.JOB_SITES) == null)
                //    continue;

                AppModuleInfo ami = new AppModuleInfo();
                ami.ID = m.Id.ToString();
                ami.Name = m.Name;
                ami.Description = m.Description;
                ami.Url = m.Url;
                ami.IconPath = m.IconPath;
                ami.BackColor = m.BackgroundColor;
                ami.ForeColor = m.ForeColor;
                ami.OpenInNewWindow = false;
                ami.Visible = true;
                ami.ModuleType = AppModuleType.System;

                if (m.Id == FeatureModule.MODULE_JOBSITES)
                    ami.SubItems = ami.GetJobsiteNavigateItems(pmss);
                else if (m.Id == FeatureModule.MODULE_ASSETHEALTH)
                    ami.SubItems = ami.GetMaintenanceNavigateItems(pmss, user);
                else if (m.Id == FeatureModule.MODULE_SECURITY)
                    ami.SubItems = ami.GetSecurityNavigateItems(pmss, user);
                else if (m.Id == FeatureModule.MODULE_MANAGEASSETS)
                    ami.SubItems = ami.GetAssetsNavigateItems(pmss, user);
                else if (m.Id == FeatureModule.MODULE_CREDENTIAL)
                    ami.SubItems = ami.GetCredentialNavigateItems(pmss, user);

                if (ami.SubItems == null || ami.SubItems.Count > 0)
                    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;
        }

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