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 LitJson;
using System.Security.Cryptography;
using EKETEAM.Tencent.WeChatMini;


namespace eFrameWork.AppWebAPI
{
    public partial class getToKen : System.Web.UI.Page
    {
        #region 属性
        private string _username = "";
        private string UserName
        {
            get
            {
                return _username;
            }
        }
        private string _password = "";
        private string Password
        {
            get
            {
                return _password;
            }
        }
        private string _mobile = "";
        private string Mobile
        {
            get
            {
                return _mobile;
            }
        }
        private string _code = "";
        private string Code
        {
            get
            {
                return _code;
            }
        }
       #endregion
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.RequestType.ToLower() != "post") return;
            if (Request.ContentType.ToLower().Contains( "application/x-www-form-urlencoded"))
            {
                if (Request.Form["username"] != null) _username = Request.Form["username"].ToString();
                if (Request.Form["password"] != null) _password = Request.Form["password"].ToString();                
                if (Request.Form["SJ"] != null) _mobile = Request.Form["SJ"].ToString();
                if (Request.Form["Mobile"] != null) _mobile = Request.Form["Mobile"].ToString();
                if (Request.Form["code"] != null) _code = Request.Form["code"].ToString();
            }
            if (Request.ContentType.ToLower().IndexOf("/json") > -1)
            {
              
                string postjson = eBase.getPostJsonString();
                if (postjson.StartsWith("{"))
                {
                    JsonData data = JsonMapper.ToObject(postjson);
                    if (data.Contains("username")) _username = data.GetValue("username");
                    if (data.Contains("password")) _password = data.GetValue("password");
                    if (data.Contains("sj")) _mobile = data.GetValue("sj");
                    if (data.Contains("mobile")) _mobile = data.GetValue("mobile");
                    if (data.Contains("code")) _code = data.GetValue("code");
                }
            }
            DataTable tb;
            string sql = "";
            #region 手机号登录
            if (Mobile.Length > 0)
            {
                //ErrJson = new eJson();
                sql = "Select top 1 * From a_eke_sysUsers Where delTag=0 and SJ='" + Mobile + "'  order by addtime"; // and Active=1
                tb = eBase.UserInfoDB.getDataTable(sql);

                if (tb.Rows.Count == 0)
                {
                    //ErrJson.Add("errcode", "1005");
                    //ErrJson.Add("message", "登录信息有误!");
                    //eBase.WriteJson(ErrJson);
                    eResult.Message(new { success = 1, errcode = "1005", message = "登录信息有误!" });
                }
                else
                {
                    #region 禁用处理
                    if (tb.Rows[0]["Active"].ToString().ToLower() == "false")
                    {

                        //ErrJson.Add("errcode", "1014");
                        //ErrJson.Add("message", "该用户已被禁用!");
                        //eBase.WriteJson(ErrJson);
                        eResult.Message(new { success = 1, errcode = "1014", message = "该用户已被禁用!" });
                    }
                    #endregion



                    eToken token = new eToken();
                    token.Exp = 7 * 24 * 60 * 60;//7天
                    //默认为30分钟，根据实际需要修改。单位：秒。 当前为1天，60分钟*60秒 为一小时
                    token.Add("id", tb.Rows[0]["UserID"].ToString());
                    token.Add("user", tb.Rows[0]["YHM"].ToString());
                    token.Add("name", tb.Rows[0]["xm"].ToString());

                    token.Add("SiteID", tb.Rows[0]["siteid"].ToString() == "0" ? "1" : tb.Rows[0]["siteid"].ToString());
                    token.Add("face", tb.Rows[0]["face"].ToString().Length > 0 ? tb.Rows[0]["face"].ToString() : "images/head.png");

                    if (tb.Columns.Contains("Department") && tb.Rows[0]["Department"].ToString().Length > 0) token.Add("depname", tb.Rows[0]["Department"].ToString());//部门名称
                    if (tb.Columns.Contains("openid") && tb.Rows[0]["openid"].ToString().Length > 0) token.Add("openid", tb.Rows[0]["openid"].ToString());
                    if (tb.Columns.Contains("code") && tb.Rows[0]["code"].ToString().Length > 0)  token.Add("orgcode", tb.Rows[0]["code"].ToString()); //当前登录用户机构编码
                    if (tb.Columns.Contains("ServiceID") && tb.Rows[0]["ServiceID"].ToString().Length > 0) token.Add("ServiceID", tb.Rows[0]["ServiceID"].ToString());


                    if (tb.Columns.Contains("PostLevel")) //职位等级 (升序:职务越高数值越小)
                    {
                        token.Add("PostLevel", tb.Rows[0]["PostLevel"].ToString() == "0" ? "99" : tb.Rows[0]["PostLevel"].ToString());

                    }
                    token.Add("DataFlags", eFHelper.getUserDataFlags(tb.Rows[0]["UserID"].ToString()).ToString());


                    //token.Add("nickname", tb.Rows[0]["nickname"].ToString());

                    string tokenString = token.Create();
                    //eJson json = new eJson();
                    //json.Add("errcode", "0");
                    //json.Add("message", "请求成功!");
                    //json.Add("token", tokenString);

                    /*
                    sql = "if exists (select * from a_eke_sysToKens Where UserID='" + tb.Rows[0]["UserID"].ToString() + "')";
                    sql += "update a_eke_sysToKens set ExpireDate='" + token.ExpireDate.ToString() + "' where  UserID='" + tb.Rows[0]["UserID"].ToString() + "'";
                    sql += " else ";
                    sql += "insert into a_eke_sysToKens (ToKenID,UserID,ExpireDate) ";
                    sql += " values ('" + Guid.NewGuid().ToString() + "','" + tb.Rows[0]["UserID"].ToString() + "','" + token.ExpireDate.ToString() + "')";
                    */
                    string ct = eBase.DataBase.getValue("select count(1) from a_eke_sysToKens Where UserID='" + tb.Rows[0]["UserID"].ToString() + "'");
                    if (ct == "0")
                    {
                        sql = "insert into a_eke_sysToKens (ToKenID,UserID,ExpireDate) ";
                        sql += " values ('" + Guid.NewGuid().ToString() + "','" + tb.Rows[0]["UserID"].ToString() + "','" + token.ExpireDate.ToString() + "')";
                    }
                    else
                    {
                        sql = "update a_eke_sysToKens set ExpireDate='" + token.ExpireDate.ToString() + "' where  UserID='" + tb.Rows[0]["UserID"].ToString() + "'";
                    }


                    eBase.DataBase.Execute(sql);
                    //eBase.WriteJson(json);
                    eResult.Message(new { success = 1, errcode = "0", message = "请求成功!", token = tokenString });
                }
            }
            #endregion
            #region 帐号密码登录
            if (UserName.Length > 0 && Password.Length > 0)
            {
                //ErrJson = new eJson();
                sql = "Select top 1 * From a_eke_sysUsers Where delTag=0 and YHM='" + UserName + "' order by addtime"; // and Active=1
                tb = eBase.UserInfoDB.getDataTable(sql);

                if (tb.Rows.Count == 0)
                {
                    //ErrJson.Add("errcode", "1005");
                    //ErrJson.Add("message", "登录信息有误!");
                    //eBase.WriteJson(ErrJson);
                    eResult.Message(new { success = 1, errcode = "1005", message = "登录信息有误!"  });
                }
                else
                {
                    #region 禁用处理
                    if (tb.Rows[0]["Active"].ToString().ToLower() == "false")
                    {

                        //ErrJson.Add("errcode", "1014");
                        //ErrJson.Add("message", "该用户已被禁用!");
                        //eBase.WriteJson(ErrJson);
                        eResult.Message(new { success = 1, errcode = "1014", message = "该用户已被禁用!" });
                    }
                    #endregion
                    if (eBase.getPassWord(Password) == tb.Rows[0]["mm"].ToString())
                    {
                        eToken token = new eToken();
                        token.Exp =7 * 24 * 60 * 60;//7天
                        //默认为30分钟，根据实际需要修改。单位：秒。 当前为1天，60分钟*60秒 为一小时
                        token.Add("id", tb.Rows[0]["UserID"].ToString());
                        token.Add("SiteID", tb.Rows[0]["SiteID"].ToString());
                        //token.Add("nickname", tb.Rows[0]["nickname"].ToString());

                        string tokenString = token.Create();
                        //eJson json = new eJson();
                        //json.Add("errcode", "0");
                        //json.Add("message", "请求成功!");
                        //json.Add("token", tokenString);


              
                        /*
                        sql = "if exists (select * from a_eke_sysToKens Where UserID='" + tb.Rows[0]["UserID"].ToString() + "')";
                        sql += "update a_eke_sysToKens set ExpireDate='" + token.ExpireDate.ToString() + "' where  UserID='" + tb.Rows[0]["UserID"].ToString() + "'";
                        sql += " else ";
                        sql += "insert into a_eke_sysToKens (ToKenID,UserID,ExpireDate) ";
                        sql += " values ('" + Guid.NewGuid().ToString() + "','" + tb.Rows[0]["UserID"].ToString() + "','" + token.ExpireDate.ToString() + "')";
                        */
                        string ct = eBase.DataBase.getValue("select count(1) from a_eke_sysToKens Where UserID='" + tb.Rows[0]["UserID"].ToString() + "'");
                        if (ct == "0")
                        {
                            sql = "insert into a_eke_sysToKens (ToKenID,UserID,ExpireDate) ";
                            sql += " values ('" + Guid.NewGuid().ToString() + "','" + tb.Rows[0]["UserID"].ToString() + "','" + token.ExpireDate.ToString() + "')";
                        
                        }
                        else
                        {
                            sql = "update a_eke_sysToKens set ExpireDate='" + token.ExpireDate.ToString() + "' where  UserID='" + tb.Rows[0]["UserID"].ToString() + "'";
                        }


                        eBase.DataBase.Execute(sql);
                        //eBase.WriteJson(json);
                        eResult.Message(new { success = 1, errcode = "0", message = "请求成功!", token = tokenString });
                        
                    }
                    else
                    {
                        //ErrJson.Add("errcode", "1005");
                        //ErrJson.Add("message", "登录信息有误!");
                        //eBase.WriteJson(ErrJson);
                        eResult.Message(new { success = 1, errcode = "1005", message = "登录信息有误!" });
                    }
                }
            }
            #endregion
            #region 微信小程序登录
            if (Code.Length > 0)
            {
                JsonData jd = new JsonData();
                jd.Add("errcode", "0");
                jd.Add("message", "登录成功!");
                if (eBase.WeChatMiniAccount.getValue("AppID").Length == 0 || eBase.WeChatMiniAccount.getValue("AppSecret").Length == 0)
                {
                    eResult.Message(new { success = 1, errcode = "1015", message = "没有绑定小程序帐号!" });
                }


             

                string url = string.Format("https://api.weixin.qq.com/sns/jscode2session?appid={0}&secret={1}&js_code={2}&grant_type=authorization_code", eBase.WeChatMiniAccount.getValue("AppID"), eBase.WeChatMiniAccount.getValue("AppSecret"), Code);
                string result = eBase.getRequest(url);               
                //{"session_key":"mwXKKxcAx1ikc5zRNuKXFQ==","openid":"or_is5OLydfnPR-JugtWt9rrF9k"}
                JsonData _json = JsonMapper.ToObject(result);
                string openid = _json.GetValue("openid");
                string session_key = _json.GetValue("session_key");
                //eBase.AppendLog(result);

                sql = "select top 1 * from a_eke_sysUsers Where delTag=0 and Active=1 and miniopenid='" + openid + "' order by addtime";
                tb = eBase.UserInfoDB.getDataTable(sql);
                eToken token = new eToken();
                token.Exp = 7 * 24 * 60 * 60;//7天
                if (tb.Rows.Count == 0)
                {
                    string iv = eParameters.Form("iv");
                    string encryptedData = eParameters.Form("encryptedData");
                    //eBase.AppendLog("session_key=" + session_key + "\r\niv=" + iv + "\r\nencryptedData=" + encryptedData);

                    string phoneNumber = WeChatMiniHelper.getPhoneNumber(session_key, iv, encryptedData);

                   // eBase.AppendLog(phoneNumber);
                    sql = "select top 1 * from a_eke_sysUsers Where delTag=0 and Active=1 and sj='" + phoneNumber + "' and len('" + phoneNumber + "')>10 order by addtime";
                    tb = eBase.UserInfoDB.getDataTable(sql);
                    if (tb.Rows.Count == 0)
                    {
                        eResult.Message(new { success = 1, errcode = "1005", message = "用户不存在!" });
                    }
                    else
                    {
                        string nickname = eParameters.Form("nickname");
                        string gender = eParameters.Form("gender");
                        string avatarUrl = eParameters.Form("avatarUrl");
                        string country = eParameters.Form("country");
                        string province = eParameters.Form("province");
                        string city = eParameters.Form("city");

                        eTable etb = new eTable("a_eke_sysUsers");
                        etb.Fields.Add("openid", openid);
                        etb.Fields.Add("nickname", nickname);
                        etb.Fields.Add("sex", gender);
                        etb.Fields.Add("headimgurl", avatarUrl);
                        etb.Fields.Add("country", country);
                        etb.Fields.Add("province", province);
                        etb.Fields.Add("city", city);
                        etb.Fields.Add("sj", phoneNumber);
                        etb.Where.Add("UserID='" + tb.Rows[0]["UserID"].ToString() + "'");
                        etb.Update();

                        token.Add("id", tb.Rows[0]["UserID"].ToString());
                        token.Add("SiteID", "1");
                        token.Add("nickname", nickname);
                        jd.Add("usertype", tb.Rows[0]["usertype"].ToString());
                        jd.Add("phone", tb.Rows[0]["sj"].ToString());
                        jd.Add("name", tb.Rows[0]["xm"].ToString());
                        jd.Add("openid", tb.Rows[0]["openid"].ToString());
                        jd.Add("userid", tb.Rows[0]["userid"].ToString());
                    }                  
                }
                else
                {
                    //eBase.AppendLog("has");

                    token.Add("id", tb.Rows[0]["UserID"].ToString());
                    token.Add("SiteID", tb.Rows[0]["SiteID"].ToString());
                    token.Add("nickname", tb.Rows[0]["nickname"].ToString());

                    jd.Add("usertype", tb.Rows[0]["usertype"].ToString());
                    jd.Add("phone", tb.Rows[0]["sj"].ToString());
                    jd.Add("name", tb.Rows[0]["xm"].ToString());
                    jd.Add("openid", tb.Rows[0]["openid"].ToString());
                    jd.Add("userid", tb.Rows[0]["userid"].ToString());
                }
                string tokenString = token.Create();

                jd.Add("token", tokenString);

                /*
                sql = "if exists (select * from a_eke_sysToKens Where UserID='" + tb.Rows[0]["UserID"].ToString() + "')";
                sql += "update a_eke_sysToKens set ExpireDate='" + token.ExpireDate.ToString() + "' where  UserID='" + tb.Rows[0]["UserID"].ToString() + "'";
                sql += " else ";
                sql += "insert into a_eke_sysToKens (ToKenID,UserID,ExpireDate) ";
                sql += " values ('" + Guid.NewGuid().ToString() + "','" + tb.Rows[0]["UserID"].ToString() + "','" + token.ExpireDate.ToString() + "')";
                */
                string ct = eBase.DataBase.getValue("select count(1) from a_eke_sysToKens Where UserID='" + tb.Rows[0]["UserID"].ToString() + "'");
                if (ct == "0")
                {
                    sql = "insert into a_eke_sysToKens (ToKenID,UserID,ExpireDate) ";
                    sql += " values ('" + Guid.NewGuid().ToString() + "','" + tb.Rows[0]["UserID"].ToString() + "','" + token.ExpireDate.ToString() + "')";
                }
                else
                {
                    sql = "update a_eke_sysToKens set ExpireDate='" + token.ExpireDate.ToString() + "' where  UserID='" + tb.Rows[0]["UserID"].ToString() + "'";
                }

                eBase.DataBase.Execute(sql);

                //eBase.WriteJson(ErrJson);
                eBase.WriteJson(jd.ToJson());
            }
            #endregion
            Response.End();
        }
    }
}