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


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


        protected void Page_Load(object sender, EventArgs e)
        {

            if (eBase.DingTalkAccount.getValue("AgentId").Length == 0 || eBase.DingTalkAccount.getValue("AppKey").Length == 0 || eBase.DingTalkAccount.getValue("AppSecret").Length == 0)
            {
                Response.Write("没有绑定域名、钉钉或绑定信息不完整!");
                Response.End();
            }

            eFileInfo fi = new eFileInfo(Request.Url.PathAndQuery);    
            string folderPath = fi.Path;
            string fromURL = eParameters.QueryString("fromURL");//登录来源页面URL

            //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 = eParameters.QueryString("code");
            if (code.Length == 0) return;

            //eBase.Writeln(redirect_uri);

          

            //eBase.Writeln(code);
            //string accessToken = DingTalkHelper.getAccesstoken();
            string userid = DingTalkHelper.getUserId(code);
            //eBase.Writeln(userid);
            JsonData jd= DingTalkHelper.getUserDetail(userid);
            //string userinfo = GetUserDetail(accessToken, userid);
            //eBase.Writeln(userinfo);

            //eBase.Writeln(jd.ToJson());

            string ddunionid = jd.getValue("unionid");
            string dduserid = jd.getValue("userid");
            if (ddunionid.Length == 0 || dduserid.Length==0)
            {
                string msg = jd.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 (ddunionid='" + ddunionid + "' or dduserid='" + dduserid + "') and delTag=0 order by addTime");


            if (fromURL.ToLower().IndexOf("fromurl") > -1)
            {
                fromURL = fromURL.getQuery("fromurl");
                fromURL = HttpUtility.UrlDecode(fromURL);
            }
            else
            {
                fromURL = "default.aspx";
            }

            //eBase.Writeln(HttpUtility.UrlDecode(HttpUtility.UrlDecode(fromURL)));
            //eBase.End();

            if (tb.Rows.Count > 0)
            {
                #region 数据库存在该用户
                if (tb.Rows[0]["Active"].ToString() == "False")
                {
                    Response.Write("登录失败,用户信息已停用!");
                    Response.End();
                }
                if (tb.Rows[0]["delTag"].ToString() == "True")
                {
                    Response.Write("登录失败,用户信息已删除!");
                    Response.End();
                }
                user = new eUser(UserArea);
                eFHelper.saveUserInfo(user, tb.Rows[0]); //保存用户登录信息
                eFHelper.UserLoginLog(user); //用户登录日志
                Response.Redirect(HttpUtility.UrlDecode(fromURL), true);
                #endregion
            }

            /*
            JsonData json = WxWorkHelper.getUserInfo(code);
            string qyuserid = json.GetValue("UserId"); //非企业成员 返回OpenId ，这里为空


            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")
                {
                    Response.Write("登录失败,用户信息已停用!");
                    Response.End();
                }
                if (tb.Rows[0]["delTag"].ToString() == "True")
                {
                    Response.Write("登录失败,用户信息已删除!");
                    Response.End();
                }
                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 = 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
            }
            */
        }
    }
}