using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using HySoft.Common;
using System.Data;
using System.IO;
using System.Text;

namespace HySoft.BaseCallCenter.Web.tools
{
    /// <summary>
    /// login 的摘要说明
    /// </summary>
    public class login : IHttpHandler
    {
        public DateTime ExpiredTime = Convert.ToDateTime(ReadFile(HttpRuntime.AppDomainAppPath + "tools\\hykj.hy"));
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            //取得处事类型
            string action = CommonRequest.GetQueryString("action");
            switch (action)
            {
                case "login":
                    context.Response.Write(Login(context));
                    break;
            }
        }
        private string Login(HttpContext context)
        {
            string username = CommonRequest.GetQueryString("username");
            string extensionphone = CommonRequest.GetQueryString("extensionphone");
            string password = CommonRequest.GetQueryString("password");
            string res = "未知错误，请重新登录";
            bool appResult = LoodLoop();
            if (appResult)
            {
                DataTable dt = new DataTable();
                try
                {
                    dt = new BaseCallCenter.BLL.T_Sys_UserAccount().GetList("F_UserCode='" + username.Trim() + "' and F_PassWord='" + password.Trim() + "'").Tables[0];
                    if (dt != null)
                    {
                        if (dt.Rows.Count > 0)
                        {
                            if (dt.Rows[0]["F_UserCode"].ToString() == dt.Rows[0]["F_PassWord"].ToString())
                            {
                                res = "firstlogin" + dt.Rows[0]["F_UserId"].ToString();
                            }
                            else
                            {
                                Dictionary<string, string> Dic = new Dictionary<string, string>();
                                Dic.Add("F_UserID", dt.Rows[0]["F_UserId"].ToString());
                                Dic.Add("F_UserCode", dt.Rows[0]["F_UserCode"].ToString());
                                Dic.Add("F_DeptId", dt.Rows[0]["F_DeptId"].ToString());
                                Dic.Add("F_UserName", dt.Rows[0]["F_UserName"].ToString());
                                Dic.Add("F_Telephone", dt.Rows[0]["F_Telephone"].ToString());
                                Dic.Add("F_RoleID", dt.Rows[0]["F_RoleID"].ToString());
                                Dic.Add("F_SeatFlag", dt.Rows[0]["F_SeatFlag"].ToString());

                                if (dt.Rows[0]["F_GroupId"].ToString() != null)
                                {
                                    Dic.Add("F_GroupId", dt.Rows[0]["F_GroupId"].ToString());
                                }
                                if (dt.Rows[0]["F_SeatRight"].ToString() != null)
                                {
                                    Dic.Add("F_SeatRight", dt.Rows[0]["F_SeatRight"].ToString());
                                }
                                if (!string.IsNullOrEmpty(extensionphone))
                                {
                                    Dic.Add("F_ExtensionNumber", extensionphone);
                                }
                                else
                                {
                                    Dic.Add("F_ExtensionNumber", "");
                                }
                                Dic.Add("F_WorkNumber", dt.Rows[0]["F_WorkNumber"].ToString());

                                CookieUtil.SetCookie("BaseCallCenter_T_User", Dic);
                                //写入登录日志
                                new BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
                                {
                                    F_LoginName = dt.Rows[0]["F_UserName"].ToString(),
                                    F_LoginId = Convert.ToInt32(dt.Rows[0]["F_UserId"].ToString()),
                                    F_Result = "登录成功",
                                    F_LoginIP = Common.DTRequest.GetIP(),
                                    F_Hostname = Common.DTRequest.GetIP(),
                                    F_LoginDate = DateTime.Now,
                                    F_Remark = "",
                                    F_State = 0
                                });
                                res = "success";
                            }
                        }
                        else
                        {
                            //写入登录日志
                            DataTable dt1 = new BaseCallCenter.BLL.T_Sys_UserAccount().GetList("F_UserCode='" + username.Trim() + "'").Tables[0];
                            if (dt1.Rows.Count > 0)
                            {
                                int rr = new BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
                                {
                                    F_LoginName = dt1.Rows[0]["F_UserName"].ToString(),
                                    F_LoginId = Convert.ToInt32(dt1.Rows[0]["F_UserId"].ToString()),
                                    F_Result = "登录失败：帐号-" + username + ";分机号-" + extensionphone,
                                    F_LoginIP = Common.DTRequest.GetIP(),
                                    F_Hostname = Common.DTRequest.GetIP(),
                                    F_LoginDate = DateTime.Now,
                                    F_Remark = "",
                                    F_State = 0
                                });
                            }
                            else
                            {
                                int rr = new BLL.T_Sys_LoginLogs().Add(new Model.T_Sys_LoginLogs()
                                {
                                    F_LoginName = username,
                                    F_LoginId = -1,
                                    F_Result = "登录失败：帐号-" + username + ";分机号-" + extensionphone,
                                    F_LoginIP = Common.DTRequest.GetIP(),
                                    F_Hostname = Common.DTRequest.GetIP(),
                                    F_LoginDate = DateTime.Now,
                                    F_Remark = "",
                                    F_State = 0
                                });
                            }
                            res = "账号或密码错误，请重新登录";
                        }
                    }
                    else
                    {
                        res = "账号或密码错误，请重新登录";
                    }
                }
                catch (Exception ex)
                {
                    res = "错误:" + ex.ToString();
                    SysLog.WriteLog(ex);
                }
                finally
                {
                    dt.Clear();
                    dt.Dispose();
                }
            }
            else
            {
                res = "授权过期，请联系系统厂家。";
            }
            return res;
        }

        /// <summary>
        /// 验证授权
        /// </summary>
        /// <returns></returns>
        private bool LoodLoop()
        {
            bool result = CheckValid();
            //return true;
            if (result)
                return true;
            else
                return false;
        }
        private bool CheckValid()
        {
            return DateTime.Now < ExpiredTime;
        }
        private static string ReadFile(string filepath)
        {
            string str = File.ReadAllText(filepath, Encoding.UTF8);
            return DESEncrypt.Decrypt(str);
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}