using System;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Xml;
using System.Text;
using QMFrameWork.WebUI.Attribute;
using QMAPP.Entity.Sys;
using QMAPP.Web.Models.Sys;
using QMAPP.Common.Web.Util;
using QMAPP.Common.Web.Controllers;
using QMFrameWork.WebUI.Menu;

namespace QMAPP.Web.Controllers
{
    /// <summary>
    /// 登录及主页控制
    /// </summary>
    [HandleError]
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            ViewData["Message"] = "Welcome to ASP.NET MVC!";

            return View();
        }

        public ActionResult About()
        {
            return View();
        }

        #region 登录载入

        /// <summary>
        /// 登录载入
        /// </summary>
        /// <returns>结果</returns>
        public ActionResult Login()
        {
            this.SetAreaMap();
            return View("Login");
        }

        #endregion

        #region 提交登录

        /// <summary>
        /// 提交登录
        /// </summary>
        /// <param name="login">登录信息</param>
        /// <returns></returns>
        [HandleException]
        [HttpPost]
        public ActionResult Login(LoginInfo login)
        {
            if (string.IsNullOrEmpty(login.LoginUserID))
            {
                 ViewData["Message"] = "用户名不能为空!";
                 return View("Login");

            }
            if (string.IsNullOrEmpty(login.PassWord))
            {
                ViewData["Message"] = "密码不能为空!";
                return View("Login");

            }

            #region 调用登录服务

            //QMAPP.ServicesAgent.LoginService.LoginServiceClient loginClient = new ServicesAgent.LoginService.LoginServiceClient();

            QMAPP.ServicesAgent.LoginService.LoginInfo servicelogin = QMAPP.ServicesAgent.LoginService.LoginServiceClient._IsLogin(new QMAPP.ServicesAgent.LoginService.LoginInfo { LoginUserID = login.LoginUserID.ToUpper(), PassWord = login.PassWord }
                , new QController().GetCredentialInfo());

            #endregion
            if (servicelogin == null)
            {
                this.SetAreaMap();
                ViewData["Message"] = "用户名或密码错误!";
                return View("Login");
            }
            

            List<string> powers = servicelogin.Powers.ToList();

            login = new QController().CopyToModel<LoginInfo, QMAPP.ServicesAgent.LoginService.LoginInfo>(servicelogin);
            login.Powers = powers;

            System.Web.HttpContext.Current.Session["MULT_LANG"] = Request.Form["selLang"];

            AccountController.SetLoginInfo(login);

            //获取个性设置信息
            QMAPP.ServicesAgent.ServiceAgent agent = new QController().GetServiceAgent();
            PersnalSet pSet = agent.InvokeServiceFunction<PersnalSet>("PersnalSetBLL_Get");

            //return Redirect("/Home/Default");
            return Redirect("/Home/Default?SystemID=Main");

            ////获取未读通知
            //string unReadNoticeStr = NoticeRemind();
            //ViewData["unReadNoticeStr"] = unReadNoticeStr;

            //return RedirectToAction("Index", "AppDesktop");

        }
 
        #endregion

        #region 主页载入

        /// <summary>
        /// 主页载入
        /// </summary>
        /// <returns></returns>
        [HandleException]
        public ActionResult Default()
        {
            ViewData["Message"] = "Welcome to ASP.NET MVC!";
            LoginInfo login = null;
            MenuHelper helper = new MenuHelper();
            PowerUtil pu = new PowerUtil();
            string systemID = Request.QueryString["SystemID"];
            string menuID = Request.QueryString["menuID"];
            try
            {
                //验证当前请求是否有登录信息
                if (AccountController.IsLogin() == false)
                {
                    //登录信息不正确
                    Response.Write("<script language=\"javascript\">top.window.location.href=\"/Home/Login/\";</script>");
                    Response.End();
                    return View(new Models.DefaultModel());
                }

                //获取登录信息
                login = AccountController.GetLoginInfo();
                if (AccountController.GetLoginInfo().LoginUserID.ToLower() != "admin")
                {
                    //获取登录用户权限
                    helper.Powers = login.Powers;
                    //20180817闫永刚再次获取POWER信息
                    try
                    {
                        QMAPP.ServicesAgent.ServiceAgent agent = new QController().GetServiceAgent();
                        helper.Powers = agent.InvokeServiceFunction<List<string>>("LoginBLL_GetPower", login);
                    }
                    catch (Exception ex)
                    {
                        
                        
                    }
                    
                }

                //取得所有权限菜单
                List<MenuInfo> menus = helper.GetMenuInfos();
                if (string.IsNullOrEmpty(systemID)==true)
                {
                    systemID = "Main";
                }
                menus = menus.Where(p => p.SystemID == systemID).ToList();

                //将权限放入到session中
                Hashtable actions = helper.GetActionList();

                AccountController.SetLimit(actions);

                //构建主页面信息
                Models.DefaultModel defaultModel = new Models.DefaultModel();
                defaultModel.UserDes = login.UserName;
                
                OutLookMenu menu = new OutLookMenu();
                defaultModel.MenuHtml = menu.GetMenuHtml(menus);
                defaultModel.SystemID = systemID;
                defaultModel.DefaultMenuID = menuID==null?"":menuID;
                defaultModel.UserID = login.UserID;
                defaultModel.LoginSessionID = System.Web.HttpContext.Current.Session.SessionID;

                #region 预登录
                if (systemID != "ManageCenter" 
                    && ConfigurationManager.AppSettings[systemID + "Root"] != null)
                {
                    defaultModel.AppLoginUrl = ConfigurationManager.AppSettings[systemID + "Root"] + "/Login/Login?sessionID=" + System.Web.HttpContext.Current.Session.SessionID+"&isLogin=login";
                }
                else
                {
                    defaultModel.AppLoginUrl = "";
                }
                #endregion

                #region 获取未读通知

                //获取未读通知
                string unReadNoticeStr = NoticeRemind();
                defaultModel.UnReadNoticeStr = unReadNoticeStr;

                #endregion 

                return View(defaultModel);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion

        #region 注销

        /// <summary>
        /// 注销
        /// </summary>
        /// <returns>结果</returns>
        [HandleException]
        public ActionResult Logout()
        {
            AccountController.Logout();
            return RedirectToAction("Login");
        }

        #endregion

        #region 获取未读通知 王丹丹
        /// <summary>
        /// 获取未读通知
        /// </summary>
        /// <returns></returns>
        public string NoticeRemind()
        {
            NoticeInfoModel model = new NoticeInfoModel();
            NoticeInfo notice = new NoticeInfo();
            string noticestr = "";
            string noticeNoReadCount="";
            try
            {
                notice.UserID = AccountController.GetLoginInfo().UserID; 
                //获取未读通知 
                QMAPP.ServicesAgent.ServiceAgent agent = new QController().GetServiceAgent();
                model.listNoticeModel = agent.InvokeServiceFunction<List<NoticeInfo>>("NoticeManageBll_GetNotReadNotice", notice);
                 
                //获取未读通知的数量
                noticeNoReadCount = model.listNoticeModel.Count(item => item.ISREAD == "0").ToString(); 
                noticestr = "<li class=\"purple\"><a data-toggle=\"dropdown\" class=\"dropdown-toggle\" href=\"#\"> ";
                noticestr += "<i class=\"ace-icon fa fa-bell icon-animated-bell\"></i><span class=\"badge badge-important\"> " + noticeNoReadCount + " </span> </a>";
                noticestr += "<ul class=\"dropdown-menu-right dropdown-navbar navbar-pink dropdown-menu dropdown-caret dropdown-close\">";
                noticestr += "<li class=\"dropdown-header\"><i class=\"ace-icon fa fa-exclamation-triangle\"></i>" + noticeNoReadCount + "条通知</li>";

                foreach (var item in model.listNoticeModel)
                {
                    string noticeTitle = "";
                    string noticeTime = "";
                    string noticeID = "";
                    if (item.NOTICETITLE.Length < 15)
                    {
                        noticeTitle = item.NOTICETITLE;
                    }
                    else
                    {
                        noticeTitle = item.NOTICETITLE.Substring(0,15)+"...";
                    }
                    
                    noticeTime = item.USETIME.ToString("yyyy-MM-dd");
                    noticeID = item.NOTICEID;
                    noticestr += "<li><a href=\"#\" onclick=\"ClickNotice('" + noticeID + "');\"><div class=\"clearfix\"><span class=\"pull-left\">";
                    noticestr += "<i class=\"btn btn-xs no-hover btn-success fa fa-bell\"></i>&nbsp; " + noticeTitle + "</span>";
                    noticestr += "<span class=\"pull-right badge badge-success\">" + noticeTime + "</span></div></a></li>";
                } 

                noticestr += "<li class=\"dropdown-footer\"><a href=\"#\" onclick=\"MoreNotice();\">查看所有通告<i class=\"ace-icon fa fa-arrow-right\">";
                noticestr += "</i></a></li></ul></li>";  
                 
                return noticestr;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 获取地区地图

        private void SetAreaMap()
        {
            //设置地图图片
            string areaName = "";
            if (string.IsNullOrEmpty(ConfigurationManager.AppSettings["AreaCode"]) == false)
                areaName = ConfigurationManager.AppSettings["AreaCode"];
            switch (areaName)
            {
                case "长春":
                    ViewData["loginmap"] = "changchunmap.png";
                    break;
                case "成都":
                    ViewData["loginmap"] = "chengdumap.png";
                    break;
                case "佛山":
                    ViewData["loginmap"] = "foshanmap.png";
                    break;
            }
        }

        #endregion
    }
}