<%@ 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" %>
<%@ Import Namespace="Newtonsoft.Json.Linq" %>

<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;
    private string FieldsXML = string.Empty;
    protected void Page_Load(object sender, EventArgs e)
    {
        string DoMethod = BasicField.GetParam("do");
        if (string.IsNullOrEmpty(DoMethod))
        {
            DoMethod = KSCMS.S("action");
        }
        __info.RdbTemplateMsg = "0";
        __info.ListCount = 0;
        switch (DoMethod)
        {
            case "gettemp":
                Button1_Click();
                break;
            case "close":
                RdbTemplateMsg_SelectedIndexChanged();
                break;
            case "open":
                RdbTemplateMsg_SelectedIndexChanged();
                break;
        }
        int TemplateMsg = Utils.StrToInt(DataFactory.GetOnlyValue("select top 1 TemplateMsg from KS_Weixinepconfig where userid=" + new TemporaryVar().UserID + ""));
        __info.RdbTemplateMsg = TemplateMsg.ToString();
        if (TemplateMsg == 1)
        {
            __info.listPanel = true;
        }
        else
        {
            __info.listPanel = false;
        }
    }
    protected void RdbTemplateMsg_SelectedIndexChanged()
    {
        DataFactory.ExecuteNonQuery("update KS_WeixinepConfig set TemplateMsg=" + Utils.StrToInt(KSCMS.S("RdbTemplateMsg")).ToString() + " where userid=" + new TemporaryVar().UserID + "");
        Msg.Alert("恭喜，设置成功！", BasicField.GetUserUrl("wx/wx_TemplateMsg"));
    }
    protected void Button1_Click()
    {
        DataFactory.ExecuteNonQuery("update KS_WeixinepConfig set TemplateMsg=" + Utils.StrToInt(KSCMS.S("RdbTemplateMsg")).ToString() + " where userid=" + new TemporaryVar().UserID + "");

        #region 删除已有的模板消息
        string token = ks_weixin.IsExistAccess_Token(1);
        string jsonres = "https://api.weixin.qq.com/cgi-bin/template/get_all_private_template?access_token=" + token;
        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 json1 = JObject.Parse(content);
        if (!string.IsNullOrEmpty(json1["errmsg"].ToString()))
        {
            Msg.Alert(json1["errmsg"].ToString());
            return;
        }
        else
        {
            JArray jsonObj = (JArray)JsonConvert.DeserializeObject(json1["template_list"].ToString());
            foreach (var item in jsonObj)
            {
                string url = "https://api.weixin.qq.com/cgi-bin/template/del_private_template?access_token=" + token;
                string postData = @"{  ""template_id"":""" + item["template_id"].ToString() + @""" }";
                string jsonress = ks_weixin.PostUrl(url, postData);
                var jsonArray = JObject.Parse(jsonress);
                if (jsonArray["errcode"].ToString() != "0")
                {
                    Msg.Alert("删除已有模板消息失败，请登录mp.weixin.qq.com，先删除所有模板消息。再重试！");
                    return;
                }
            }
        }
        #endregion
        string[] arry = KSCMS.S("orderid").Split(',');
        for (int i = 0; i < arry.Length; i++)
        {
            int sid = Utils.StrToInt(arry[i].ToString());
            string id = KSCMS.S("tpids").Split(',')[i].ToString();
            string oldTemplateId = KSCMS.S("myids").Split(',')[i].ToString();
            Hashtable ht = new Hashtable();
            ht.Add("enable", KSCMS.S("checkids").Split(',')[i].ToString());

            if (KSCMS.S("checkids").Split(',')[i].ToString() == "1")
            {
                string url = ks_weixin.GetTemplateMessageTpId + "access_token=" + token;
                string postData = @"{  ""template_id_short"":""" + id + @""" }";

                jsonres = ks_weixin.PostUrl(url, postData);

                if (jsonres.IndexOf("template num exceeds") != -1)
                {
                    Msg.Alert("出错啦，模板数最多只能开启25个。如果您确认选择的个数小于25个，请先登录微信公众平台(http://mp.weixin.qq.com)删除所有模板消息，再重新获取！ ");
                    return;
                }
                var jsonArray = JObject.Parse(jsonres);
                string myTemplateID = jsonArray["template_id"].ToString();
                ht.Add("mytemplateid", myTemplateID);
            }
            else
            {
                ht.Add("mytemplateid", "");
            }
            CommonData.Update("KS_Weixineptemplate", ht, "where userid=" + new TemporaryVar().UserID + " and orderid=" + (i+1) + "");
        }
        Msg.Alert("恭喜,批量获取我的消息模板ID成功！");
        return;

    }
</script>
<%
	if (!isLoadPage) return;
%>
 <link rel="stylesheet" type="text/css" href="/admin/weixin/images/font/css/font-awesome.min.css">
 <link href="/SysImg/teacher/css/newswx.css" rel="stylesheet" />
 <div class="t_tybox">
 <div class="tytitle"><h4>微信消息模板</h4></div>
 <form name="myForm" method="post" action="<%=BasicField.GetUserUrl("wx/wx_TemplateMsg") %>" id="myForm">
 <div class="console_body">
 <input type="hidden" value="" name="action" id="action" />     
     <table width="100%" border="0" cellpadding="1" cellspacing="1" class="template_msg_top" style="border-bottom:none;  border:1px solid #eee;"> 
          <tr>
             <td class="lefttd" align="right"><b>是否启用模板消息功能：</b></td>
             <td class="righttd">
                <table id="RdbTemplateMsg" border="0">
                    <tr>
                        <td><span class="star_input"><input id="RdbTemplateMsg_0" type="radio" name="RdbTemplateMsg" onclick="location.href='<%=BasicField.GetUserUrl("wx/wx_TemplateMsg","do-open,RdbTemplateMsg-1")%>'" value="1" <%=Utils.StrToInt(__info.RdbTemplateMsg)==1?"checked":"" %>  /><label for="RdbTemplateMsg_0">启用</label></span></td>
                        <td><span class="star_input"><input id="RdbTemplateMsg_1" type="radio" name="RdbTemplateMsg"  onclick="location.href='<%=BasicField.GetUserUrl("wx/wx_TemplateMsg","do-close,RdbTemplateMsg-0")%>'" value="0" <%=Utils.StrToInt(__info.RdbTemplateMsg)==0?"checked":"" %> /><label for="RdbTemplateMsg_1">不启用</label></span></td>
                    </tr>
                </table>
             </td>
             <td><span class="tips">1、只有认证通过的微信服务号才能使用本功能。<br />
                 2、需要登录微信公众平台中心，将行业分类设置为：IT科技/互联网|电子商务，IT科技/IT软件与服务</span>
             </td>
          </tr>
    </table>	
	<% if(__info.listPanel){ %>
    <div ID="listPanel" Width="100%">
        <table width="100%" border="0" cellpadding="1" cellspacing="1" class="template_msg_top" style="border-bottom:none;"> 
           <tr>
            <td style="padding:0;">
                <input type="submit" name="Button1" value="一键获取我的模板ID" onclick="return (check());" id="Button1" class="button" style="vertical-align: middle; margin-right:15px;" />
                <input type="checkbox" name="chkall" id="chkall" onclick="selectAll(this.checked);"/><label for="chkall">全部选中</label>                  &nbsp;&nbsp;
            </td>
           </tr>
        </table>
        <script>
        	function selectAll(b) {
        		$(".template_msg").find("input[type='checkbox']").each(function () {
        			$(this).prop("checked", b);
        		});
        	}
        	function check() {
        		var num = 0;
        		$(".template_msg").find("input[type='checkbox']").each(function () {
        			if ($(this).prop("checked") == true) {
        				num++;
        			}
        		});
        		if (num > 25) {
        			KesionJS.Alert('温馨提示：最多只能选择25个模板消息，您当前选择了' + num + '个！');
        			return false;
        		} else {
        			$("#action").val("gettemp");
        			return true;
        		}
            }
            function setvalue(id,obj) {
                if ($(obj).attr("checked") == "checked") {
                    $("#checkids" + id).val("1");
                }
                else {
                    $("#checkids" + id).val("0");
                }
            }
        </script>
		<table class="template_msg" cellspacing="0" border="0" id="list" style="width:100%;border-collapse:collapse;">
			<tr class="CTitle">
				<th scope="col">序号</th><th scope="col">模板库编号</th><th scope="col">启用</th><th scope="col">标题</th><th scope="col">我的模板ID</th>
			</tr>
			<%
                string param = "";
                if (System.IO.Directory.Exists(Utils.GetMapPath("/admin/agent/")) == false)
                {
                    param = " and (orderid<16 or orderid>23)";
                }
                using (DataTable dt = DataFactory.GetDataTable("select * from KS_WeixinEpTemplate where userid=" + new TemporaryVar().UserID + " " + param + " order by orderid asc"))
                {
                    if (dt.Rows.Count > 0)
                    {
                        __info.ListCount = Utils.StrToInt(dt.Rows.Count);
                        foreach (DataRow dr in dt.Rows)
                        {
                            KSCMS.W("<tr><td class=\"Ctd\" align=\"left\"  style=\"width:10%;\">" + dr["orderid"].ToString() + "<input type=\"hidden\" value=\"" + dr["orderid"].ToString() + "\" name=\"orderid\"></td>" +
                                "<td class=\"Ctd\" align=\"left\"  style=\"width:20%;\">" + dr["templateID"].ToString() + "<input type=\"hidden\" value=\"" + dr["templateID"].ToString() + "\" name=\"tpids\"></td>" +
                                "<td class=\"Ctd\" align=\"left\"  style=\"width:10%;\">" +
                                "<input type=\"checkbox\"  " + (dr["enable"].ToString() == "1" ? "checked" : "") + " onclick='setvalue("+dr["orderid"].ToString()+",this)' /><input type='hidden' id='checkids"+dr["orderid"].ToString()+"' value='"+dr["enable"].ToString()+"' name='checkids'></td>" +
                 " <td class=\"Ctd\" align=\"left\"  style=\"width:20%;\">" + dr["name"].ToString() + "</td><td class=\"Ctd\" align=\"left\"  style=\"width:40%;\">" + dr["MyTemplateID"].ToString() + "<input type=\"hidden\" value=\"" + dr["MyTemplateID"].ToString() + "\" name=\"myids\"></td> </tr>");
                        }
                    }
                    else
                    {
                        KSCMS.W("暂无数据，请同步微信模板！");
                    }
                }
	    %>
			</table>

     <br />
      <div class="warn_templatemsg">
        <script type="text/javascript">
        	showtips('<span class="state"><strong>说明：</strong><br /></span>1、使用请先执行一键获取我的模板ID；<br/>2、微信限制每次最多只能同时开通15个模板消息，如果获取我的模板ID提示数量已过过15个，请登录微信公众平台管理里，先删除模板，再重新获取；');
		</script>
      </div>
    
   
   
     </div>
  <%} %>
  
  </div>
 </form>
</div>