using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using EKETEAM.FrameWork;
using EKETEAM.Data;
using EKETEAM.Tencent.WxWork;
using System.Web.Caching;
using System.Net;
using System.IO;
using System.Text;
using LitJson;


namespace eFrameWork.WXWork
{
    public partial class Login : System.Web.UI.Page
    {
        public string UserArea = "Application";
        eUser user;
        public string redirect_uri = "";

        private void ProxyLogin()
        {
            if (Request.QueryString["data"] != null)
            {
                #region 代理返回数据
                string data = Request.QueryString["data"].ToString();
                try
                {
                    string base64 = Base64.Decode(data);
                    if (base64.StartsWith("{"))
                    {
                        JsonData json = JsonMapper.ToObject(base64);
                        string qyuserid = json.GetValue("UserId");
                        if (qyuserid.Length == 0)
                        {
                            litMsg.Text = eBase.getTipMsg(new eTipMsg() { Title = "授权失败!", Body = "请与企业微信管理员联系。", Icon = "warning", Text = "关闭", Href = "javascript:WeixinJSBridge.call('closeWindow');" });
                            return; 
                        }
                        DataTable tb = eBase.UserInfoDB.getDataTable("select top 1 * from a_eke_sysUsers where qyUserID='" + qyuserid + "' and delTag=0 order by LEN(ISNULL(qyUserID,'')) desc, addTime");
                        if (tb.Rows.Count > 0)
                        {
                            #region 数据库存在该用户
                            if (tb.Rows[0]["Active"].ToString() == "False")
                            {
                                litMsg.Text = eBase.getTipMsg(new eTipMsg() { Title = "登录失败!", Body = "用户信息未审核，或已停用。", Icon = "warning", Text = "关闭", Href = "javascript:WeixinJSBridge.call('closeWindow');" });
                                return;
                            }
                            if (tb.Rows[0]["delTag"].ToString() == "True")
                            {
                                litMsg.Text = eBase.getTipMsg(new eTipMsg() { Title = "登录失败!", Body = "用户信息不存在。", Icon = "warning", Text = "关闭", Href = "javascript:WeixinJSBridge.call('closeWindow');" });
                                return;
                            }
                            user = new eUser(UserArea);
                            eFHelper.saveUserInfo(user, tb.Rows[0]); //保存用户登录信息
                            eFHelper.UserLoginLog(user); //用户登录日志
                            string fromurl = eParameters.QueryString("fromURL");
                            if (fromurl.Length == 0)
                            {
                                Response.Redirect("Default.aspx", true);
                            }
                            else
                            {
                                Response.Redirect(HttpUtility.UrlDecode(fromurl), true);
                            }
                            #endregion
                        }
                        else
                        {
                            litMsg.Text = eBase.getTipMsg(new eTipMsg() { Title = "登录失败!", Body = "用户不存在或没绑定企业微信。", Icon = "warning", Text = "关闭", Href = "javascript:WeixinJSBridge.call('closeWindow');" });
                            return;
                        }
                    }                    
                    Response.End();
                }
                catch
                {
                }
                #endregion
            }
            string self_url = HttpUtility.UrlEncode(Request.Url.AbsoluteUri);
            string url = eBase.WXWorkAccount.getValue("Proxy") + "loginProxy.aspx?fromURL=" + self_url;
            Response.Redirect(url, true);
            //eBase.Writeln(url);
            //eBase.End();
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (eBase.WXWorkAccount.getValue("Proxy").Length > 0)
            {
                ProxyLogin();
                return;
            }
            if (eBase.WXWorkAccount.getValue("CorpID").Length == 0 || eBase.WXWorkAccount.getValue("AgentId").Length == 0 || eBase.WXWorkAccount.getValue("Secret").Length == 0)
            {
                litMsg.Text = eBase.getTipMsg(new eTipMsg() { Title = "绑定错误!", Body = "没有绑定域名、企业微信或绑定信息不完整。", Icon = "warning", Text = "关闭", Href = "javascript:WeixinJSBridge.call('closeWindow');" });
                return;
            }

            eFileInfo fi = new eFileInfo(Request.Url.PathAndQuery);    
            string folderPath = fi.Path;
            string fromURL = eParameters.QueryString("fromURL");//登录来源页面URL
            //eBase.Writeln(fromURL);
            //eBase.End();
            /*
            JsonData jd2 = new JsonData();
            jd2["userid"] = "qyuserid";
            jd2["name"] = "name";
            jd2["gender"] = "gender";
            jd2["avatar"] = "avatar";
            jd2["fromURL"] = "fromURL";
            Session["WXWork_UserInfo"] = jd2.ToJson();
            Response.Redirect("BindChoose.aspx?fromURL=" + HttpUtility.UrlEncode(fromURL), true);
            */
            user = new eUser(UserArea);
            if (user.Logined)
            {
                return;
            }

            //redirect_uri = Request.Url.Scheme + "://" + Request.Url.Host;
            //redirect_uri += (Request.Url.Port == 80 || Request.Url.Port == 443 ? "" : ":" + Request.Url.Port.ToString()) + folderPath + "Login.aspx";

            redirect_uri = Request.Url.Scheme + "://" + eRequest.fromHost;
            redirect_uri += (eRequest.fromPort == 80 || eRequest.fromPort == 443 ? "" : ":" + eRequest.fromPort.ToString()) + folderPath + "Login.aspx";

            if (fromURL.Length > 0) redirect_uri += "?fromURL=" + HttpUtility.UrlEncode(HttpUtility.UrlEncode(fromURL)); // HttpUtility.UrlDecode(fromURL);
            redirect_uri = HttpUtility.UrlEncode(redirect_uri);


            string code = Request["code"];
            if (string.IsNullOrEmpty(code))
            {
                OpenAccess();
            }

            JsonData json = WxWorkHelper.getUserInfo(code);
            //{"errcode":48010,"errmsg":"you are using TLS 1.0/1.1 which is deprecated, please use TLS 1.2 or higher, hint: [1761634463448152432890000], from ip: 122.245.29.66, more info at https://open.work.weixin.qq.com/devtool/query?e=48010"}


            string qyuserid = json.GetValue("UserId"); //非企业成员 返回OpenId ，这里为空
            string userticket = json.GetValue("user_ticket");
            if (qyuserid.Length == 0 || userticket.Length == 0)
            {
                litMsg.Text = eBase.getTipMsg(new eTipMsg() { Title = "登录失败!", Body = "请与企业微信管理员联系。", Icon = "warning", Text = "关闭", Href = "javascript:WeixinJSBridge.call('closeWindow');" });
                return;

                string msg = json.getValue("errmsg");
                if (msg.Length == 0) msg = "登录失败,请与企业微信管理员联系!";
                Response.Write(msg);
                Response.End();
            }

            DataTable tb = eBase.UserInfoDB.getDataTable("select top 1 * from a_eke_sysUsers where qyUserID='" + qyuserid + "' and delTag=0 order by LEN(ISNULL(qyUserID,'')) desc, addTime");
            if (tb.Rows.Count > 0)
            {
                #region 数据库存在该用户
                if (tb.Rows[0]["Active"].ToString() == "False")
                {
                    litMsg.Text = eBase.getTipMsg(new eTipMsg() { Title = "登录失败!", Body = "用户信息未审核，或已停用。", Icon = "warning", Text = "关闭", Href = "javascript:WeixinJSBridge.call('closeWindow');" });
                    return;
                }
                if (tb.Rows[0]["delTag"].ToString() == "True")
                {
                    litMsg.Text = eBase.getTipMsg(new eTipMsg() { Title = "登录失败!", Body = "用户信息不存在。", Icon = "warning", Text = "关闭", Href = "javascript:WeixinJSBridge.call('closeWindow');" });
                    return;
                }
                user = new eUser(UserArea);
                eFHelper.saveUserInfo(user, tb.Rows[0]); //保存用户登录信息
                eFHelper.UserLoginLog(user); //用户登录日志
                Response.Redirect(HttpUtility.UrlDecode(fromURL), true);
                #endregion
            }
            else
            {
                #region 添加用户
                JsonData _json = WxWorkHelper.getUserDetail(userticket);
                string avatar= _json.GetValue("avatar").Replace("\\", "");
                int mode = 2;//1.自动添加用户，2.让用户选择绑定现有帐号，或注册新帐号。
                if (mode == 1) //1.自动添加用户
                {
                    #region 自动添加用户
                    eTable etb = new eTable("a_eke_sysUsers");
                    etb.DataBase = eBase.UserInfoDB;
                    if (eBase.WXWorkAccount.getValue("SiteID").Length > 0) etb.Fields.Add("SiteID", eBase.WXWorkAccount.getValue("SiteID"));
                    etb.Fields.Add("UserType", "2");
                    etb.Fields.Add("qyUserID", qyuserid);
                    etb.Fields.Add("xm", _json.GetValue("name"));
                    etb.Fields.Add("name", _json.GetValue("name"));
                    etb.Fields.Add("gender", _json.GetValue("gender"));
                    etb.Fields.Add("avatar", avatar);
                    etb.Fields.Add("RoleID", "201310aa-89d7-4209-b3c1-b507e1dc6267"); //默认具有角色的权限
                    etb.Add();
             
                    string userid = etb.ID;
                    string face = WxWorkHelper.downHeadImage(userid, qyuserid, avatar);
                    tb = eBase.UserInfoDB.getDataTable("select top 1 * from a_eke_sysUsers where UserID='" + userid + "'");
                    if (tb.Rows.Count > 0)
                    {
                        user = new eUser(UserArea);
                        eFHelper.saveUserInfo(user, tb.Rows[0]); //保存用户登录信息
                    }
                    eFHelper.UserLoginLog(user); //用户登录日志
                    Response.Redirect(HttpUtility.UrlDecode(fromURL), true);
                    #endregion
                }
                else //让用户选择绑定现有帐号，或注册新帐号。
                {

                    JsonData jd = new JsonData();
                    jd["userid"] = qyuserid;
                    jd["name"] = _json.GetValue("name");
                    jd["gender"] = _json.GetValue("gender");
                    jd["avatar"] = avatar;
                    jd["fromURL"] = fromURL;
                    Session["WXWork_UserInfo"] = jd.ToJson();
                    Response.Redirect("BindChoose.aspx?fromURL=" + HttpUtility.UrlEncode(fromURL), true);
                }
                #endregion
            }
        }

        

        private void OpenAccess()
        {   
            if (!user.Logined)
            {
                string url = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_base&agentid={2}&state=STATE#wechat_redirect", eBase.WXWorkAccount.getValue("CorpID"), redirect_uri, eBase.WXWorkAccount.getValue("AgentId"));
                //url = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_userinfo&agentid={2}&state=STATE#wechat_redirect", eBase.WXWorkAccount.getValue("CorpID"), redirect_uri, eBase.WXWorkAccount.getValue("AgentId"));
                url = string.Format("https://open.weixin.qq.com/connect/oauth2/authorize?appid={0}&redirect_uri={1}&response_type=code&scope=snsapi_privateinfo&agentid={2}&state=STATE#wechat_redirect", eBase.WXWorkAccount.getValue("CorpID"), redirect_uri, eBase.WXWorkAccount.getValue("AgentId"));
                Response.Redirect(url);
            }
            else
            {
                Response.Redirect(Request.Url.ToString());
            }
        }
    
    }
}