<%@ 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="System.Net" %>
<%@ Import Namespace="System.IO" %>
<%@ 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;
    public int QunFaID = 0;
    public int WeiXinType = 0;
    public int SendCount = 4;
    public int sendtype = 0;
    protected void Page_Load(object sender, EventArgs e)
    {
        string DoMethod = KSCMS.S("do");
        __info.setbtn="";
        __info.Panel1=true;
        __info.TxtContent = "";
        if (string.IsNullOrEmpty(DoMethod))
        {
            DoMethod = KSCMS.S("action");
        }
        sendtype = Utils.StrToInt(KSCMS.S("sendtype"));
        WeiXinType = Utils.StrToInt(DataFactory.GetOnlyValue("select top 1 WeiXinType from KS_WeixinUser where  TypeFlag=" + new TemporaryVar().GroupID + " and userID=" + new TemporaryVar().UserID + ""));
        switch (DoMethod)
        {
            case "look":
                __info.Panel1 = false;
                break;
            case "send":
                setbtn_Click();
                break;
        }
        if (WeiXinType == 1)
        {
            int Count = Utils.StrToInt(DataFactory.GetOnlyValue("select count(id) from  KS_WeiXinQunFA where TypeFlag=" + new TemporaryVar().GroupID + " and userID=" + new TemporaryVar().UserID + "  and massStatus='成功' and  datediff(m,AddDate,getdate())=0"));
            SendCount = SendCount - Count;
            if (SendCount == 0)
            {
                __info.setbtn="none";
            }
        }
        else
        {
            int Count = Utils.StrToInt(DataFactory.GetOnlyValue("select count(id) from  KS_WeiXinQunFA where TypeFlag=" + new TemporaryVar().GroupID + " and userID=" + new TemporaryVar().UserID + "  and massStatus='成功' and datediff(d,AddDate,getdate())=0"));
            SendCount = SendCount - Count;
            if (SendCount == 3)
            {
                __info.setbtn = "none";
            }
        }
    }
    public string GetQunFaMessage(int SendCount, int WeiXinType)
    {
        #region 群发消息
        string str = string.Empty;

        if (WeiXinType == 1)
        {
            if (SendCount > 0)
            {
                str = string.Format(@" <div class=""warn"">
		               <div class=""bubble_tips_inner"">
			           <p class=""mass_send_tips"">你本月还能群发 <em class=""send_num"">{0}</em> 条消息</p>
		              </div>
		              <i class=""bubble_tips_arrow out""></i>
		              <i class=""bubble_tips_arrow in""></i>
	                  </div>", SendCount);
            }
            else
            {
                str = "<h4><font color='red'>群发次数已经达到上限啦，所以群发按钮已经屏蔽！</font></h4>";
            }
        }
        else if (WeiXinType == 0)
        {
            if (SendCount == 4)
            {
                str = string.Format(@" <div class=""warn"">
		          <div class=""bubble_tips_inner"">
			       <p class=""mass_send_tips"">你今天可以群发 <em class=""send_num"">{0}</em> 条消息</p>
		       </div>
		        <i class=""bubble_tips_arrow out""></i>
		          <i class=""bubble_tips_arrow in""></i>
	                </div>", SendCount);
            }
            else
            {
                str = "<h4><font color='red'>群发次数已经达到上限啦，所以群发按钮已经屏蔽！</font></h4>";
            }
        }
        return str;
        #endregion
    }
    public string GetSendType(string SendType)
    {
        string str = string.Empty;
        if (SendType == "0")
        {
            str = "文本";
        }
        else if (SendType == "1")
        {
            str = "素材";
        }
        else if (SendType == "2")
        {
            str = "图文";
        }
        else if (SendType == "3")
        {
            str = "商品";
        }
        else if (SendType == "4")
        {
            str = "课程";
        }
        return str;
    }
    public string GetSendContent(string content, string sucaiId, string tuwenid, string Courseid, string SendType, int CosType)
    {
        string str = string.Empty;
        if (!string.IsNullOrEmpty(content))
        {
            if (SendType == "0")
            {
                str = "<a href=\"javascript:;\" title=\"" + content + "\">" + content + "</a>";
            }
        }
        if (!string.IsNullOrEmpty(sucaiId))
        {
            if (SendType == "1")
            {
                string title = DataFactory.GetOnlyValue("select top 1 Title from KS_WeixinPigmsg where id=" + sucaiId);
                str = "<a href=\"javascript:;\" title=\"" + title + "\">" + title + "</a>";
            }
        }
        if (!string.IsNullOrEmpty(tuwenid))
        {
            if (SendType == "2")
            {
                string[] tuwen = string.Concat(tuwenid, "§").Split('§');

                using (DataTable dt2 = DataFactory.GetDataTable("select Top 1 * from KS_EnterpriseNews where id=" + tuwen[2] + ""))
                {
                    if (dt2.Rows.Count > 0)
                    {
                        DataRow dr = dt2.Rows[0];
                        str = "<a href=\"javascript:;\" title=\"" + dr["title"].ToString() + "\">" + dr["title"].ToString() + "</a>";
                    }
                }
            }
        }
        if (!string.IsNullOrEmpty(Courseid))
        {
             string[] courseids = string.Concat(Courseid, "§").Split('§');


            if (SendType == "4")
            {
                string tableName = "KS_Course";
                if (CosType == 0)
                {
                    tableName = "KS_CourseFace";
                }
              
                using (DataTable dt2 = DataFactory.GetDataTable("select Top 1 * from " + tableName + " where courseid=" + courseids[0] + " "))
                {
                    if (dt2.Rows.Count > 0)
                    {
                        DataRow dr = dt2.Rows[0];
                        str = "<a href=\"javascript:;\" title=\"" + dr["name"].ToString() + "\">" + dr["name"].ToString() + "</a>";
                    }
                }
            }
        }
        return str;
    }
    protected void setbtn_Click()
    {

        string padata = sendGroupmessage();//jose();//_txtMenu.Text.Trim();
     
        string url = string.Empty;

        if (KSCMS.S("drType") == "1")//按用户
        {
            url = ks_weixin.SendGroupUrl + "access_token=" + ks_weixin.IsExistAccess_Token(1);// 获取用户token   
        }
        else if (KSCMS.S("drType") == "2")//按分组
        {
            url = ks_weixin.SendGroupAllUrl + "access_token=" + ks_weixin.IsExistAccess_Token(1);// 获取用户token   
        }

        byte[] byteArray = Encoding.UTF8.GetBytes(padata); // 转化
        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(url);
        webRequest.Method = "POST";
        webRequest.ContentLength = byteArray.Length;
        Stream newStream = webRequest.GetRequestStream();
        newStream.Write(byteArray, 0, byteArray.Length); //写入参数
        newStream.Close();
        HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
        StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8);
        string str = sr.ReadToEnd();
        JObject jsonObj = JObject.Parse(str);
        #region 插入数据
        if (str.IndexOf("success") > 0)
        {
            Hashtable ht = new Hashtable();
            ht.Add("AddPeople",new TemporaryVar().UserName);
            ht.Add("AddDate", DateTime.Now);
            ht.Add("TypeFlag", new TemporaryVar().GroupID);
            ht.Add("userid",new TemporaryVar().UserID);
            if (KSCMS.S("drType") == "1")
            {
                if (KSCMS.S("drsex") == "2")
                {
                    ht.Add("MassObject", "按全部用户");
                }
                else if (KSCMS.S("drsex") == "1")
                {
                    ht.Add("MassObject", "按全部用户(男粉丝）");
                }
                else if (KSCMS.S("drsex") == "0")
                {
                    ht.Add("MassObject", "按全部用户(女粉丝）");
                }
            }
            else if (KSCMS.S("drType") == "2")
            {
                ht.Add("MassObject", "按分组选择");
            }
            if (!string.IsNullOrEmpty(KSCMS.S("TxtContent")))
            {
                ht.Add("Content", KSCMS.S("TxtContent"));
                ht.Add("SendType", 0);
            }
            else if (!string.IsNullOrEmpty(KSCMS.S("TxtSuCaiID")))
            {
                ht.Add("SuCaiID", KSCMS.S("TxtSuCaiID"));
                ht.Add("SendType", 1);
            }
            else if (!string.IsNullOrEmpty(KSCMS.S("TxtTuWenID")))
            {
                ht.Add("tuwenid", KSCMS.S("TxtTuWenID"));
                ht.Add("SendType", 2);
            }
            else if (!string.IsNullOrEmpty(KSCMS.S("TxtCourseID")))
            {
                ht.Add("Courseid", KSCMS.S("TxtCourseID"));
                ht.Add("CosType",Utils.StrToInt(KSCMS.S("CosType")));
                ht.Add("SendType", 4);
            }
       
            ht.Add("massStatus ", "成功");
            if (jsonObj["msg_id"] != null)
            {
                ht.Add("MassMessageID", jsonObj["msg_id"].ToString());
            }
            CommonData.Insert("KS_WeiXinQunFA", ht);
            Msg.AlertDoFun("提示,群发信息发送成功!", "parent.location.href='" + BasicField.GetUserUrl("wx/wx_SendGroup") + "'");
            return;
        }
        else
        {
            Hashtable ht = new Hashtable();
            ht.Add("AddPeople", new TemporaryVar().UserName);
            ht.Add("AddDate", DateTime.Now);
            ht.Add("TypeFlag", new TemporaryVar().GroupID);
            ht.Add("userid", new TemporaryVar().UserID);
            if (KSCMS.S("drType") == "1")
            {
                if (KSCMS.S("drsex") == "2")
                {
                    ht.Add("MassObject", "按全部用户");
                }
                else if (KSCMS.S("drsex") == "1")
                {
                    ht.Add("MassObject", "按全部用户(男粉丝）");
                }
                else if (KSCMS.S("drsex") == "0")
                {
                    ht.Add("MassObject", "按全部用户(女粉丝）");
                }
            }
            else if (KSCMS.S("drType") == "2")
            {
                ht.Add("MassObject", "按分组选择");
            }
            if (!string.IsNullOrEmpty(KSCMS.S("TxtContent")))
            {
                ht.Add("Content", KSCMS.S("TxtContent"));
                ht.Add("SendType", 0);
            }
            else if (!string.IsNullOrEmpty(KSCMS.S("TxtSuCaiID")))
            {
                ht.Add("SuCaiID", KSCMS.S("TxtSuCaiID"));
                ht.Add("SendType", 1);
            }
            else if (!string.IsNullOrEmpty(KSCMS.S("TxtTuWenID")))
            {
                ht.Add("tuwenid", KSCMS.S("TxtTuWenID"));
                ht.Add("SendType", 2);
            }
            else if (!string.IsNullOrEmpty(KSCMS.S("TxtCourseID")))
            {
                ht.Add("Courseid", KSCMS.S("TxtCourseID"));
                ht.Add("SendType", 4);
                ht.Add("Costype", Utils.StrToInt(KSCMS.S("costype")));
            }
            ht.Add("massStatus ", "失败");
            if (jsonObj["msg_id"] != null)
            {
                ht.Add("MassMessageID", jsonObj["msg_id"].ToString());
            }
         
            CommonData.Insert("KS_WeiXinQunFA", ht);
            Msg.AlertDoFun("对不起，发送失败!", "parent.location.href='"+BasicField.GetUserUrl("wx/wx_SendGroup")+"'");
        }
        #endregion

    }
    public string sendGroupmessage()
    {

        string sb = string.Empty;
        string openid = String.Empty;
        string sqlwhere = String.Empty;
        if (KSCMS.S("sendtype") == "0")
        {
            if (string.IsNullOrEmpty(KSCMS.S("TxtContent")))
            {
                Msg.Alert("请输入群发内容!");
            }
        }
        else if (KSCMS.S("sendtype") == "1")
        {
            if (string.IsNullOrEmpty(KSCMS.S("TxtSuCaiID")))
            {
                Msg.Alert("请选择素材!");
            }
        }
        else if (KSCMS.S("sendtype") == "2")
        {
            if (string.IsNullOrEmpty(KSCMS.S("TxtTuWenID")))
            {
                Msg.Alert("请选择图文!");
            }
        }
        else if (KSCMS.S("sendtype") == "4")
        {
            if (string.IsNullOrEmpty(KSCMS.S("TxtCourseID")))
            {
                Msg.Alert("请选择课程!");
            }
        }
        if (KSCMS.S("drType") == "1")
        {
            #region 按用户群发
            if (WeiXinType == 1)
            {
                if (KSCMS.S("drsex") == "2")
                {
                    sqlwhere = "where schoolID="+new TemporaryVar().UserID+"";
                }
                else
                {
                    sqlwhere = " where sex=" + KSCMS.S("drsex") + " and schoolID="+new TemporaryVar().UserID+"";
                }
                using (DataTable dt = DataFactory.GetDataTable("select * from  KS_weixinopenuser " + sqlwhere + " order by id desc "))
                {
                    foreach (DataRow dr in dt.Rows)
                    {
                        if (string.IsNullOrEmpty(openid))
                        {
                            openid = "\"" + dr["openid"].ToString() + "\"";
                        }
                        else
                        {
                            openid += ",\"" + dr["openid"].ToString() + "\"";
                        }
                    }
                }
         
                if (KSCMS.S("sendtype") == "0")
                {
                    #region 文本
                    if (!string.IsNullOrEmpty(KSCMS.S("TxtContent")))
                    {

                        sb = "{\"touser\":[" + openid + "],\"msgtype\":\"text\",\"text\":{\"content\":\"" + Utils.ClearHtml(KSCMS.S("TxtContent")) + "!\"}}";
                    }
                    #endregion
                }
                else if (KSCMS.S("sendtype") == "1")
                {
                    if (!string.IsNullOrEmpty(KSCMS.S("TxtSuCaiID")))
                    {

                        #region 素材类型
                        using (DataTable dt = DataFactory.GetDataTable("select top 1 * from KS_WeixinPigmsg where id=" + Utils.StrToInt(KSCMS.S("TxtSuCaiID"))))
                        {
                            if (dt.Rows.Count > 0)
                            {
                                string articlesJson = GetArticlesJsonStr(ks_weixin.IsExistAccess_Token(1), dt);
                                string newsMsg = UploadNews(ks_weixin.IsExistAccess_Token(1), articlesJson);
                                string newsid = ks_weixin.GetJsonValue(newsMsg, "media_id");
                                sb = "{\"touser\":[" + openid +
                            "],\"mpnews\":{\"media_id\":\"" + newsid +
                            "\"},\"msgtype\":\"mpnews\"}";
                            }
                        }
                        #endregion
                    }
                }
                else if (KSCMS.S("sendtype") == "2")
                {
                    if (!string.IsNullOrEmpty(KSCMS.S("TxtTuWenID")))
                    {
                        #region 图文
                        string[] tuwenid = string.Concat(KSCMS.S("TxtTuWenID"), "§").Split('§');

                        using (DataTable dt2 = DataFactory.GetDataTable("select Top 1 * from KS_EnterpriseNews where id=" + tuwenid[2] + " "))
                        {
                            if (dt2.Rows.Count > 0)
                            {
                                //GetXiTongJsonStr
                                string xitongJson = GetXiTongJsonStr(ks_weixin.IsExistAccess_Token(1), dt2,1);
                                // KSCMS.W(xitongJson + "<hr>");
                                string newsMsg = UploadNews(ks_weixin.IsExistAccess_Token(1), xitongJson);
                                // KSCMS.W(newsMsg + "<hr>");
                                string newsid = ks_weixin.GetJsonValue(newsMsg, "media_id");
                                //  KSCMS.W(newsid + "<hr>");

                                sb = "{\"touser\":[" + openid +
                            "],\"mpnews\":{\"media_id\":\"" + newsid +
                            "\"},\"msgtype\":\"mpnews\"}";

                            }
                        }
                        #endregion
                    }
                }
                else if (KSCMS.S("sendtype") == "4")
                {
                    if (!string.IsNullOrEmpty(KSCMS.S("TxtCourseID")))
                    {
                        #region 商品
                        string[] Courseid = string.Concat(KSCMS.S("TxtCourseID"), "§").Split('§');
                        string tableName = "KS_Course";
                        if (Utils.StrToInt(KSCMS.S("costype")) == 0)
                        {
                            tableName = "KS_CourseFace";
                        }
                        using (DataTable dt3 = DataFactory.GetDataTable("select Top 1 * from " + tableName + " where Courseid=" + Courseid[2] + " "))
                        {
                            if (dt3.Rows.Count > 0)
                            {

                                string xitongJson = GetXiTongJsonStr(ks_weixin.IsExistAccess_Token(1), dt3,2);
                                //  KSCMS.W(xitongJson + "<hr>");
                                string newsMsg = UploadNews(ks_weixin.IsExistAccess_Token(1), xitongJson);
                                //  KSCMS.W(newsMsg + "<hr>");
                                string newsid = ks_weixin.GetJsonValue(newsMsg, "media_id");
                                // KSCMS.W(newsid + "<hr>");

                                sb = "{\"touser\":[" + openid +
                            "],\"mpnews\":{\"media_id\":\"" + newsid +
                            "\"},\"msgtype\":\"mpnews\"}";

                            }
                        }
                        #endregion
                    }
                }
            }
            #endregion
        }
        else if (KSCMS.S("drType") == "2")
        {

            #region 按分组群发
            if (KSCMS.S("sendtype") == "0")
            {
                #region 文本类型
                if (!string.IsNullOrEmpty(KSCMS.S("TxtContent")))
                {

                    sb = "{\"filter\":{\"is_to_all\":false,\"group_id\":\"" + KSCMS.S("groupname").Trim() +
                      "\"},\"text\":{\"content\":\"" + Utils.ClearHtml(KSCMS.S("TxtContent")) +
                    "\"},\"msgtype\":\"text\"}";
                    //sb = "{\"touser\":[" + openid + "],\"msgtype\":\"text\",\"text\":{\"content\":\"" + Utils.ClearHtml(KSCMS.S("TxtContent")) + "!\"}}";
                }
                #endregion
            }
            else if (KSCMS.S("sendtype") == "1")
            {
                if (!string.IsNullOrEmpty(KSCMS.S("TxtSuCaiID")))
                {

                    #region 素材类型
                    using (DataTable dt = DataFactory.GetDataTable("select top 1 * from KS_WeixinPigmsg where id=" + KSCMS.S("TxtSuCaiID")))
                    {
                        if (dt.Rows.Count > 0)
                        {
                            string articlesJson = GetArticlesJsonStr(ks_weixin.IsExistAccess_Token(1), dt);
                            // KSCMS.W(articlesJson+"<hr>");
                            string newsMsg = UploadNews(ks_weixin.IsExistAccess_Token(1), articlesJson);
                            //KSCMS.W(newsMsg+"<hr>");
                            string newsid = ks_weixin.GetJsonValue(newsMsg, "media_id");
                            //KSCMS.W(newsid + "<hr>");

                            sb = "{\"filter\":{\"is_to_all\":false,\"group_id\":\"" + KSCMS.S("groupname").Trim() +
                         "\"},\"mpnews\":{\"media_id\":\"" + newsid +
                       "\"},\"msgtype\":\"mpnews\"}";
                        }
                    }
                    #endregion
                }
            }
            else if (KSCMS.S("sendtype") == "2")
            {
                if (!string.IsNullOrEmpty(KSCMS.S("TxtTuWenID")))
                {
                    #region 图文

                    string[] tuwenid = string.Concat(KSCMS.S("TxtTuWenID"), "§").Split('§');

                    using (DataTable dt2 = DataFactory.GetDataTable("select Top 1 * from KS_EnterpriseNews where id=" + tuwenid[2] + ""))
                    {
                        if (dt2.Rows.Count > 0)
                        {
                            string xitongJson = GetXiTongJsonStr(ks_weixin.IsExistAccess_Token(1), dt2,1);
                            string newsMsg = UploadNews(ks_weixin.IsExistAccess_Token(1), xitongJson);
                            string newsid = ks_weixin.GetJsonValue(newsMsg, "media_id");
                            sb = "{\"filter\":{\"is_to_all\":false,\"group_id\":\"" + KSCMS.S("groupname").Trim() +
                       "\"},\"mpnews\":{\"media_id\":\"" + newsid +
                     "\"},\"msgtype\":\"mpnews\"}";

                        }
                    }
                    #endregion
                }
            }
            else if (KSCMS.S("sendtype") == "4")
            {
                if (!string.IsNullOrEmpty(KSCMS.S("TxtCourseID")))
                {
                    #region 课程
                    string[] Courseid = string.Concat(KSCMS.S("TxtCourseID"), "§").Split('§');
                    string tableName = "KS_Course";
                    if (Utils.StrToInt(KSCMS.S("costype")) == 0) {
                        tableName = "KS_CourseFace";
                    }
                    using (DataTable dt3 = DataFactory.GetDataTable("select Top 1 * from " + tableName + " where courseid=" + Courseid[2] + ""))
                    {
                        if (dt3.Rows.Count > 0)
                        {
                            string xitongJson = GetXiTongJsonStr(ks_weixin.IsExistAccess_Token(1), dt3,2);
                            string newsMsg = UploadNews(ks_weixin.IsExistAccess_Token(1), xitongJson);
                            string newsid = ks_weixin.GetJsonValue(newsMsg, "media_id");
                            sb = "{\"filter\":{\"is_to_all\":false,\"group_id\":\"" + KSCMS.S("groupname").Trim() +
                          "\"},\"mpnews\":{\"media_id\":\"" + newsid +
                        "\"},\"msgtype\":\"mpnews\"}";

                        }
                    }
                    #endregion
                }
            }
            #endregion
        }
        return sb;
    }
    /// <summary>
    /// 拼接系统的Json字符串
    /// </summary>
    public static string GetXiTongJsonStr(string access_token, DataTable dt,int passType=0)
    {
        StringBuilder sbArticlesJson = new StringBuilder();
        sbArticlesJson.Append("{\"articles\":[");
        DataRow dr = dt.Rows[0];
        #region 得到media_id
        bool isRemote = false;
        string pic = string.Empty;
        if (passType == 0)
        {
            pic = (dr["DefaultPic"].ToString() == string.Empty ? "/SysImg/nopic.gif" : dr["DefaultPic"].ToString());
        }
        else if (passType == 1)
        {
            pic = (dr["photo"].ToString() == string.Empty ? "/SysImg/nopic.gif" : dr["photo"].ToString());
        }
        else
        {
            pic = (dr["photourl"].ToString() == string.Empty ? "/SysImg/nopic.gif" : dr["photourl"].ToString());
        }

        if (pic.ToLower().StartsWith("http://"))
        {
            string filename = Utils.RndNum(5) + DateTime.Now.ToFileTimeUtc() + pic.Substring(pic.LastIndexOf("."));
            string SavePath = MyCache.GetCacheConfig(0) + MyCache.GetCacheConfig(22) + "/temp/" + filename;
            Kesion.Publics.UtilsFile.CreateFolders(MyCache.GetCacheConfig(0) + MyCache.GetCacheConfig(22) + "/temp/");

            if (Kesion.APPCode.Public.SaveRemoteFile(pic, SavePath).Equals(true))
            {
                isRemote = true;
                pic = SavePath;
            }
        }
        string msg = UploadMedia(ks_weixin.IsExistAccess_Token(1), "image", Utils.GetMapPath(pic)); // 上图片返回媒体ID
        string media_id = ks_weixin.GetJsonValue(msg, "media_id");
        if (isRemote)
        {
            Kesion.Publics.UtilsFile.DelFile(pic);
        }
        #endregion
        #region 内容图片的链接
        string content = string.Empty;
        if (passType == 1)
        {
            content = dr["content"].ToString() == string.Empty ? dr["intro"].ToString() : dr["content"].ToString();
        }
        else
        {
            content = dr["intro"].ToString();
        }
        if (passType==0)
        {
            int BasicType = Utils.StrToInt(DataFactory.GetOnlyValue("select top 1 BasicType from KS_Model  where ChannelID=" + dr["ChannelID"].ToString()));
            if (BasicType == 2)
            {
                string[] ImgArr = Regex.Split(content, @"[|]{3}");
                int TotalPage = ImgArr.Length;
                string bigImgSrc = string.Empty;
                string thumbList = string.Empty;
                string defaultImageSrc = string.Empty;
                string defaultImageIntro = string.Empty;
                string introList = string.Empty;
                for (int n = 0; n < TotalPage; n++)
                {
                    introList += ImgArr[n].Split('|')[0].Trim() + "|";
                    bigImgSrc += ImgArr[n].Split('|')[1].Trim().Replace("\n", string.Empty) + "|";
                    if (n == 0)
                    {
                        thumbList = string.Format(@"<li><a id=""t{0}"" class=""currthumb"" href=""javascript:void(0)"" onclick=""showImg({0});""><img src=""{1}"" border=""0""/></a></li>", n, ImgArr[n].Split('|')[2]);
                    }
                    else
                    {
                        thumbList += string.Format(@"<li><a id=""t{0}"" class=""normalthumb"" href=""javascript:void(0)"" onclick=""showImg({0});""><img src=""{1}"" border=""0""/></a></li>", n, ImgArr[n].Split('|')[2]);
                    }
                }
                content = thumbList;
                ArrayList al1 = KSCMS.GetImgSrcArr(content);
                foreach (object o in al1)
                {
                    string pic1 = o.ToString();
                    string oldPic1 = pic1;
                    bool isRemote1 = ks_weixin.ProcessImage(ref pic1);
                    string msg1 = UploadUrl(ks_weixin.IsExistAccess_Token(1), Utils.GetMapPath(pic1));
                    string newpic1 = ks_weixin.GetJsonValue(msg1, "url");
                    content = Utils.ReplaceString(content, oldPic1, newpic1, true);
                    if (isRemote1)
                    {
                        Kesion.Publics.UtilsFile.DelFile(pic1);
                    }
                }
            }
            else
            {
                ArrayList al1 = KSCMS.GetImgSrcArr(content);
                foreach (object o in al1)
                {
                    string pic1 = o.ToString();
                    string oldPic1 = pic1;
                    bool isRemote1 = ks_weixin.ProcessImage(ref pic1);
                    string msg1 = UploadUrl(ks_weixin.IsExistAccess_Token(1), Utils.GetMapPath(pic1));
                    string newpic1 = ks_weixin.GetJsonValue(msg1, "url");
                    content = Utils.ReplaceString(content, oldPic1, newpic1, true);
                    if (isRemote1)
                    {
                        Kesion.Publics.UtilsFile.DelFile(pic1);
                    }
                }
            }
        }
        content = Utils.ReplaceString(content, @"""", @"\""", true);
        content = Utils.ReplaceString(content, "\n", "<br/>", true);
        #endregion
        string author = dr["username"].ToString() == string.Empty ? "官方" : dr["username"].ToString();
        string intro = dr["intro"].ToString();
        sbArticlesJson.Append("{");
        sbArticlesJson.Append("\"thumb_media_id\":\"" + media_id + "\",");
        sbArticlesJson.Append("\"author\":\"" + author + "\",");
        if (passType == 2)
        {
            sbArticlesJson.Append("\"title\":\"" + dr["name"].ToString() + "\",");
        }
        else
        {
            sbArticlesJson.Append("\"title\":\"" + dr["title"].ToString() + "\",");
        }
        string url = string.Empty;
        if (passType == 1)
        {
            url = Utils.GetRootPath() + BasicField.GetEplistContentUrl(Utils.StrToInt(dr["SchoolID"]), "action-news,archive-archive,paramID-" + dr["id"]);
        }
        else if (passType == 2)
        {
            url = GetUrl(Utils.StrToInt(dr["courseid"].ToString()),Utils.StrToInt(dr["teachway"].ToString()));
        }
        sbArticlesJson.Append("\"content_source_url\":\"" + url + "\",");
        sbArticlesJson.Append("\"content\":\"" + content + "\",");
        sbArticlesJson.Append("\"digest\":\"" + FormatIntro(intro) + "\",");
        sbArticlesJson.Append("\"show_cover_pic\":\"0\"}");
        sbArticlesJson.Append("]}");

        return sbArticlesJson.ToString();
    }
    public static string GetUrl(int courseid, int costype)
    {
        string value = "courseview";
        if (costype == 0)
        {
            value = "faceview";
        }
        else if (costype == 5)
        {
            value = "liveview";
        }
        return BasicField.GetRewriteUrl(value, courseid);
    }
    /// <summary>
    /// 上传媒体返回媒体ID
    /// </summary>
    public static string UploadMedia(string access_token, string type, string path)
    {
        string url = string.Format("http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token={0}&type={1}", access_token, type);  //qf
        return ks_weixin.HttpUploadFile(url, path, "file");

    }
    /// <summary>
    /// 过滤简介
    /// </summary>
    /// <param name="intro"></param>
    /// <returns></returns>
    private static string FormatIntro(string intro)
    {
        if (string.IsNullOrEmpty(intro))
        {
            return string.Empty;
        }
        else
        {
            string str = Utils.RemoveHtml(intro);
            str = Utils.ReplaceString(str, @"""", @"\""", true);
            str = Utils.ReplaceString(str, @"\n", string.Empty, true);
            str = Utils.CutStr(str, 50);
            return str;
        }
    }
    /// <summary>
    /// 返回Url
    /// </summary>
    public static string UploadUrl(string access_token, string path)
    {
        string url = string.Format("http://file.api.weixin.qq.com/cgi-bin/media/uploadimg?access_token={0}", access_token);
        return ks_weixin.HttpUploadFile(url, path, "media");
    }
    /// <summary>
    /// 上传图文消息素材返回media_id
    /// </summary>
    public static string UploadNews(string access_token, string postData)
    {
        string str = ks_weixin.PostUrl(string.Format("https://api.weixin.qq.com/cgi-bin/media/uploadnews?access_token={0}", access_token), postData);
        if (str.IndexOf("invalid") != 1)
        {
        }
        return str;
    }
    /// <summary>
    /// 拼接图文消息素材Json字符串
    /// </summary>
    public static string GetArticlesJsonStr(string access_token, DataTable dt)
    {
        StringBuilder sbArticlesJson = new StringBuilder();
        sbArticlesJson.Append("{\"articles\":[");
        foreach (DataRow dr in dt.Rows)
        {
            #region 得到media_id
            bool isRemote = false;
            string pic = dr["PicUrl"].ToString();
            if (string.IsNullOrEmpty(pic))
            {
                pic =Utils.GetRootPath()+"/SysImg/nopic.gif";
            }
            if (pic.ToLower().StartsWith("http://")||pic.ToLower().StartsWith("https://"))
            {
                string filename = Utils.RndNum(5) + DateTime.Now.ToFileTimeUtc() + pic.Substring(pic.LastIndexOf("."));
                string SavePath = MyCache.GetCacheConfig(0) + MyCache.GetCacheConfig(22) + "/temp/" + filename;
                Kesion.Publics.UtilsFile.CreateFolders(MyCache.GetCacheConfig(0) + MyCache.GetCacheConfig(22) + "/temp/");
                if (Kesion.APPCode.Public.SaveRemoteFile(pic, SavePath).Equals(true))
                {
                    isRemote = true;
                    pic = SavePath;
                }
            }

            string msg = UploadMedia(ks_weixin.IsExistAccess_Token(1), "image", Utils.GetMapPath(pic)); // 上图片返回媒体ID

            string media_id = ks_weixin.GetJsonValue(msg, "media_id");
            if (isRemote)
            {
                Kesion.Publics.UtilsFile.DelFile(pic);
            }
            #endregion
            #region 内容图片的链接
            string content = dr["content"].ToString();
            ArrayList al1 = KSCMS.GetImgSrcArr(content);
            foreach (object o in al1)
            {
                string pic1 = o.ToString();
                string oldPic1 = pic1;
                bool isRemote1 = ks_weixin.ProcessImage(ref pic1);
                if (pic1.IndexOf("http") == -1)
                {
                    string msg1 = UploadUrl(ks_weixin.IsExistAccess_Token(1), Utils.GetMapPath(pic1));
                    string newpic1 = ks_weixin.GetJsonValue(msg1, "url");
                    content = Utils.ReplaceString(content, oldPic1, newpic1, true);
                    if (isRemote1)
                    {
                        Kesion.Publics.UtilsFile.DelFile(pic1);
                    }
                }
            }
            content = Utils.ReplaceString(content, @"""", @"\""", true);
            content = Utils.ReplaceString(content, "\n", "<br/>", true);
            #endregion
            sbArticlesJson.Append("{");
            sbArticlesJson.Append("\"thumb_media_id\":\"" + media_id + "\",");
            sbArticlesJson.Append("\"author\":\"" + dr["AddPeople"].ToString() + "\",");
            sbArticlesJson.Append("\"title\":\"" + dr["Title"].ToString() + "\",");
            sbArticlesJson.Append("\"content_source_url\":\"" + dr["Url"].ToString() + "\",");
            sbArticlesJson.Append("\"content\":\"" + content + "\",");
            sbArticlesJson.Append("\"digest\":\"" + FormatIntro(dr["Info"].ToString()) + "\",");
            sbArticlesJson.Append("\"show_cover_pic\":\"0\"}");
            {
                #region 子条文
                using (DataTable dt2 = DataFactory.GetDataTable("select * from KS_WeixinPigmsg where ParentID=" + dr["id"].ToString()))
                {
                    foreach (DataRow dr2 in dt2.Rows)
                    {
                        #region 得到media_id
                        bool isRemote2 = false;
                        string pic2 = dr2["PicUrl"].ToString();
                        if (pic2.ToLower().StartsWith("http://") || pic2.ToLower().StartsWith("https://"))
                        {
                            string filename2 = Utils.RndNum(5) + DateTime.Now.ToFileTimeUtc() + pic2.Substring(pic2.LastIndexOf("."));
                            string SavePath2 = MyCache.GetCacheConfig(0) + MyCache.GetCacheConfig(22) + "/temp/" + filename2;
                            Kesion.Publics.UtilsFile.CreateFolders(MyCache.GetCacheConfig(0) + MyCache.GetCacheConfig(22) + "/temp/");
                            if (Kesion.APPCode.Public.SaveRemoteFile(pic2, SavePath2).Equals(true))
                            {
                                isRemote2 = true;
                                pic2 = SavePath2;
                            }
                        }
                        string msg2 = UploadMedia(ks_weixin.IsExistAccess_Token(1), "image", Utils.GetMapPath(pic2)); // 上图片返回媒体ID
                        string media_id2 = ks_weixin.GetJsonValue(msg2, "media_id");
                        if (isRemote2)
                        {
                            Kesion.Publics.UtilsFile.DelFile(pic2);
                        }
                        #endregion
                        #region 内容图片的链接
                        string content2 = dr2["content"].ToString();
                        ArrayList al3 = new ArrayList();
                        al3 = KSCMS.GetImgSrcArr(content2);

                        if (al3 != null)
                        {
                            foreach (string o in al3)
                            {

                                #region 取出内容的图片链接
                                string pic3 = o.ToString();
                                string oldPic3 = pic3;
                                bool isRemote3 = ks_weixin.ProcessImage(ref pic3);

                                string msg3 = string.Empty;
                                if (pic3.IndexOf("http") == -1)
                                {
                                    msg3 = UploadUrl(ks_weixin.IsExistAccess_Token(1), Utils.GetMapPath(pic3));
                                    string newpic3 = ks_weixin.GetJsonValue(msg3, "url");
                                    content2 = Utils.ReplaceString(content2, oldPic3, newpic3, true);
                                }
                                if (isRemote3)
                                {
                                    Kesion.Publics.UtilsFile.DelFile(pic3);
                                }
                                #endregion
                            }
                        }
                        content2 = Utils.ReplaceString(content2, @"""", @"\""", true);
                        content2 = Utils.ReplaceString(content2, "\n", "<br/>", true);
                        #endregion
                        if (!string.IsNullOrEmpty(media_id2))
                        {
                            sbArticlesJson.Append(",{");
                            sbArticlesJson.Append("\"thumb_media_id\":\"" + media_id2 + "\",");
                            sbArticlesJson.Append("\"author\":\"" + dr2["AddPeople"].ToString() + "\",");
                            sbArticlesJson.Append("\"title\":\"" + dr2["Title"].ToString() + "\",");
                            sbArticlesJson.Append("\"content_source_url\":\"" + dr2["Url"].ToString() + "\",");
                            sbArticlesJson.Append("\"content\":\"" + content2 + "\",");
                            sbArticlesJson.Append("\"digest\":\"" + FormatIntro(dr2["Info"].ToString()) + "\",");
                            sbArticlesJson.Append("\"show_cover_pic\":\"0\"}");
                        }
                    }
                }
                #endregion
            }
        }
        sbArticlesJson.Append("]}");
        return sbArticlesJson.ToString();
    }
</script>
<%
	if (!isLoadPage) return;
%>
 <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_SendGroup") %>" id="myForm">
 <input type="hidden" value="" name="action" id="action" />
 <div class="console_body">
		<script>
			jQuery(document).ready(function () {
				var sex = $("#drsex").val();
				var type = $("#drType").val();
				DoType(type);
				// DoSendType();
			});
			function DoType(id) {
				$.ajax({
					url: "/plus/course/wxajax.aspx?action=getgroup&type=" + id,
					context: document.body,
					type: "GET",
					success: function (data) {
						$("#getsex").html(data);
					}
				});
			}
		</script>
		<script>
			$(function () {
				aa(<%=sendtype%>);
				$(".group_send_box ul li").click(function () {
					var k = $(this).index();
					aa(k);
				});
			});
			function aa(k) {
				$(".group_send_box ul li").each(function (index, domEle) {
					$(this).attr("class", "");
				});
				$(".group_send_box ul li").each(function (index, domEle) {
					if (k == index) {
						$("#sendtype").val(k);
						if (k == 0) {
						} else if (k == 1) {

						} else if (k == 2) {
						}
						$(this).attr("class", "change");
					}
				});
			}
			function sendCheck() {
				$("#action").val("send");
				$("#aspnetForm").attr("target", "hidframe");
				$("#setbtn").attr("value", "发送中...");
				$("#setbtn").post();
			}
			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>
		<%if (__info.Panel1){ %>
		<div ID="Panel1" >
			<iframe src="about:blank" style="display: none" name="hidframe" id="hidframe"></iframe>
			<div class="openKey" style="margin: 10px 20px 10px 20px; font-weight: normal; line-height: 30px;">
				群发消息规则：根据微信官方规定，订阅号每天可以群发1条信息，服务号每月可以群发4条信息，发送大于规定的信息数，用户将接收不到！
         <p class="tishi_send_group">
			 注意：群发对象是按全部用户：订阅号不可用，服务号认证后可用；
         群发对象是按分组选择：订阅号和服务号认证后均可用。
		 </p>
			</div>
			<input id="TxtTuWenID" type="hidden" name="TxtTuWenID" />
			<input id="TxtCourseID" type="hidden" name="TxtCourseID" />
			<textarea id="ShowTxtTuWen0" style="width: 300px; height: 200px; display: none"></textarea>
			<textarea id="ShowTxtCourse0" style="width: 300px; height: 200px; display: none"></textarea>
			<input id="TxtSuCaiID" type="hidden" name="TxtSuCaiID" />
			<textarea id="ShowTxtSuCai0" style="width: 300px; height: 200px; display: none"></textarea>
			<input type="hidden" id="sendtype" name="sendtype" value="<%=sendtype %>" />
			<input id="CosType" type="hidden" value="0" name="CosType" />
			<div class="group_send_dx">

				<a href="<%=BasicField.GetUserUrl("wx/wx_SendGroup","do-look") %>" class="chack_recode">查看群发记录</a>

				群发对象：
                    
			<span>
				<select id="drType" name="drType" onchange="DoType(this.value)">

					<%if (WeiXinType == 1||WeiXinType == 2)
	   { %>
					<option value="1">按全部用户</option>
					<option value="2">按分组选择</option>
					<%}
	   else if (WeiXinType == 0)
	   {%>
					<option value="2">按分组选择</option>
					<% }%>
				</select>
			</span>
				<span class="txt" id="getsex"></span>
			</div>
			<div class="group_send_box">
				<ul class="group_send_ul">
					<li class="change"><a href="javascript:;" onclick="$('#mybox1').show();$('#mybox2').hide();">
						<i class="sm_tab wz"></i>文字 </a></li>
					<li>
						<a href="<%=BasicField.GetUserUrl("wx/wx_SuCaiList","frame-no,action-qunfa,qunfaId-"+QunFaID+"") %>" onclick="$('#mybox2').show();$('#mybox1').hide();" target="iframemain0"><i class="sm_tab sc_tw"></i>素材</a></li>
					<li>
						<a href="<%=BasicField.GetUserUrl("wx/wx_TuWenList","frame-no,action-qunfa,qunfaId-"+QunFaID+"") %> " onclick="$('#mybox2').show();$('#mybox1').hide();" target="iframemain0"><i class="sm_tab tw2"></i>图文</a></li>
		<li></li>
					<li>
						<a href="<%=BasicField.GetUserUrl("wx/wx_CourseList","frame-no,action-qunfa,qunfaId-"+QunFaID+"") %>" onclick="$('#mybox2').show();$('#mybox1').hide();" target="iframemain0"><i class="sm_tab sp"></i>课程</a>

					</li>
				
					<div class="clear"></div>
				</ul>
				<div class="group_send_con">
					<div class="group_sc" id="mybox1" style="display: block">
						<div><textarea name="TxtContent" rows="2" cols="20" id="TxtContent" style="height: 200px; width:100%; background: #fff; background-color: #fff;border: 0 !important;"><%=__info.TxtContent%></textarea></div>
					</div>
					<div class="group_sc" id="mybox2" style="display: none">
						<iframe class="editArea-ifrm" frameborder="no" border="0" src="<%=BasicField.GetUserUrl("wx/wx_SuCaiList","frame-no,action-qunfa,qunfaId-"+QunFaID+"") %>" style="width: 100%;" name="iframemain0" id="iframemain0"></iframe>
					</div>
				</div>
			</div>
			<div class="group_send_bottom">
				<%=GetQunFaMessage(SendCount,WeiXinType) %>
				<span class="group_send_botton">
					 <input type="submit" name="setbtn" value="群发" onclick="return (sendCheck());" id="setbtn" class="send_button" style="display:<%=__info.setbtn%>" />
				</span>

			</div>
		</div>
		<%}else{ %>
		<div ID="Panel2">
			<div class="groupmanage qf">
				<table style="width: 98%; margin: 10px 1%; border: 1px solid #eee; text-align: center;" cellpadding="0" cellspacing="0">
					<tr class="RepeaterGroup">
								<th width="5%">序号</th>
								<th width="10%">类型</th>
								<th width="20%">标题</th>
								<th width="20%">群发对象</th>
								<th width="5%">状态</th>
								<th width="15%">消息ID</th>
								<th width="15%">群发日期</th>
							</tr>
				<%
		  int pagesize = 20;
            int recordcount, pagecount;
			 int CurrPage = new BasicField().GetCurrPage;
            string sqlpame = " where typeFlag="+new TemporaryVar().GroupID+" and userid="+new TemporaryVar().UserID+" ";
			using (DataTable dt = DataFactory.GetPage("*", "KS_WeiXinQunFA " + sqlpame, "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 style='background-color: " + ((i % 2 == 0) ? "#fff" : "#fff") + "'><td>" + (pagesize * (CurrPage - 1) + i) + "</td>" +
								"<td>" + GetSendType(dr["sendtype"].ToString()) + "</td>" +
								"<td>" + GetSendContent(dr["content"].ToString(), dr["SuCaiID"].ToString(), dr["tuwenid"].ToString(), dr["courseid"].ToString(), dr["sendtype"].ToString(),Utils.StrToInt(dr["costype"].ToString())) + "</td>" +
								"<td>" + dr["MassObject"].ToString() + "</td><td style=\"color: red;\">" + dr["massStatus"].ToString() + "</td>" +
								"<td>" + dr["MassMessageID"].ToString() + " </td><td>" + dr["AddDate"].ToString() + "</td></tr>");
						i++;
					}
				}
				else
				{
					KSCMS.W("<tr width=\"100%\"><td class=\"empty\" colspan=\"9\" style=\"padding: 10px; text-align: center;\">暂无记录</td></tr>");
				}
			}
		 %>
				</table>
			</div>
            <div class="fy_box">
			  <%
			  #region 分页
			  string PageStr = "[KS:PageStr1]";
			  BasicField.ReplaceFilterPage(ref PageStr, CurrPage, CurrPage, pagecount, recordcount);
			  KSCMS.W(PageStr);
			  #endregion
		   %>
		   </div>
           <div class="clear"></div>
		</div>
		<%} %>
	</div>
 </form>
 </div>