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.WeChat;
using System.Web.Caching;
using System.Net;
using System.IO;
using System.Text;
using LitJson;


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

 
        protected void Page_Load(object sender, EventArgs e)
        {

            JsonData jd2 = new JsonData();
            jd2["openid"] = "openid";
            jd2["nickname"] = "nickname";
            jd2["sex"] = "sex";
            jd2["headimgurl"] = "headimgurl";
            jd2["country"] = "country";
            jd2["province"] = "province";
            jd2["city"] = "city";
            jd2["unionid"] = "unionid";

            jd2["fromURL"] = "fromURL";
            Session["WeChat_UserInfo"] = jd2.ToJson();
            Response.Redirect("BindChoose.aspx?fromURL=fromURL", true);


            if (eBase.WeChatAccount.getValue("AppID").Length == 0 || eBase.WeChatAccount.getValue("AppSecret").Length == 0)
            {
                litMsg.Text = eBase.getTipMsg(new eTipMsg() { Title = "绑定错误!", Body = "没有绑定域名、公众号或绑定信息不完整。", Icon = "warning", Text = "关闭", Href = "javascript:WeixinJSBridge.call('closeWindow');" });
                return;
            }           
            string fromURL = eParameters.QueryString("fromURL");//登录来源页面URL
            user = new eUser(UserArea);
            if (user.Logined)
            {
                return;
            }
            eFileInfo fi = new eFileInfo(Request.Url.PathAndQuery);
            string folderPath = fi.Path;
            //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 = WeChatHelper.getAccessToken(code);

            string access_token = json.GetValue("access_token");
            string openid = json.GetValue("openid");
            string unionid = json.GetValue("unionid");
            if (openid.Length == 0 && unionid.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 (openid='" + openid + "'" + (unionid.Length > 0 ? " or unionid='" + unionid + "'" : "") + ") and delTag=0 order by 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 = WeChatHelper.getUserInfo(access_token,openid);
                string headimgurl = _json.GetValue("headimgurl").Replace("\\", "");//为空
                //eBase.AppendLog(_json.ToJson());
                int mode = 1;//1.自动添加用户，2.让用户选择绑定现有帐号，或注册新帐号。
                if (mode == 2) //1.自动添加用户
                {
                    #region 自动添加用户
                    eTable etb = new eTable("a_eke_sysUsers");
                    etb.DataBase = eBase.UserInfoDB;
                    if (eBase.WeChatAccount.getValue("SiteID").Length > 0) etb.Fields.Add("SiteID", eBase.WeChatAccount.getValue("SiteID"));
                    etb.Fields.Add("UserType", "2");
                    etb.Fields.Add("RoleID", "201310aa-89d7-4209-b3c1-b507e1dc6267"); //默认具有角色的权限
                    // ,openid,nickname,sex,headimgurl,country,province,city,unionid
                    etb.Fields.Add("openid", openid);
                    etb.Fields.Add("nickname", _json.GetValue("nickname"));
                    etb.Fields.Add("sex", _json.GetValue("sex"));
                    etb.Fields.Add("headimgurl", headimgurl);
                    etb.Fields.Add("country", _json.GetValue("country"));
                    etb.Fields.Add("province", _json.GetValue("province"));
                    etb.Fields.Add("city", _json.GetValue("city"));
                    if( _json.GetValue("unionid").Length > 0)  etb.Fields.Add("unionid", _json.GetValue("unionid"));                   
                    etb.Add();
             
                    string userid = etb.ID;
                    string face = WeChatHelper.downHeadImage(userid, headimgurl);
                    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["openid"] = openid;
                    jd["nickname"] = _json.GetValue("nickname");
                    jd["sex"] = _json.GetValue("sex");
                    jd["headimgurl"] = headimgurl;
                    jd["country"] = _json.GetValue("country");
                    jd["province"] = _json.GetValue("province");
                    jd["city"] = _json.GetValue("city");
                    if (_json.GetValue("unionid").Length > 0) jd["unionid"] = _json.GetValue("unionid"); 

                    jd["fromURL"] = fromURL;
                    Session["WeChat_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_userinfo&m=oauth2#wechat_redirect", eBase.WeChatAccount.getValue("AppID"), redirect_uri);
                Response.Redirect(url);
            }
            else
            {
                Response.Redirect(Request.Url.ToString());
            }

        }
    
    }
}