<%@ 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="System.Data" %>
<%@ Import Namespace="System.Xml" %>
<%@ 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;

    protected void Page_Load(object sender, EventArgs e)
    {
        string DoMethod = BasicField.GetParam("do");
        if (string.IsNullOrEmpty(DoMethod))
        {
            DoMethod = KSCMS.S("action");
        }
        __info.txtGroupName = "";
        __info.Btn_Modify = "";
        __info.Btn_Save = "";

        if (!IsPostBack)
        {
            BindGroupList();
            __info.Panel1 = true;
            if (KSCMS.S("do") == "modify")
            {
                __info.Panel1 = false;
                __info.Btn_Modify = "";
                __info.Btn_Save = "none";
                modify();
            }
            if (KSCMS.S("action") == "add")
            {
                __info.Panel1 = false;
                __info.Btn_Modify = "none";
                __info.Btn_Save = "";
            }
            if (KSCMS.S("do") == "del")
            {
                string res = "";
                string Access_tokento = ks_weixin.IsExistAccess_Token(1);
                string posturl = ks_weixin.GetGroupDeleteUrl + "access_token=" + Access_tokento;
                string groupid = Utils.StrToInt(KSCMS.S("groupid")).ToString();
                string postData = "{\"group\":{\"id\":" + groupid.ToString() + "}}";
                res = ks_weixin.PostUrl(posturl, postData);
                Hashtable ht = new Hashtable();
                ht.Add("GroupID", groupid);
                CommonData.Delete("KS_WeiXinGroupInfo", ht);
                Msg.Alert("删除成功！由于缓存问题，您可能需要重新登录才能看到效果！", BasicField.GetUserUrl("wx/wx_UserGroupList"));
                isLoadPage = false;
                return;
            }
            if (KSCMS.S("action") == "save")
            {
                if (string.IsNullOrEmpty(KSCMS.S("txtGroupName")))
                {
                    Msg.Alert("请输入分组名称");
                    isLoadPage = false;
                    return;
                }
                if (KSCMS.S("txtGroupName").Trim().Length > 30)
                {
                    Msg.Alert("组名称应在30个字符之内");
                    isLoadPage = false;
                    return;
                }

                string res = "";
                string Access_tokento = ks_weixin.IsExistAccess_Token(1);
                string posturl = ks_weixin.GetGroupAddUrl + "access_token=" + Access_tokento;
                string postData = "{\"group\":{\"name\":\"" + KSCMS.S("txtGroupName").Trim() + "\"}}";
                res = ks_weixin.PostUrl(posturl, postData);

                Hashtable ht = new Hashtable();
                ht.Add("userid", new TemporaryVar().UserID);
                ht.Add("GroupName", KSCMS.S("txtGroupName").Trim());
                CommonData.Insert("KS_WeiXinGroupInfo", ht);
                Msg.AlertDoFun("恭喜，创建成功!", "top.box.close();");
                isLoadPage = false;
                return;
            }
            if (KSCMS.S("action") == "modify")
            {
                if (string.IsNullOrEmpty(KSCMS.S("txtGroupName")))
                {
                    Msg.Alert("请输入分组名称");
                    isLoadPage = false;
                    return;
                }
                if (KSCMS.S("txtGroupName").ToString().Trim().Length > 30)
                {
                    Msg.Alert("组名称应在30个字符之内");
                    isLoadPage = false;
                    return;
                }

                string res = "";
                string Access_tokento = ks_weixin.IsExistAccess_Token(1);
                string posturl = ks_weixin.GetGroupUpDateUrl + "access_token=" + Access_tokento;
                string postData = "{\"group\":{\"id\":" + KSCMS.S("groupId").Trim() + ",\"name\":\"" + KSCMS.S("txtGroupName").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("GroupName", KSCMS.S("txtGroupName").Trim());
                    CommonData.Update("KS_WeiXinGroupInfo", ht, "where GroupID='" + KSCMS.S("groupId") + "' and userid="+new TemporaryVar().UserID+"");
                    Msg.AlertDoFun("恭喜，修改成功!", "top.box.close();");
                    isLoadPage = false;
                    return;
                }
                else
                {
                    Msg.AlertDoFun("对不起,修改失败!", "top.box.close();");
                    isLoadPage = false;
                    return;
                }
            }
        }
    }
    private void BindGroupList()
    {
        string group = Cache["AllGroups_content"] as string;
        if (group == null)
        {
            group = (new ks_weixin()).SendGet(string.Empty, ks_weixin.GetGroupListUrl);
            Cache.Insert("AllGroups_content", group, null, DateTime.Now.AddSeconds(7000), System.Web.Caching.Cache.NoSlidingExpiration);
        }
        JObject json1 = JObject.Parse(group);
        JValue ss=  new JValue("s");
       
        if ( json1["errmsg"]!=null)
        {
            Msg.Alert(json1["errmsg"].ToString());
            return;
        }
        else
        {
            JArray jsonObj = (JArray)JsonConvert.DeserializeObject(json1["groups"].ToString());
            DataFactory.ExecuteNonQuery("delete from KS_WeiXinGroupInfo");
            foreach (var item in jsonObj)
            {
                Hashtable ht = new Hashtable();
                ht.Add("GroupID", item["id"].ToString());
                ht.Add("GroupName", item["name"].ToString());
                ht.Add("GroupCount", item["count"].ToString());
                ht.Add("userid", new TemporaryVar().UserID);
                CommonData.Insert("KS_WeiXinGroupInfo", ht);
            }
        }
    }
    private void modify()
    {
        using (DataTable dt = DataFactory.GetDataTable("select top 1 * from KS_WeiXinGroupInfo where GroupID='" + KSCMS.S("groupId") + "' and userid="+new TemporaryVar().UserID+""))
        {
            if (dt.Rows.Count > 0)
            {
                DataRow dr = dt.Rows[0];
                __info.txtGroupName = dr["GroupName"].ToString();
            }
        }
    }

</script>
<%
	if (!isLoadPage) return;
%>
<script>
	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();
				}
			}
		});
	}
</script>
 <link href="/admin/weixin/images/style.css" rel="stylesheet" />
 <form name="myForm" method="post" action="<%=BasicField.GetUserUrl("wx/wx_UserGroupList") %>" id="myForm">
 <input type="hidden"  value="" name="action" id="action" />
	    <div class="content-area">   
		<%if(__info.Panel1){ %>
    <div ID="Panel1">
        <div class="message top_message">
           由于缓存的原因，两个小时才会更新数据库，其实微信平台已经更新啦！注意最多只能100组！
         </div>
       <div>
             <a Class="Btn_add_group"  href="javascript:void(0)" onclick=" top.openWin('创建分组', '<%=BasicField.GetUserUrl("wx/wx_UserGroupList","action-add,frame-no") %> ', true, 500, 250)" title="创建分组">+创建分组</a>
       </div>
        <div class="groupmanage">
            <table style="width:100%;margin: 10px 0;border: 1px solid #e7e7eb;text-align:center;" cellpadding="0" cellspacing="0">
			 <tr class="RepeaterGroup">
            <th width="17.5%">序号</th>
            <th width="17.5%">ID编号</th>
            <th width="17.5%">分组名称</th>
            <th width="17.5%">分组人数</th>
            <th width="30%">操作</th>
          </tr>
			<%

                int pagesize = 20;
                int CurrPage = new BasicField().GetCurrPage;
                int recordcount, pagecount;
                using (DataTable dt = DataFactory.GetPage("*", "KS_WeiXinGroupInfo", "id", "order by id desc", CurrPage, pagesize, out recordcount, out pagecount))
                {
                    if (dt.Rows.Count > 0)
                    {
                        int i = 1;
                        foreach (DataRow dr in dt.Rows)
                        {
                            KSCMS.W("<tr><td><span>" + (pagesize * (CurrPage - 1) + i) + "</span></td><td>" + dr["GroupID"].ToString() + "</td><td>" + dr["GroupName"].ToString() + "</td><td>" + dr["GroupCount"].ToString() + "</td>" +
                            "<td><a  href=\"javascript:void(0)\" onclick=\" top.openWin('分组操作', '" + BasicField.GetUserUrl("wx/wx_UserGroupList", "frame-no,do-modify,groupId-" + dr["groupid"].ToString()) + "', true, 500, 250)\" title=\"修改分组\" class=\"updata_name\">修改分组名称</a>" +
                   " <a href=\"" + BasicField.GetUserUrl("wx/wx_UserGroupList", "do-del,groupid-" + dr["groupid"].ToString()) + "\">删除分组</a></td>     </tr>");
                            i++;
                        }
                    }

                }
	    %>

    </table>
        </div>
           <%
            #region 分页
            string PageStr = "[KS:PageStr2]";
            BasicField.ReplaceFilterPage(ref PageStr, CurrPage, CurrPage, pagecount, recordcount);
            KSCMS.W(PageStr);
            #endregion
         %>
    </div>
	<%}else{ %>
<div ID="Panel2">
    <table style=" width:100%;margin:20px auto 20px auto;" cellpadding="0" cellspacing="0">
      
      <tr>
        <td style="text-align:right;">分组名称：</td>
        <td> 
            <input type="hidden" value="<%=KSCMS.S("groupId") %>" name="groupid" />
		  <input type="text" class="inputstyle" maxlength="30" id="txtGroupName" value="<%=__info.txtGroupName %>" name="txtGroupName"/>
        </td>
      </tr>
      <tr>
        <td></td>
        <td>
			<input type="submit" value="保存" style="display:<%=__info.Btn_Save%>" Class="save_group" onclick="$('#action').val('save')" />

				<input type="submit" value="修改" style="display:<%=__info.Btn_Modify%>" Class="save_group" onclick="$('#action').val('modify')" />
      </tr>
    </table>
</div>
<%} %>
</div>
 </form>
