using System;
using System.Data;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using EKETEAM.Data;
using EKETEAM.FrameWork;
using LitJson;

namespace eFrameWork.Manage
{

    public partial class Login : System.Web.UI.Page
    {
        public string fromURL = "";
        public string wechatFromURL = "";
        public string wxworkFromURL = "";
        public string dingtalkFromURL = "";
        public bool wechat = false;
        public bool wxwork = false;
        public bool dingtalk = false;
        public string UserArea = "Manage";
        eUser user;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["data"] != null)
            {
                #region 代理返回数据
                string data = Request.QueryString["data"].ToString();
                string base64 = Base64.Decode(data);
                if (base64.Length > 5 && base64.StartsWith("\"") && base64.EndsWith("\"")) base64 = base64.Substring(1, base64.Length - 2);
                base64 = base64.Replace("\\\\/", "\\/");
                base64 = base64.Replace("\\\"", "\"");
                if (base64.StartsWith("{"))
                {
                    JsonData json = JsonMapper.ToObject(base64);

                    DataTable tb = new DataTable();
                    string qyuserid = json.GetValue("UserId");
                    if (json.Contains("result")) //钉钉
                    {
                        string userid = json["result"]["userid"].ToString();
                        string unionid = json["result"]["unionid"].ToString();
                        tb = eBase.UserInfoDB.getDataTable("select top 1 * from a_eke_sysUsers where (ddunionid='" + unionid + "' or dduserid='" + userid + "') and UserType=1 and delTag=0 order by addTime");
                    }
                    else
                    {
                        if (qyuserid.Length > 0)//企业微信
                        {
                            tb = eBase.UserInfoDB.getDataTable("select top 1 * from a_eke_sysUsers where qyUserID='" + qyuserid + "' and UserType=1 and delTag=0 order by LEN(ISNULL(qyUserID,'')) desc, addTime");
                        }
                        else //微信
                        {

                            string openid = json.GetValue("openid");
                            string unionid = json.GetValue("unionid");


                            if (openid.Length > 0 || unionid.Length == 0)
                            {
                                tb = eBase.UserInfoDB.getDataTable("select top 1 * from a_eke_sysUsers where (unionid='" + unionid + "' or openid='" + openid + "') and UserType=1 and delTag=0 order by addTime");
                            }
                        }
                    }
                    if (tb.Rows.Count > 0)
                    {
                        if (tb.Rows[0]["Active"].ToString() == "False")
                        {
                            Response.Write("登录失败,用户信息已停用!");
                            Response.End();
                        }
                        fromURL = eParameters.QueryString("fromURL"); //登录来源页面URL
                        if (fromURL.Length == 0) fromURL = "Default.aspx";
                        user = new eUser(UserArea);
                        eFHelper.saveUserInfo(user, tb.Rows[0]); //保存用户登录信息
                        eFHelper.UserLoginLog(user); //用户登录日志
                        //Response.Redirect(HttpUtility.UrlDecode(fromURL), true);
                        Response.Write("<script>parent.document.location.href='" + HttpUtility.UrlDecode(fromURL) + "';</script>");
                        Response.End();
                    }
                }
                eBase.End();
                #endregion
            }            
            eFHelper.checkErrorCount(); //检查登录错误次数是否超过设定值
            fromURL = eParameters.QueryString("fromURL");
            user = new eUser(UserArea);
            if (user.Logined && fromURL.Length > 0)
            {
                fromURL = eParameters.QueryString("fromURL");
                Response.Redirect(fromURL, true);
            }
            if (fromURL.Length == 0) fromURL = eBase.getLocalPath();
            string UserAgent = Request.ServerVariables["HTTP_USER_AGENT"];
            if (string.IsNullOrEmpty(UserAgent))
            {
                eFHelper.setErrorSession(); //增加登录错误次数
                Response.Write("<script>alert('登录信息不正确！');document.location='" + fromURL + "';</script>");
                Response.End();
                
            }
            if (eBase.WeChatAccount.getValue("Proxy").Length > 0 || (eBase.WeChatAccount.getValue("OpenAppID").Length > 0 && eBase.WeChatAccount.getValue("OpenAppSecret").Length > 0))
            {
                wechat = true;
            }
            if (eBase.WXWorkAccount.getValue("Proxy").Length > 0 || (eBase.WXWorkAccount.getValue("CorpID").Length > 0 && eBase.WXWorkAccount.getValue("AgentId").Length > 0 && eBase.WXWorkAccount.getValue("Secret").Length > 0))
            {
                wxwork = true;
            }
            if (eBase.DingTalkAccount.getValue("Proxy").Length > 0 || (eBase.DingTalkAccount.getValue("CorpId").Length > 0 && eBase.DingTalkAccount.getValue("AgentId").Length > 0 && eBase.DingTalkAccount.getValue("AppSecret").Length > 0))
            {
                dingtalk = true;
            }
            if (eBase.WeChatAccount.getValue("Proxy").Length > 0)
            {
                wechatFromURL = HttpUtility.UrlEncode(Request.Url.AbsoluteUri);
            }
            else
            {
                wechatFromURL = fromURL;
            }
            if (eBase.WXWorkAccount.getValue("Proxy").Length > 0)
            {
                wxworkFromURL = HttpUtility.UrlEncode(Request.Url.AbsoluteUri);
            }
            else
            {
                wxworkFromURL = fromURL;
            }
            if (eBase.DingTalkAccount.getValue("Proxy").Length > 0)
            {
                dingtalkFromURL = HttpUtility.UrlEncode(Request.Url.AbsoluteUri);
            }
            else
            {
                dingtalkFromURL = fromURL;
            }
         
            string LoginFile = "Login.aspx";
            if (fromURL.Length > 0) LoginFile += "?fromURL=" + HttpUtility.UrlEncode(fromURL);
            if (Request.Form["yhm"] != null)
            {
                if (eConfig.openRndCode()) eFHelper.checkRndCode(Request.Form["yzm"].ToString(), fromURL); //验证验证码是否正确
                string sql = "Select * From a_eke_sysUsers Where delTag=0 and Active=1 and UserType=1 and YHM='" + Request.Form["yhm"].ToString() + "'";//top 1 
                sql += " order by addTime";
                DataTable tb = eBase.DataBase.getDataTable(sql);               

                if (tb.Rows.Count == 0)
                {
                    eFHelper.setErrorSession(); //增加登录错误次数
                    Response.Write("<script>alert('登录信息不正确！');document.location='" + fromURL + "';</script>");
                    Response.End();
                }
                else
                {
                    string encpass = Request.Form["mm"].ToString();//得到RSA加密的密码
                    string pass = eRSA.getPass(encpass);//进行RSA解密
                    if (eBase.getPassWord(pass) == tb.Rows[0]["mm"].ToString())
                    {
                        #region 单点登录
                        if (eConfig.singleSign)
                        {
                            string ip = eBase.getIP();
                            string lastip = eBase.UserInfoDB.getValue("select top 1 IP from a_eke_sysUserLog where UserID='" + tb.Rows[0]["userid"].ToString() + "' order by addtime desc");
                            if (ip.Length > 7 && lastip.Length > 7 && lastip != ip)
                            {
                                string lastUserAgent = eBase.UserInfoDB.getValue("select UserAgent from a_eke_sysUserLog where UserID='" + tb.Rows[0]["userid"].ToString() + "' and DATEDIFF(dd,getdate(),addTime)=0");
                                if (lastUserAgent.Length > 0)
                                {
                                    if (lastUserAgent.ToLower() != UserAgent.ToLower())
                                    {
                                        eFHelper.setErrorSession(); //增加登录错误次数
                                        Response.Write("<script>alert('请勿违规登录,否则封禁帐号!');document.location='" + fromURL + "';</script>");
                                        Response.End();
                                    }
                                }
                            }
                        }
                        #endregion
                        user = new eUser(UserArea);
                        eFHelper.saveUserInfo(user, tb.Rows[0]); //保存用户登录信息
                        eFHelper.UserLoginLog(user); //用户登录日志

                        if (eParameters.QueryString("fromURL").Length > 0)
                        {
                            Response.Redirect(HttpUtility.UrlDecode(eParameters.QueryString("fromURL")), true);
                        }
                        else
                        {
                            Response.Redirect("Default.aspx", true);
                        }

                    }
                    else
                    {
                        eFHelper.setErrorSession(); //增加登录错误次数
                        Response.Write("<script>alert('登录信息不正确！');document.location='" + fromURL + "';</script>");
                        Response.End();
                    }
                }
            }
        }
    }
}