<%@ Control Language="C#" %>
<%@ Import Namespace="Kesion.Publics" %>
<%@ Import Namespace="Kesion.BLL" %>
<%@ Import Namespace="Kesion.Cache" %>
<%@ Import Namespace="Kesion.Components" %>
<%@ Import Namespace="Kesion.HtmlTags" %>
<%@ Import Namespace="Kesion.APPCode" %>
<%@ Import Namespace="Kesion.Weixin" %>
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="Newtonsoft.Json.Linq" %>
<%@ Import Namespace="System.Xml" %>

<script runat="server" type="text/C#">
    dynamic __user = HttpContext.Current.Items["user"];                //初始化用户信息，
    private static dynamic __info = new System.Dynamic.ExpandoObject();   //初始化当前页信息
    bool isLoadPage = true;  //定义页面是否加载
    public string AuthUrl = string.Empty;
public string btnvalue="前往授权页面";
    protected void Page_Load(object sender, EventArgs e)
    {
        switch (KSCMS.S("action").ToString())
        {
            case "close"://取消管理的操作信息
                CloseManage();
                break;
        }

        if (!DataFactory.Exists("KS_WeixinUser", "userId=" + new TemporaryVar().UserID))
        {
            Initial();
        }
        else
        {
            btnvalue="已授权";
        }
    }
    /// <summary>
    /// 初始化信息
    /// </summary>
    private void Initial()
    {
        EpConfig EnterPrise = new EpConfig();

        //第三方开发平台数据
        if (Utils.StrToInt(EnterPrise.GetEpConfig(29)) == 1)
        {
            string appId = EnterPrise.GetEpConfig(30);
            string accessToken = string.Empty;//component_access_token
            string preauthCode = string.Empty;//pre_auth_code
            string rootPath = Utils.GetRootPath();
            string url1 = "";
            string FilePath = HttpContext.Current.Server.MapPath("~/Config/cache/WX");
            string FileName = "wxcomponentaccesstoken.cache";
            string Path = FilePath + "\\" + FileName;
            FileInfo file = new FileInfo(Path);
            if (File.Exists(Path) && file.LastWriteTime.AddHours(1.8) > DateTime.Now)
            {
                StreamReader sr = new StreamReader(Path, Encoding.Default);
                String line;
                string jsontoken = string.Empty;
                while ((line = sr.ReadLine()) != null)
                {
                    jsontoken += line.ToString();
                }
                sr.Close();
                sr.Dispose();
                JObject json1 = JObject.Parse(jsontoken);
                accessToken = json1["component_access_token"].ToString();
                //第三步 获取pre_auth_code
                if (!string.IsNullOrEmpty(accessToken))
                {
                    Session["component_access_token"] = accessToken;
                    url1 = "https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token=" + accessToken + "";
                    JObject json2 = JObject.Parse(DoPost(url1, "{\"component_appid\":\"" + appId + "\" }"));
                    preauthCode = json2["pre_auth_code"].ToString();
                    AuthUrl = "https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid=" + appId + "&pre_auth_code=" + preauthCode + "&redirect_uri=" + rootPath + "/Plus/Pay/WX/EPNotify.aspx?do=auth&userid=" + new TemporaryVar().UserID + "";
                }
            }
        }
    }
    /// <summary>
    /// 请求获取参数信息
    /// </summary>
    /// <param name="url">请求路径</param>
    /// <param name="data">传递的参数</param>
    /// <returns></returns>
    public string DoPost(string url,string data)
    {
        try
        {
            byte[] byteArray = Encoding.UTF8.GetBytes(data); // 转化
            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.Default);
            string srt = sr.ReadToEnd();
            return srt.ToString();
        }
        catch
        {
            return "";
        }
    }

    

    /// <summary>
    /// 关闭管理信息
    /// </summary>
    public void CloseManage()
    {
        try {
            //清理相关记录信息
            DataFactory.ExecuteNonQuery("delete from  KS_WeixinUser where UserName='" + __user.UserName + "' ");
            //清理粉丝列表信息
            DataFactory.ExecuteNonQuery("delete from KS_WeixinOpenuser where schoolid=" + new TemporaryVar().UserID);
            //清理机构微信模板信息
            DataFactory.ExecuteNonQuery("delete froM KS_WeixinEpTemplate where UserID=" + new TemporaryVar().UserID);
        } catch (Exception ex) {
           // Utils.WriteLog("机构微信报错信息："+ex);
        }
        Msg.Alert("取消管理成功",BasicField.GetUserUrl("wx/wx_portset"));
    }


</script>
<%
	if (!isLoadPage) return;
%>
<style>
    .search_group a {
    background: #5bc0de;
    float: right;
    margin: 0 0 0 10px;
    color: #fff;
    border-radius: 3px;
    padding: 0 20px;
    display: block;
    height: 32px;
    line-height: 32px;
}

</style>
<link href="/SysImg/teacher/css/newswx.css" rel="stylesheet" />
<div class="t_tybox" style="height:120px">
    <div class="tytitle"><h4>微信接口设置</h4></div>

   
    <div class="search_group" >


        <%  int epstatus = 0;
            string epimg = "";
            string epimg2 = "";
            using (var dr = DataFactory.ExecuteReader("select top 1 * from  KS_WeixinUser where username='" + __user.UserName + "'"))
            {
                while (dr.Read())
                {
                    epstatus = 1;
                    epimg = dr["url"].ToString();
                    epimg2 = dr["ercodeimg"].ToString();
                }
                dr.Close();
            }%>
        <%if (epstatus == 1) { %>
            <table width="100%" cellpadding="0" cellspacing="0" border="0" class="wchatInfo">
            <tr>
                <td class="wchatTit">管理的公众号信息：</td>
                <td><div class="wchatLogoImg"><img src="<%=epimg %>" onerror="this.src='/sysimg/nopic.gif'"/></div></td>
            </tr>
            <tr>
                <td class="wchatTit">公众号二维码信息：</td>
                <td class="wchatCode"><div class="wchatImg"><img src="<%=epimg2 %>" onerror="this.src='/sysimg/nopic.gif'"/></div></td>
            </tr>
            <tr>
                <td class="wchatTit"  colspan="2"><a href="<%=BasicField.GetUserUrl("wx/wx_portset","action-close") %>"></a>取消管理</td>
            </tr>
        </table>
        <%} else { %>

        <%if (!string.IsNullOrEmpty(AuthUrl))
                { %>
        <a href="<%= AuthUrl %>" target="_blank"><%=btnvalue%></a>
        <%}
                else
                { %> 
        请联系管理人员到总站后台设置“第三方公众号配置” 信息。
        <%} %>
        <%} %>
    </div>
	
</div>