using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Text;
using System.Web;
using System.Web.SessionState;
using System.Web.Security;
using System.Reflection;
using Mammonth.Common;
using Northwind.Model;
using Northwind.BLL;
using System.Net;

namespace Northwind.Web.Service {
    /// <summary>
    /// UserService 的摘要说明
    /// </summary>
    public class _AdminLoginService : IHttpHandler, IRequiresSessionState {

        #region 固定方法，无需修改
        public bool IsReusable {
            get {
                return false;
            }
        }
        public void ProcessRequest(HttpContext context) {
            //
            string methodName = context.Request["method"];
            if (string.IsNullOrEmpty(methodName)) {
                methodName = context.Request["do"];
            }
            if (string.IsNullOrEmpty(methodName)) {
                return;
            }
            Type type = this.GetType();
            MethodInfo method = type.GetMethod(methodName);   //获取要执行的方法
            if (method == null) {
                //没有找到要执行的方法
                OutputError(string.Format("没有找到方法:{0}", methodName));
                return;
            }
            try {
                //调用方法
                method.Invoke(this, null);
            } catch (Exception ex) {
                OutputError(ex.Message);
            } finally {
                //日记记录
                AfterInvoke(methodName);
            }
        }
        //日志管理
        protected void AfterInvoke(string methodName) {

        }
        #endregion

        /// <summary>
        /// 用户登录
        /// </summary>
        public void Login() {
            //获取提交的数据
            string submitJSON = HttpContext.Current.Request["submitData"];
            Hashtable data = (Hashtable)JSON.Decode(submitJSON);
            //进行数据处理

            string UserName = Convert.ToString(data["username"]);
            string PassWord = Convert.ToString(data["pwd"]);
            string CheckCode = Convert.ToString(data["checkcode"]);
            //
            if ((HttpContext.Current.Session["CheckCode"] == null || CheckCode != HttpContext.Current.Session["CheckCode"].ToString())) {

                OutputError("验证码输入错误");
                return;
            }
            //获取MD5加密值
            PassWord = (PassWord.Length != 32) ? SafeConfig.GetMD5(PassWord) : PassWord;
            AdminBLL bll = new AdminBLL();
            Admin model = bll.Exists(UserName, PassWord);//查询用户是否存在         
            if (model != null) { //登录成功 
                SetLoginStruct(model); 
                //返回处理结果
                HttpContext.Current.Response.Write("{\"message\":\"登录成功\"}");
            } else {
                //登录失败         
                string error = bll.GetLastError();
                OutputError(string.Format("登录失败,请检查账号密码是否正确:{0}", error));
            }
        }

        /// <summary>
        /// 用户注销
        /// 仅仅由主框架页面/Admin/index/main.html退出链接调用
        /// </summary>
        /// <remarks>
        /// creater: zhaoshunlu 2013-11-8
        /// </remarks>
        public void Logout() {
            //清除在线人员列表    
            if (HttpContext.Current.Session["LoginAdminStruct"] != null) {
                LoginAdminStruct userStruct = (LoginAdminStruct)HttpContext.Current.Session["LoginAdminStruct"];
                //
                HttpContext.Current.Session["LoginAdminStruct"] = null;
            }
            //取消当前回话
            HttpContext.Current.Session.Abandon();
            HttpContext.Current.Response.Write("y");
        }

        /// <summary>
        /// 保存修改密码
        /// </summary>
        /// <remarks>
        /// creater: zhaoshunlu 2013-11-8
        /// </remarks>
        public void ChangedPassWord() {
            //清除在线人员列表    
            if (HttpContext.Current.Session["LoginAdminStruct"] != null) {
                LoginAdminStruct userStruct = (LoginAdminStruct)HttpContext.Current.Session["LoginAdminStruct"];
                //
                string UserName = userStruct.UserName;
                string PassWord = HttpContext.Current.Request["PassWord"];
                string OldPassWord = HttpContext.Current.Request["OldPassWord"];

                PassWord = SafeConfig.GetMD5(PassWord);
                OldPassWord = SafeConfig.GetMD5(OldPassWord);
                //
                AdminBLL bll = new AdminBLL();
                if (bll.ChengedPwd(UserName, PassWord, OldPassWord)) { //修改成功
                    //返回处理结果
                    HttpContext.Current.Response.Write("{\"message\":\"登录成功\"}");
                } else {
                    //登录失败         
                    string error = bll.GetLastError();
                    OutputError(string.Format("保存修改密码失败:{0}", error));
                }
            } else {
                OutputError("还没有登录或者登录已经超时！");
            }
        }



        /// <summary>
        /// 获取登录用户信息
        /// 由每个需要验证用户登录权限的页面加载时调用一次。
        /// </summary>
        public void GetUserData() {
            if (HttpContext.Current.Session["LoginAdminStruct"] == null) {
                OutputError("还没有登录或者登录已经超时！");
            } else {
                LoginAdminStruct userStruct = (LoginAdminStruct)HttpContext.Current.Session["LoginAdminStruct"];
                //直接返回用户登录资料信息
                string josndef = "{\"msg\":\"默认权限\",IsQuery: \"Y\", \"IsEdit\":\"Y\", \"IsDele\": \"Y\", \"Bstop\": false }";
                userStruct.AccessPower = JSON.Decode<Hashtable>(josndef);
                //
                HttpContext.Current.Response.Write(JSON.Encode(userStruct));
            }
        }

        /// <summary>
        /// 获取在线用户和系统消息
        /// 由主框架页面index/main.html 按一定的刷新率 实时调用获取。
        /// </summary>
        public void GetOnLineUser() {

            CheckAdminToAutoLogin();//2014-10-21 检查并自动登录

            StringBuilder sb = new StringBuilder();
            sb.Append("{");
            //检查是否在线
            if (HttpContext.Current.Session["LoginAdminStruct"] != null) {
                sb.Append("LoginState:true,Message:\"在线\"");
            } else {
                //不在线 LoginState:false
                sb.Append("LoginState:false,Message:\" 超时\"");
            }
            sb.Append("}");
            //
            string json = sb.ToString();
            HttpContext.Current.Response.Write(json);
        }
        /// <summary>
        /// 设置登录状态，创建Session和身份验证票证
        /// </summary>
        /// <param name="model">请求登录的对象</param>
        /// <param name="bFristLogin">是否正常登录,true 用户自主登录，false 系统自动登录(比如掉线后自动登录)</param>
        /// <remarks>
        /// 创建 zhaoshunlu 2014-10-21
        /// </remarks>
        private static void SetLoginStruct(Admin model, bool bFristLogin = true) {
            if (model == null) return;
            //踢重复登录用户下线,替换掉会话信息
            //
            //设置登录信息                 
            LoginAdminStruct user = new LoginAdminStruct();
            user.SessionID = HttpContext.Current.Session.SessionID;//登录回话ID
            //user.LoginIP = HttpContext.Current.Request.UserHostAddress;
            //user.LoginTime = System.DateTime.Now; 
            //user.UserID = model.ID.ToString();
            user.UserName = model.Name;         //用户名  
            //
            //保存登录信息  到SESSION
            HttpContext.Current.Session["LoginAdminStruct"] = user;
            // 
            if (bFristLogin) {
                //更新用户登录次数和登录时间  
                //model.loginCount = loginCount+1;               //登录次数
                //model.LastLoginTime = System.DateTime.Now;     //最后登录时间 
                //model.LoginIP = HttpContext.Current.Request.UserHostAddress; //IP
                //bll.UpdateForm(model, new string[] { "loginCount", "LastLoginTime" });
                //
                //添加票据               
                FormsAuthentication.SetAuthCookie( user.UserName, true);
                //HttpContext.Current.Response.Redirect(FormsAuthentication.GetRedirectUrl( user.UserName, false));                
            }
        }

        /// <summary>
        /// 检查用户登录信息，如果已经掉线就根据验证票证自动登录
        /// 由每个具体业务的web接口ashx页面加载时调用一次。
        /// html页面请勿调用它
        /// </summary>
        /// <remarks>
        /// creater: zhaoshunlu  2014-10-21
        /// </remarks>
        public static void CheckAdminToAutoLogin() {
            //--beging zhao 2014-10-21增加
            //防止Session不稳定导致会话超时丢失，根据票证重新获取用户信息，保持一直在线
            if (HttpContext.Current.User.Identity.IsAuthenticated) {
                if (HttpContext.Current.Session["LoginAdminStruct"] == null) {
                    string name = HttpContext.Current.User.Identity.Name; //当前用户名 如00001009
                    //
                    AdminBLL bll = new AdminBLL();
                    Admin model = bll.GetOneByName(name);//查询用户是否存在 
                    SetLoginStruct(model, false);//系统自动登录，非用户自主登录，
                }
            }
        }

        /// <summary>
        ///  获取主工具栏系统主菜单,根据权限控制某些项目的显示与隐藏
        /// </summary>
        /// <returns></returns>    
        /// <remarks> 
        /// 调用页面 /Admin/index/main.html
        /// 创建人及日期：ZhaoShunLu 2013-7-31
        /// <para>修改人、日期及内容:</para>
        /// </remarks>
        public void GetSysMenuToolBar() {

            StringBuilder sb = new StringBuilder();
            if (HttpContext.Current.Session["LoginAdminStruct"] != null) {
                LoginAdminStruct user = (LoginAdminStruct)HttpContext.Current.Session["LoginAdminStruct"];
                //
                string webroot = HttpContext.Current.Server.MapPath("/"); //站点根目录，后面已经有\,如E:\Web\
                string CommonData = webroot + "Admin\\CommonData\\";
                //
                //1 获取功能开关列表 
                //直接从json配置文件中读取
                string funSwitch = Template.ReadJSON(CommonData + "_Default\\systemtoolbar.txt");// + System.DateTime.Now.ToString("yyyyMMddHHmmssffff"))
                IList<MenuSetInfo> menulist = JSON.Decode<IList<MenuSetInfo>>(funSwitch);
                //2 
                string comDesign = Template.ReadJSON(CommonData + "_Default\\adornment.txt");
                //3 获取用户所在权限组权限项集合 
				//--权限组权限项
				//
                sb.Append("{"); 
                //
                #region MenuItems  [2013-8-7 ZhaoShunLu]
                sb.AppendFormat("MenuItems:[");
                bool IsPHas = false;
                for (int i = 0; i < menulist.Count; i++) {
                    if (user.RightGroupID != 0) {//user.RightGroupID != 0 用户已经设置权限组
                        if (menulist[i].enable) { 
                            if (IsPHas) {
                                sb.Append(",");
                            }
                            sb.Append("{");
                            sb.AppendFormat("id: \"{0}\",iconCls: \"{1}\", text: \"{2}\" ,  url:\"{3}\"", menulist[i].id, menulist[i].icon, menulist[i].name, menulist[i].target);
                            sb.Append("}");
                            IsPHas = true; 
                        } else {
                            if (!IsPHas)
                                IsPHas = false;
                        }
                    }
                }
                sb.Append("]");
                #endregion
                //
                if (!string.IsNullOrEmpty(comDesign)) {
                    comDesign = comDesign.Substring(1, comDesign.Length - 2).Replace("'", "\""); //去掉前后的{}符号
                    sb.Append(",");
                    sb.Append(comDesign);
                }
                //---
                sb.Append("}");
            } else {
                sb.Append("[]");
            }
            //
            string json = sb.ToString();
            HttpContext.Current.Response.Write(json);
        }
        /// <summary>
        /// 获取左侧边系统主菜单,根据权限控制某些项目的显示与隐藏
        /// 调用页面：/Admin/index/main.html
        /// </summary>
        public void GetSysMenuTree() {
            if (HttpContext.Current.Session["LoginAdminStruct"] != null) {
                LoginAdminStruct user = (LoginAdminStruct)HttpContext.Current.Session["LoginAdminStruct"];
                //直接从json配置文件中读取
                string webroot = HttpContext.Current.Server.MapPath("/"); //站点根目录，后面已经有\,如E:\Web\ 
                string CommonData = webroot + "Admin\\CommonData\\";
                string funSwitch = Template.ReadJSON(CommonData + "_Default\\systemtreemenu.txt"); 
                //
                HttpContext.Current.Response.Write(funSwitch);
            } else {
                HttpContext.Current.Response.Write("[]");
            }
        }
        
        /// <summary>
        /// 输出错误消息
        /// </summary>
        /// <param name="errMsg">错误消息</param>
        /// <param name="errCode">错误代码,特定值：1000 超时或者未登录,999 无权限操作</param>
        /// <remarks>
        /// 创建：zhaoshunlu 214-07-10
        /// </remarks>
        private void OutputError(string errMsg, string errCode = "1000") {
            Hashtable result = new Hashtable();
            result["error"] = errMsg;
            result["code"] = errCode;
            result["errorCode"] = errCode;
            result["message"] = errMsg;
            result["stackTrace"] = "";

            string json = JSON.Encode(result);
            //
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Write(json);
        }
    }
}