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

namespace eFrameWork.Plugins
{
    public partial class WxWorkScanLogin : System.Web.UI.Page
    {
        public string UserArea = "Application";
        eUser user;
        public string fromURL = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            fromURL = eParameters.QueryString("fromURL");
            string area = eParameters.QueryString("area");
            if (Request.QueryString["mode"] != null)
            {
                if (area.Length > 0 && fromURL.Length > 0)
                {
                    fromURL += (fromURL.IndexOf("?") == -1 ? "?" : "&") + "area=" + area;
                }
                return;
            }
            fromURL = eParameters.QueryString("state");//登录来源页面URL
            if (fromURL.Length == 0) fromURL = "Default.aspx";
            if (fromURL.getQuery("area").Length > 0)
            {
                UserArea = fromURL.getQuery("area");
                fromURL = fromURL.removeQuery("area");
            }
            string code = Request["code"];
            if (string.IsNullOrEmpty(code)) return;
            JsonData json = WxWorkHelper.getUserInfo(code);

            string _fromURL = HttpUtility.UrlDecode(fromURL);


            string qyuserid = json.getValue("UserId"); //非企业成员 返回OpenId ，这里为空
            string userticket = json.getValue("user_ticket");//扫码不会返回 user_ticket
            if (qyuserid.Length == 0)
            {
                if (_fromURL.ToLower().StartsWith("http"))
                {
                    JsonData jd = new JsonData();
                    jd.Add("success", "1");
                    jd.Add("errcode", "1");
                    jd.Add("message", "登录失败,请与企业微信管理员联系!");
                    string _base64 = Base64.Encode(jd.ToJson());
                    fromURL = HttpUtility.UrlDecode(fromURL);
                    fromURL = fromURL.addQuery("data", _base64);
                    Response.Redirect(fromURL, true);
                }
                else
                {
                    Response.Write("登录失败,请与企业微信管理员联系!");
                    Response.End();
                }
            }
            if (_fromURL.ToLower().StartsWith("http"))
            {
                string[] arr = _fromURL.Split("/".ToCharArray());
                string host = arr[2].ToLower();
                host = host.Split(":".ToCharArray())[0];//忽略端口号
                if (eBase.WXWorkAccount.getValue("ReverseProxy").ToLower().IndexOf(host) > -1 || Request.Url.Host.ToLower() == host)
                {
                    json = WxWorkHelper.getUser(qyuserid);
                    string _base64 = Base64.Encode(json.ToJson());
                    _fromURL = _fromURL.addQuery("data", _base64);
                    Response.Redirect(_fromURL, true);
                }
                eBase.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)
            {
               
                if (tb.Rows[0]["Active"].ToString() == "False")
                {
                    Response.Write("登录失败,用户信息已停用!");
                    Response.End();
                }
                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();
            }
            else
            {
                 //JsonData _json = WxWorkHelper.getUser(qyuserid);

            }
            //Response.Write(code);
            //Response.End();
        }
        
    }
}