<%@ Control Language="C#" %>
<%@ Import Namespace="Kesion.Publics" %>
<%@ Import Namespace="Kesion.BLL" %>
<%@ Import Namespace="Kesion.Cache" %>
<%@ Import Namespace="Kesion.HtmlTags" %>
<%@ Import Namespace="Kesion.APPCode" %>
<%@ Import Namespace="Kesion.Weixin" %>
<%@ Import Namespace="Kesion.XML" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Xml" %>
<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace=" Newtonsoft.Json.Linq" %>
<%@ Import Namespace=" Newtonsoft.Json" %>
<script runat="server" type="text/C#">
    dynamic __user = HttpContext.Current.Items["user"];                //初始化用户信息，
    private static dynamic __info = new System.Dynamic.ExpandoObject();   //初始化当前页信息
    bool isLoadPage = true;  //定义页面是否加载
    DataRow dr = null;
    public static int pagesize = 20;
    public int newCount = 0;
    public string NewUserListCount = string.Empty;
    public int todayCount = 0;
    private int currNum = 0;
    private static string WeiXinOpenID = string.Empty;
    protected void Page_Load(object sender, EventArgs e)
    {
        string DoMethod = KSCMS.S("do");
        if (string.IsNullOrEmpty(DoMethod))
        {
            DoMethod = KSCMS.S("action");
        }
        __info.Panel1 = true;

        __info.count = 0;
        __info.txtRemarkName = "";
        if (!string.IsNullOrEmpty(KSCMS.S("drSex")))
        {
            Session["drSex"] = KSCMS.S("drSex");
        }
        if (!string.IsNullOrEmpty(KSCMS.S("DDLgroups")))
        {
            Session["group"] = KSCMS.S("DDLgroups");
        }
        if (Session["drSex"] != null)
        {
            __info.drSex = Session["drSex"].ToString();
        }
        else
        {
            __info.drSex = "";
        }
        switch (DoMethod)
        {
            case "ref":
                fb(ks_weixin.IsExistAccess_Token(1));
                KSCMS.Die("ok");
                break;
            case "RefAll":
                RefSh();
                break;
            case "del":
                Button1_Click();
                break;
            case  "tb":
                BtnRefAll_Click();
                break;
            case "saves":
                Btn_Save_Click();
                break;
            case "modifyremark":
                __info.Panel1 = false;

                #region 粉丝的备注
                string Access_tokento = ks_weixin.IsExistAccess_Token(1);
                string jsonres = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + Access_tokento + "&openid=" + KSCMS.GetParam("openid", false);
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(jsonres);
                myRequest.Method = "GET";
                HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
                StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
                string content = reader.ReadToEnd();
                reader.Close();

                JObject jsonObj = JObject.Parse(content);
                // Msg.Alert(content);
                //假如备注名不为空，给备注名文本框赋值，显示原有的备注名
                if (jsonObj["errmsg"] != null)
                {
                    Msg.Alert(jsonObj["errmsg"].ToString());
                    return;
                }
                else
                {
                    if (!String.IsNullOrWhiteSpace(jsonObj["remark"].ToString()))
                    {
                        __info.txtRemarkName = jsonObj["remark"].ToString();
                    }
                }
                #endregion

                break;
            case "move":
                DDlAddgroups();
                break;
        }

        WeiXinOpenID = ks_weixin.WeiXinOpenID(1);
        __info.Panel = true;
        todayCount = Utils.StrToInt(DataFactory.GetOnlyValue("select count(id) from  KS_weixinopenuser where DateDiff(dd,subscribe_time,getdate())=0 and schoolid="+new TemporaryVar().UserID+""));
        string token = ks_weixin.IsExistAccess_Token(1);
        string url = ks_weixin.GetUserListUrl + "access_token=" + token;
        try
        {
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
            webRequest.Method = "get";
            HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
            StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            string josn = sr.ReadToEnd();
            JObject json1 = JObject.Parse(josn);
            __info.count = json1["total"].ToString();
            __info.NewTotal = Utils.StrToInt(json1["total"].ToString());
            __info.oldTotal = Utils.StrToInt(DataFactory.GetOnlyValue("select count(id) from  KS_weixinopenuser and schoolid=" + new TemporaryVar().UserID + ""));
            __info.Total = __info.NewTotal - __info.oldTotal;
            newCount = __info.Total;
        }
        catch(Exception ex)
        {
            Msg.Alert(ex.Message);
        }

    }

    public string GetNewUserCount(int newCount)
    {
        string str = string.Empty;
        str = ",最近新增<font style=\"color:Red\" class=\"newnum\">" + newCount + "</font>位粉丝";
        return str;
    }
    public void RefSh()
    {
        string token = ks_weixin.IsExistAccess_Token(1);
        string next_openid = string.Empty;
        string url = ks_weixin.GetUserListUrl + "access_token=" + token;
        string josn = GetUserJosn(url);
        JObject json1 = JObject.Parse(josn);
        JObject openid = JObject.Parse(json1["data"].ToString());
        Hashtable ht = new Hashtable();
        ht.Add("Flag", 0);
        ht.Add("schoolid", new TemporaryVar().UserID);
        CommonData.Update("KS_weixinopenuser", ht, "where  Subscribe=1 ");
        #region
        int totalNum = Utils.StrToInt(json1["total"].ToString());
        int nn = 0;
        if (totalNum > 10000)
        {
            int perPage = 10000;
            if (totalNum % perPage == 0)
            {
                nn = totalNum / perPage;
            }
            else
            {
                nn = totalNum / perPage + 1;
            }
            next_openid = json1["next_openid"].ToString();
        }
        else
        {
            next_openid = json1["next_openid"].ToString();
        }

        for (int ii = 0; ii < Utils.StrToInt(json1["count"].ToString()); ii++)
        {
            getuserinfo(openid["openid"][ii].ToString(), token);
        }

        #endregion

        #region 把next_openid和Count写入XML
        SaveXMl(next_openid);
        #endregion
        DataFactory.ExecuteNonQuery("update KS_WeixinEpConfig set UserListTotal='" +json1["total"].ToString() + "' where userid=" + new TemporaryVar().UserID + "");

        #region  分批获取
        for (int i = 0; i < nn; i++)
        {
            if (i > 0)
            {
                next_openid = DataFactory.GetOnlyValue("select top 1 UserListNextOpenID from KS_Weixinepconfig where userid=" + new TemporaryVar().UserID + "");
            }
            fb(token, next_openid);
        }
        #endregion
        DataFactory.ExecuteNonQuery("Delete From KS_weixinopenuser where Subscribe=1 and Flag=0 and schoolid="+new TemporaryVar().UserID+"");
        Msg.Alert("更新成功！",BasicField.GetUserUrl("wx/wx_UserList"));
    }
    public void fb(string token, string next_openid = "")
    {
        token = ks_weixin.IsExistAccess_Token(1);
        string url = string.Empty;
        #region  分批获取
        int newnum = 0;
        if (string.IsNullOrEmpty(next_openid))  //new
        {
            url = ks_weixin.GetUserListUrl + "access_token=" + token;
        }
        else
        {
            newnum = Utils.StrToInt(KSCMS.S("newnum"));
            url = ks_weixin.GetUserListUrl + "access_token=" + token + "&next_openid=" + next_openid;
        }
        string josn = GetUserJosn(url);
        JObject json1 = JObject.Parse(josn);
        if (json1["count"].ToString() == "0") return;
        JObject openid = JObject.Parse(json1["data"].ToString());
        int totalNum = Utils.StrToInt(json1["total"].ToString());
        int count = Utils.StrToInt(json1["count"].ToString());
        if (newnum > 0) count = newnum;
        next_openid = json1["next_openid"].ToString();
        for (int ii = 0; ii < count; ii++)
        {

            getuserinfo(openid["openid"][ii].ToString(), token);
        }

        #region 把next_openid写入XML
        if (!string.IsNullOrEmpty(next_openid))
        {
            SaveXMl(next_openid);
        }

        #endregion
        #endregion
    }

    private void SaveXMl(string next_openid)
    {
        DataFactory.ExecuteNonQuery("update KS_WeixinEpConfig set UserListNextOpenID='" + next_openid + "' where userid=" + new TemporaryVar().UserID + "");
    }
    private string GetUserJosn(string url)
    {
        #region get的方法
        try
        {
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
            webRequest.Method = "get";
            HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
            StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
            string josn = sr.ReadToEnd();
            return josn;
        }
        catch
        {
        }
        return "error";
        #endregion

    }
    public void getuserinfo(string userinfo, string token)
    {
        #region 取用户信息入库
        string url = ks_weixin.GetUserInfoUrl + "access_token=" + token + "&openid=" + userinfo + "&lang=zh_CN";
        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
        webRequest.Method = "get";
        HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
        StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
        string josn = sr.ReadToEnd();
        if (josn.IndexOf("errcode") > 0)
        {
        }
        else
        {
            JObject json1 = JObject.Parse(josn);
            if (DataFactory.Exists("KS_weixinopenuser", " openid='" + json1["openid"].ToString() + "' and  WeiXinOpenID='" + WeiXinOpenID + "' and schoolid=" + new TemporaryVar().UserID + ""))
            {
                Hashtable ht = new Hashtable();
                if (json1["subscribe"].ToString() == "1")  //已关注
                {
                    ht.Add("WeiXinOpenID", WeiXinOpenID);
                    ht.Add("subscribe", json1["subscribe"].ToString());
                    ht.Add("openid", json1["openid"].ToString());
                    ht.Add("nickname", json1["nickname"].ToString());
                    ht.Add("sex", json1["sex"].ToString());
                    ht.Add("language", json1["language"].ToString());
                    ht.Add("city", json1["city"].ToString());
                    ht.Add("province", json1["province"].ToString());
                    ht.Add("country", json1["country"].ToString());
                    ht.Add("headimgurl", json1["headimgurl"].ToString());
                    ht.Add("Remark", json1["remark"].ToString());
                    ht.Add("GroupID", json1["groupid"].ToString());
                    ht.Add("Flag", 1);
                    CommonData.Update("KS_weixinopenuser", ht, "where openid='" + json1["openid"].ToString() + "' and  WeiXinOpenID='" + WeiXinOpenID + "' and schoolid="+new TemporaryVar().UserID+"");
                }

            }
            else
            {
                Hashtable ht = new Hashtable();
                if (json1["subscribe"].ToString() == "1")  //已关注
                {
                    ht.Add("WeiXinOpenID", WeiXinOpenID);
                    ht.Add("subscribe", json1["subscribe"].ToString());
                    ht.Add("openid", json1["openid"].ToString());
                    ht.Add("nickname", json1["nickname"].ToString());
                    ht.Add("sex", json1["sex"].ToString());
                    ht.Add("language", json1["language"].ToString());
                    ht.Add("city", json1["city"].ToString());
                    ht.Add("province", json1["province"].ToString());
                    ht.Add("country", json1["country"].ToString());
                    ht.Add("headimgurl", json1["headimgurl"].ToString());
                    ht.Add("subscribe_time", UnixTimeToTime(json1["subscribe_time"].ToString()));
                    ht.Add("verify", 1);
                    ht.Add("Remark", json1["remark"].ToString());
                    ht.Add("GroupID", json1["groupid"].ToString());
                    ht.Add("Flag", 1);
                    ht.Add("schoolid", new TemporaryVar().UserID);
                    CommonData.Insert("KS_weixinopenuser", ht);
                }
            }
        }
        #endregion
    }
    private DateTime UnixTimeToTime(string timeStamp)
    {
        #region 时间转换
        DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
        long lTime = long.Parse(timeStamp + "0000000");
        TimeSpan toNow = new TimeSpan(lTime);
        return dtStart.Add(toNow);
        #endregion
    }
    protected void DDlAddgroups_SelectedIndexChanged(object sender, EventArgs e)
    {
        string groupId = KSCMS.S("DDlAddgroups");
        string openid = Utils.FilterIDs(KSCMS.S("ids"));
        if (openid == null || openid == "0")
        {
            Msg.Alert("请选择要移动分组的粉丝！",BasicField.GetUserUrl("wx/wx_UserList"));
        }
        else
        {
            using (DataTable dt = DataFactory.GetDataTable("select openid from KS_WeixinOpenuser Where id in(" + openid + ") and schoolID="+new TemporaryVar().UserID+""))
            {
                if (dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        string res = "";
                        string Access_tokento = ks_weixin.IsExistAccess_Token(1);
                        string posturl = "https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token=" + Access_tokento;
                        string postData = "{\"openid\":\"" + dr["openid"].ToString() + "\",\"to_groupid\":\"" + groupId.ToString() + "\"}";
                        res = ks_weixin.PostUrl(posturl, postData);
                        JObject jsonObj = JObject.Parse(res);
                        string isright = jsonObj["errcode"].ToString();//0
                        string istrueorfalse = jsonObj["errmsg"].ToString();//ok
                        if (isright.Equals("0") && istrueorfalse.Equals("ok"))
                        {
                            Hashtable ht = new Hashtable();
                            ht.Add("GroupID", groupId.ToString());
                            CommonData.Update("KS_WeixinOpenuser", ht, "where OpenID='" + dr["openid"].ToString() + "' and schoolID=" + new TemporaryVar().UserID + "");
                        }
                        else
                        {
                        }
                    }
                }
            }
            Msg.Alert("移动用户成功",BasicField.GetUserUrl("wx/wx_UserList"));
        }
    }
    protected void Button1_Click()
    {
        if (KSCMS.S("ids") != "")
        {
            string ids = KSCMS.S("ids").Replace(" ", "");
            string[] id_arr = ids.Split(',');
            Hashtable ht = new Hashtable();
            foreach (string id2 in id_arr)
            {
                ht.Add("id", id2);
                ht.Add("schoolID", new TemporaryVar().UserID);
                CommonData.Delete("KS_WeixinOpenuser", ht);
                ht.Clear();
            }
            Msg.Alert("提示,删除粉丝成功!", KSCMS.GetComeUrl());
            isLoadPage = false;
            return;
        }
    }


    protected void BtnRefAll_Click()
    {
        #region 同步所有
        DateTime starttime = DateTime.Now;
        ShowMain("从微信服务器同步粉丝到本站");
        string token = ks_weixin.IsExistAccess_Token(1);
        string next_openid = string.Empty;
        string url = ks_weixin.GetUserListUrl + "access_token=" + token;

        string josn = GetUserJosn(url);
        JObject json1 = JObject.Parse(josn);
        if (json1["data"] == null)
        {
            Msg.Alert("对不起，没有找到粉丝！");
        }
        JObject openid = JObject.Parse(json1["data"].ToString());

        Hashtable ht = new Hashtable();
        ht.Add("Flag", 0);
        CommonData.Update("KS_weixinopenuser", ht, "where  Subscribe=1 and schoolID="+new TemporaryVar().UserID+"");
        #region
        int totalNum = Utils.StrToInt(json1["total"].ToString());
        int nn = 0;
        if (totalNum > 10000)
        {
            int perPage = 10000;
            if (totalNum % perPage == 0)
            {
                nn = totalNum / perPage;
            }
            else
            {
                nn = totalNum / perPage + 1;
            }
            next_openid = json1["next_openid"].ToString();
        }
        else
        {
            next_openid = json1["next_openid"].ToString();
        }

        for (int ii = 0; ii < Utils.StrToInt(json1["count"].ToString()); ii++)
        {
            currNum++;
            //  if (currNum % 10 == 0)
            {
                InnerJS(currNum, totalNum);
            }
            getuserinfo(openid["openid"][ii].ToString(), token);
        }

        #endregion

        #region 把next_openid和Count写入XML
        SaveXMl(next_openid);
        #endregion

        DataFactory.ExecuteNonQuery("update KS_WeixinEpConfig set UserListTotal='" + json1["total"].ToString() + "' where userid=" + new TemporaryVar().UserID + "");
        #endregion
        #region  分批获取
        for (int i = 0; i < nn; i++)
        {
            if (i > 0)
            {
                next_openid = DataFactory.GetOnlyValue("select top 1 UserListNextOpenID from KS_Weixinepconfig where userid=" + new TemporaryVar().UserID + "");
            }
            fb(token, next_openid);
        }
        #endregion

        DataFactory.ExecuteNonQuery("Delete From KS_weixinopenuser where Subscribe=1 and Flag=0 and schoolID=" + new TemporaryVar().UserID + "");

        Msg.Alert("同步成功！", BasicField.GetUserUrl("wx/wx_UserList"));


    }
    private static void InnerJS(int NowNum, int TotalNum)
    {
        #region 显示进度
        KSCMS.W("<script>");
        KSCMS.W(string.Format(@"img2.width={0};", ((double)NowNum / TotalNum) * 400));
        KSCMS.W(string.Format(@"txt2.innerHTML=""更新进度:{0}"";", (((double)NowNum / TotalNum) * 100).ToString("f2")));
        KSCMS.W(string.Format(@"txt3.innerHTML=""总共需要更新 <font color=red><b>{0}</b></font> 位,<font color=red><b>在此过程中请勿刷新此页面！！！</b></font> 系统正在同步第 <font color=red><b>{1}</b></font> 位粉丝"";", TotalNum, NowNum));
        KSCMS.W("<"+"/"+"script>");
        //  KSCMS.Flush();
        #endregion

    }
    private static void ShowMain(string tips)
    {
        #region 显示主体
        string str = string.Format(@"
				  <!DOCTYPE html><html>
				  <head>
					<link href='/SysImg/teacher/css/newswx.css' rel='stylesheet'/>
				  </head>
                  <body scroll=no bgcolor='transparent'>
                   <div id='manage_top' class='toptitle menu_top_fixed'>{0}</div><div class=""menu_top_fixed_height""></div> 
", tips);


        str += @"<div><div class=""content-area""> ";
        str += @"<table id=""BarShowArea"" width=""400"" border=""0"" align=""center"" cellspacing=""1"" cellpadding=""1"">
				    <tr>
				    <td bgcolor=000000>
				     <table width=""400"" border=""0"" cellspacing=""0"" cellpadding=""1"">
				    <tr>
				    <td bgcolor=ffffff height=9 style=""text-align:left""><img src=""../../sysimg/default/bar.gif"" width=0 height=10 id=img2 name=img2 align=absmiddle></td></tr></table>
				    <td bgcolor=ffffff height=9><span width=0 height=16 id=Span1 name=img2 align=absmiddle bgcolor='#000000'></span></td></tr></table>
				    </td></tr></table>
				    <table width=""550"" border=""0"" align=""center"" cellspacing=""1"" cellpadding=""1""><tr>
				    <td align=center> <span id=txt2 name=txt2 style=""font-size:9pt"">0</span><span id=txt4 style=""font-size:9pt"">%</span></td></tr>
				    <tr><td align=center><span id=txt3 name=txt3 style=""font-size:9pt"">0</span></td></tr>
				    </table>
    			 </div>
    		 

           </body>
         </htmL>
              ";
        KSCMS.W(str);
        #endregion
    }
    protected void Btn_Save_Click()
    {
        //保存备注

        string openid =string.Empty;
        if (HttpContext.Current.Request["openid"] != null)
        {
            openid = HttpContext.Current.Request["openid"].ToString();
        }
        if (string.IsNullOrEmpty(KSCMS.S("txtRemarkName")))
        {
            Msg.Alert("请输入备注名称");
            return;
        }
        if (KSCMS.S("txtRemarkName").Trim().Length > 30)
        {
            Msg.Alert("备注名称应在30个字符之内");
            return;
        }

        string res = "";
        string Access_tokento = ks_weixin.IsExistAccess_Token(1);
        string posturl = ks_weixin.GetUserInfoRemark + "access_token=" + Access_tokento;
        string postData = "{\"openid\":\"" + openid.ToString().Trim() + "\",\"remark\":\"" + KSCMS.S("txtRemarkName").Trim() + "\"}";
        res = ks_weixin.PostUrl(posturl, postData);
        //使用前需药引用Newtonsoft.json.dll文件
        JObject jsonObj = JObject.Parse(res);
        //获取返回结果的正确|true|false,
        string isright = jsonObj["errcode"].ToString();//0
        string istrueorfalse = jsonObj["errmsg"].ToString();//ok
        if (isright.Equals("0") && istrueorfalse.Equals("ok"))
        {
            Hashtable ht = new Hashtable();
            ht.Add("remark", KSCMS.S("txtRemarkName").Trim());
            CommonData.Update("KS_WeixinOpenuser", ht, "where OpenID='" + openid + "' and schoolID=" + new TemporaryVar().UserID + "");
            Msg.AlertDoFun("恭喜，修改备注成功!", "top.box.close();");
        }
        else
        {
            Msg.AlertDoFun("对不起，修改备注失败!", "top.box.close();");
        }
    }
    /// <summary>
    /// 移动用户到分组
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void DDlAddgroups()
    {
        /////取得分组ID
        string groupId =KSCMS.S("DDlAddgroups");
        string openid = Utils.FilterIDs(KSCMS.S("ids"));
        // KSCMS.Die(openid);
        if (openid == null || openid == "0")
        {
            Msg.Alert("请选择要移动分组的粉丝！", BasicField.GetUserUrl("wx/wx_UserList"));
            isLoadPage = false;
            return;
        }
        else
        {
            using (DataTable dt = DataFactory.GetDataTable("select openid from KS_WeixinOpenuser Where id in(" + openid + ") and schoolID=" + new TemporaryVar().UserID + ""))
            {
                if (dt.Rows.Count > 0)
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        string res = "";
                        string Access_tokento = ks_weixin.IsExistAccess_Token(1);
                        string posturl = "https://api.weixin.qq.com/cgi-bin/groups/members/update?access_token=" + Access_tokento;
                        string postData = "{\"openid\":\"" + dr["openid"].ToString() + "\",\"to_groupid\":\"" + groupId.ToString() + "\"}";
                        res = ks_weixin.PostUrl(posturl, postData);
                        JObject jsonObj = JObject.Parse(res);
                        string isright = jsonObj["errcode"].ToString();//0
                        string istrueorfalse = jsonObj["errmsg"].ToString();//ok
                        if (isright.Equals("0") && istrueorfalse.Equals("ok"))
                        {
                            Hashtable ht = new Hashtable();
                            ht.Add("GroupID", groupId.ToString());
                            CommonData.Update("KS_WeixinOpenuser", ht, "where OpenID='" + dr["openid"].ToString() + "' and schoolID=" + new TemporaryVar().UserID + "");
                        }
                        else
                        {
                        }
                    }
                }
            }
            Msg.Alert("移动用户成功",BasicField.GetUserUrl("wx/wx_UserList"));
            isLoadPage = false;
            return;
        }
    }

</script>
<%
	if (!isLoadPage) return;
%>
 <link href="/SysImg/teacher/css/newswx.css" rel="stylesheet" />
 <script>
     $(function () {
         var w = 250;
         var h = 50;
         $(".prompt_box").css("position", "fixed");
         $(".prompt_box").css("width", w).css("height", h);
         var x = ($(window).width() - w) / 2;
         var y = ($(window).height() - h) / 3;
         $(".prompt_box").css("top", y).css("left", x);
     });
</script>
    <script type="text/javascript">
        function look() {

            $("#zuijinLoading").show();
            $.ajax({
                url: "<%=BasicField.GetUserUrl("wx/wx_UserList","action-ref,newnum-"+newCount+"")%> ",
                context: document.body,
                type: "get",
                success: function (data) {
                    if (data == 'ok') {
                        KesionJS.Alert("粉丝获取成功", "location.reload();");
                    } else {
                        KesionJS.Alert("获取失败", "location.reload();");
                    }
                    $("#zuijinLoading").hide();
                }
            });
            return false;
        }
        function RefAll() {
            $("#Loading").show();
            $.ajax({
                url: "<%=BasicField.GetUserUrl("wx/wx_UserList","action-RefAll")%>",
                context: document.body,
                type: "get",
                success: function (data) {
                    if (data == 'ok') {
                        KesionJS.Alert("粉丝获取成功", "location.reload();");
                    } else {
                        KesionJS.Alert("粉丝获取失败", "location.reload();");
                    }
                    $("#Loading").hide();
                }
            });
            return false;
        }
        var box = null;
        var isreload = false;
        function openWin(title, url, reload, width, height) {
            if (width == null) width = 760;
            if (height == null) height = 450;
            isreload = reload;
            box = $.dialog.open(url, {
                id: 'topbox', lock: true, title: title, width: width, height: height, close: function () {
                    if (isreload) {
                        //top.frames['main'].location.reload();
                    }
                }
            });
        }
        function DoChange(type) {
            if (type == 1) {
                $("#action").val("move")
            }
            else if (type == 2) {

            }
            else {

            }
            $("#myForm").submit();
        }

     </script>
<div class="t_tybox">
 <div class="tytitle"><h4>微信粉丝列表</h4></div>
 <form name="myForm" method="post" action="<%=BasicField.GetUserUrl("wx/wx_UserList") %>" id="myForm">
 <input type="hidden"  value="" name="action" id="action" />
  <input type="hidden"  value="" name="do"  id="domethod" />
 	<div class="console_body">
	<%if(__info.Panel1){ %>
	<div id="Panel1">
	<div class="prompt_bg" style="display: none" id="Loading">
				<div class="prompt_box">
					<p>
						<img src="/admin/weixin/images/loading.gif" />正在刷新所有，可能有点卡，请耐心等待...</p>
				</div>
			</div>
			<div class="prompt_bg" style="display: none" id="zuijinLoading">
				<div class="prompt_box">
					<p>
						<img src="/admin/weixin/images/loading.gif" />正在刷新最近，请耐心等待...</p>
				</div>
			</div>
			
			<div class="content-area">
				<div class="openKey">如果您对粉丝已经移动分组，粉丝列表没有变化的话，请重新点击刷新按钮，如果移动分组的下拉没有变化，是因为缓存的原因，其实微信平台的数据已经更新啦，请您耐心等待！<br />
					<font color="red">注意移动分组最多只全选50个粉丝同时进行分组！这里的删除是操作数据库</font></div>
				<div class="search_group">
					<div class="search">
						<input id="TxtKey" name="TxtKey" class="search_box" value="" />
						<input type="submit" value="" ID="buttonsearch" class="search_btn" />
					</div>

					<input type="submit" ID="Submit1" class="delete_fans" value="删除粉丝" onclick="if (GetIDS('del')) { $('#domethod').val('del'); return true } else { return false }" />
						<input type="submit" value="从微信同步到本站" ID="Submit2" class="delete_fans" onclick=" $('#domethod').val('tb')" />
					<a href="<%=BasicField.GetUserUrl("wx/wx_UserGroupList") %>">分组管理</a>
					<div class="clear"></div>
				</div>
				<div class="bottom_group">
					<ul>
						<li id="p15">
							<div class="shuaixuan">
								<label><input type="checkbox" name="chkall" id="chkall" onclick="CheckAll(this.form);" class="qx_btn" />全选</label>
								<%
								 string select1 = "<option value=\"-1\">移动用户到分组</option>";
								 string select2 = "<option value=\"-1\">分组统计</option>";
								 string jsonres = "";
								 string content = Cache["AllGroups_content"] as string;
								 string Access_tokento = ks_weixin.IsExistAccess_Token(1);
								 if (content == null)
								 {
									 jsonres = "https://api.weixin.qq.com/cgi-bin/groups/get?access_token=" + Access_tokento;
									 HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(jsonres);
									 myRequest.Method = "GET";
									 HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse();
									 StreamReader reader = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);
									 content = reader.ReadToEnd();
									 reader.Close();
									 //设置缓存的数据7000秒后过期
									 Cache.Insert("AllGroups_content", content, null, DateTime.Now.AddSeconds(7000), System.Web.Caching.Cache.NoSlidingExpiration);
								 }
						  
								 //使用前需要引用Newtonsoft.json.dll文件
								 JObject json1 = JObject.Parse(content);
								 if (json1["groups"] != null)
								 {
									 JArray jsonObj = (JArray)JsonConvert.DeserializeObject(json1["groups"].ToString());
									 foreach (var item in jsonObj)
									 {
										 select1 += "<option value=\"" + item["id"].ToString() + "\">" + item["name"].ToString() + "(" + item["count"].ToString() + ")" + "</option>";
										 string selected = "";
										 if (Session["group"]!=null&&Session["group"].ToString() == item["id"].ToString())
										 {
											 selected = "selected";
										 }
										 select2 += "<option " + selected + " value=\"" + item["id"].ToString() + "\">" + item["name"].ToString() + "</option>";
									 }
								 }
								 KSCMS.W("<select name=\"DDlAddgroups\" class=\"DDlAddgroups\" onchange=\"DoChange(1)\">"+select1+"</select>");
								 KSCMS.W("<select name=\"DDLgroups\" class=\"DDLgroups\" onchange=\"DoChange(2)\">" + select2 + "</select>");
									   %>
							</div>
						</li>
						<span class="tishi_message">
                             总共 <sapn style="color: Red"><span ID="count"/><%=__info.count %></sapn>位粉丝 ,今日新增<font style="color: Red" class="newnum"><%=todayCount%></font>位粉丝
						</span>
						<span style="float: right; padding-right: 10px; height: 25px; line-height: 25px;">
							<select ID="drSex" name="drSex" onchange="DoChange(3)">
							    <option <%= Utils.StrToInt(__info.drSex)==0?"selected":"" %> value="0">--按性别查看--</option>
								<option <%= Utils.StrToInt(__info.drSex)==1?"selected":"" %> value="1">男</option>
								<option <%= Utils.StrToInt(__info.drSex)==2?"selected":"" %> value="2">女</option>
							</select>
						</span>
						<div class="clear"></div>
					</ul>
					<div class="messagebox">
						<table width="99%" class="CTable" align="center" border="0" cellpadding="0" cellspacing="0">
                          <tr class="CTitle">
                              <td></td>
                              <td>编号</td>
                              <td>微信头像</td>
                              <td>昵称（备注名）</td>
                              <td>性别</td>
                              <td>关注时间</td>
                              <td>城市</td>
                              <td>所属分组</td>
                              <td>操作</td>
                          </tr>
					<%
					   string sqlParam = "ks_weixinopenuser where 1=1 and schoolID=" + new TemporaryVar().UserID + "";
				
							#region 日期限制
							if (!string.IsNullOrEmpty(KSCMS.S("adddate")))
							{
								if (Utils.IsDateTime(KSCMS.S("adddate")))
								{
									sqlParam += " and [subscribe_time]>='" + KSCMS.S("adddate") + "'";
								}
							}
							#endregion
							if (Session["drSex"] != null && Session["drSex"].ToString() != "0" && !string.IsNullOrEmpty(Session["drSex"].ToString()))
							{
								sqlParam += " and sex=" + Session["drSex"].ToString();
							}
							if(!string.IsNullOrEmpty(KSCMS.S("TxtKey")))
							{
								sqlParam += " and NickName like N'%" + KSCMS.S("TxtKey") + "%'";
							}
							if (Session["group"] != null && Session["group"].ToString() != "-1" && !string.IsNullOrEmpty(Session["group"].ToString()))
							{
								sqlParam += " and GroupID='" + Session["group"].ToString() + "'";
							}
							int recordcount, pagecount;
							int PageIndex = new BasicField().GetCurrPage;
							using (DataTable dt = DataFactory.GetPage("*", sqlParam, "id", "order by subscribe_time desc", PageIndex, pagesize, out recordcount, out pagecount))
							{
								if (dt.Rows.Count > 0)
								{
									int i = 1;
									foreach (DataRow dr in dt.Rows)
									{
										KSCMS.W("<tr><td style=\"text-align: center;\"><span id=\"\"></span><input type=\"checkbox\" name=\"ids\" id=\"ids\" value='" + dr["id"].ToString() + "' />" +
													"<td align=\"center\" style=\"color: #999;\">" + ((PageIndex - 1) * pagesize + i) + "</td>" +
													"<td align=\"center\"><img src=\"" + dr["headimgurl"].ToString() + "\" height=\"40\" width=\"50\" title='OpenID：" + dr["OpenID"].ToString() + "' /></td>" +
													"<td align=\"center\" style=\"color: #999;\">" + dr["nickname"].ToString() + (Convert.ToString(dr["Remark"].ToString()) == string.Empty ? "" : "<font color='red'>(" + dr["Remark"].ToString() + ")</font>") + "</td>" +
													"<td align=\"center\" style=\"color: #999;\">" + (dr["sex"].ToString() == "1" ? "男" : "女") + "</td>" +
													"<td align=\"center\" style=\"color: #999;\">" + dr["subscribe_time"].ToString() + "</td>" +
													"<td align=\"center\" style=\"color: #999;\">" + dr["city"] + "</td>");
										KSCMS.W("<td align=\"center\">");
										string group = Cache["AllGroups_content"] as string;
				
										if (group == null)
										{
											group = (new ks_weixin()).SendGet(string.Empty, ks_weixin.GetGroupListUrl);
				
											//设置缓存的数据7000秒后过期
											Cache.Insert("AllGroups_content", group, null, DateTime.Now.AddSeconds(7000), System.Web.Caching.Cache.NoSlidingExpiration);
										}
				
										JObject jsons = JObject.Parse(group);
										if (jsons["groups"] != null)
										{
											JArray jsonObj = (JArray)JsonConvert.DeserializeObject(jsons["groups"].ToString());
				
											foreach (var item in jsonObj)
											{
												
												if (item["id"].ToString().Equals(dr["groupid"].ToString()))
												{
													KSCMS.W("<input type='text' value=" + item["name"].ToString() + " class='TxtGroupName' Style=\"color: #999;\">");
												}
											}
										}
										i++;
										KSCMS.W("</td><td align=\"center\"><a class=\"update_user\" href=\"javascript:void(0)\" onclick=\"openWin('修改备注','" + BasicField.GetUserUrl("wx/wx_UserList", "frame-no,action-modifyremark,openid-" + dr["OpenID"].ToString() + "") + "',true,500,250)\" title=\"修改备注\">修改备注</a></td> </tr>");
									}
								}
								else
								{
									KSCMS.W("<tr width=\"100%\" ><td class=\"empty\" colspan=\"9\" style=\"padding: 10px; text-align: center;\">你还没有粉丝信息</td></tr>");
								}
							}
						  %>
						
						  </table>
					</div>
				</div>
			    <div class="fy_box">
				 <%
                    #region 分页
                    string PageStr = "[KS:PageStr1]";
                    BasicField.ReplaceFilterPage(ref PageStr, PageIndex, pagesize, pagecount, recordcount);
                    KSCMS.W(PageStr);
                    #endregion
                 %>
                </div>
                <div class="clear"></div>
		</div>
		</div>
		<%}else{ %>
		<div ID="Panel2">
			<table style="width: 100%; margin: 20px auto 20px auto;" cellpadding="0" cellspacing="0">
				<tr>
					<td style="text-align: right;"><strong>OpenID：</strong></td>
					<td><%=KSCMS.GetParam("openid",false) %><input type="hidden" name="openid" value="<%=KSCMS.GetParam("openid",false) %>" /></td>
				</tr>
				<tr>
					<td style="text-align: right;"><strong>备注名称：</strong></td>
					<td>
						<input name="txtRemarkName" value="<%=__info.txtRemarkName %>" class="inputstyle" />
					</td>
				</tr>
				<tr>
					<td></td>
					<td>
					<input type="submit" value="确定" ID="Submit3" class="save_group" onclick="$('#domethod').val('saves')" />
				</tr>
			</table>
		</div>
		<%} %>


	</div>
 </form>
</div>