using System;
using System.Collections.Generic;
using System.Data;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using EKETEAM.FrameWork;
using EKETEAM.Data;
using EKETEAM.Tencent.WxWork;
using System.Web.Caching;
using System.Net;
using System.IO;
using System.Text;
using LitJson;


namespace eFrameWork.DDing
{
    public partial class _Default1 : System.Web.UI.Page
    {
        string corpId = "dinghtw5mwwwy8owozem";
        string corpSecret = "ZWfotALxz2wta8fyo1VYxfveqqkPTFq_vavdjzN4dK061CBdTWcHIt3xfMPVc0vo";

        string AgentId = "2319929138";
        protected void Page_Load(object sender, EventArgs e)
        {

            Send();
            return;
            if ( Request.QueryString["code"]!=null)
            {
                string code = Request.QueryString["code"].ToString();

                string accessToken = getAccesstoken();
                string userid = GetUserId(accessToken, code);
                string userinfo = GetUserDetail(accessToken, userid);
                eBase.Writeln(userinfo);
                Response.End();
            }
            //Response.Write(GetJsApiTicket());
           // Response.End();
        }
        public string getAccesstoken()
        {
            string CacheName = eBase.DingTalkAccount.getValue("CorpID") + "_" + eBase.DingTalkAccount.getValue("AgentId") + "_Accesstoken";
            string tmp = (string)HttpRuntime.Cache.Get(CacheName);
            if (tmp == null)
            {
                string url = string.Format("https://oapi.dingtalk.com/gettoken?corpid={0}&corpsecret={1}", eBase.DingTalkAccount.getValue("CorpID"), eBase.DingTalkAccount.getValue("AgentId"));
                string result = eBase.getRequest(url);
                //{"errcode":0,"access_token":"8558d6dc78533024b47310ad3ba410bc","errmsg":"ok","expires_in":7200}
                //{"errcode":40089,"errmsg":"不合法的corpId或corpSecret"}
                JsonData json = result.ToJsonData();
                tmp = json.getValue("access_token");
                HttpRuntime.Cache.Insert(CacheName, tmp, null, DateTime.Now.AddSeconds(7000), Cache.NoSlidingExpiration);
            }
            return tmp;
        }
        public string getAccesstoken2()
        {
            string CacheName = eBase.DingTalkAccount.getValue("CorpID") + "_" + eBase.DingTalkAccount.getValue("AppKey") + "_Accesstoken";
            string tmp = (string)HttpRuntime.Cache.Get(CacheName);
            if (tmp == null)
            {
                string url = string.Format("https://oapi.dingtalk.com/gettoken?appkey={0}&appsecret={1}", eBase.DingTalkAccount.getValue("AppKey"), eBase.DingTalkAccount.getValue("AppSecret"));
                string result = eBase.getRequest(url);
                //{"errcode":0,"access_token":"8558d6dc78533024b47310ad3ba410bc","errmsg":"ok","expires_in":7200}
                //{"errcode":40089,"errmsg":"不合法的corpId或corpSecret"}
                JsonData json = result.ToJsonData();
                tmp = json.getValue("access_token");
                HttpRuntime.Cache.Insert(CacheName, tmp, null, DateTime.Now.AddSeconds(7000), Cache.NoSlidingExpiration);
            }
            return tmp;
        }
        public string GetJsApiTicket()
        {
            string accessToken = getAccesstoken();
            string url = string.Format("https://oapi.dingtalk.com/get_jsapi_ticket?access_token={0}", accessToken);
            string result = eBase.getRequest(url);
            //{"errcode":0,"errmsg":"ok","ticket":"l1nDcfgkfqh6ZIEyHn1ecFn4UHDdo8EJqMMsABSdWdS6baweQI9Sl0uujp076WXhIecv0Who81Zn4hYMOgiEpd","expires_in":7200}
            //eBase.AppendLog(result);
            JsonData json = result.ToJsonData();
            string tmp = json.getValue("ticket");
            return tmp;
        }
        public long GetTimeStamp()
        {
            //TimeSpan ts = DateTime.UtcNow - new DateTime(, , , , , , );
            TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
            return Convert.ToInt64(ts.TotalSeconds);
        }
        public string GetUserId(string accessToken, string code)
        {
            string url = string.Format("https://oapi.dingtalk.com/user/getuserinfo?access_token={0}&code={1}", accessToken, code);
            string result = eBase.getRequest(url);
            //{"errcode":0,"sys_level":2,"is_sys":true,"name":"庹忠东","errmsg":"ok","deviceId":"a0d246d9c648f91fb3cf3b7e7d668cf8","userid":"013725223624084149"}

            //eBase.AppendLog(result);
            JsonData json = result.ToJsonData();
            string tmp = json.getValue("userid");
            return tmp;
        }
        public string GetUserDetailJson(string accessToken, string userId)
        {
            string url = string.Format("https://oapi.dingtalk.com/user/get?access_token={0}&userid={1}", accessToken, userId);
            string result = eBase.getRequest(url);
            //{"errcode":60011,"errmsg":"没有调用该接口的权限，接口权限申请参考：https://open.dingtalk.com/document/orgapp-server/add-api-permission"}

            //身份验证 - 通讯录个人信息读权限
            //{"errcode":0,"exclusiveAccount":false,"unionid":"E5diSWXRceqMCaljo19xKzgiEiE","roles":[{"id":1986667312,"name":"子管理员","groupName":"默认","type":102},{"id":1986667313,"name":"负责人","groupName":"默认","type":103},{"id":1986667320,"name":"IT","groupName":"职务","type":0}],"userid":"013725223624084149","isLeaderInDepts":"{1:false}","isBoss":true,"isSenior":false,"department":[1],"orderInDepts":"{1:176245508045154512}","errmsg":"ok","active":true,"avatar":"https://static-legacy.dingtalk.com/media/lADPD3lG17hhp5vNBJTNBJI_1170_1172.jpg","isAdmin":true,"tags":{},"isHide":false,"name":"庹忠东","position":"IT主管","realAuthed":false}

            //eBase.AppendLog(result);
            return result;
        }
        
        public string GetUserDetail(string accessToken, string userId)
        {
            string url = string.Format("https://oapi.dingtalk.com/user/get?access_token={0}&userid={1}", accessToken, userId);
            string result = eBase.getRequest(url);
            //{"errcode":0,"exclusiveAccount":false,"unionid":"E5diSWXRceqMCaljo19xKzgiEiE","roles":[{"id":1986667312,"name":"子管理员","groupName":"默认","type":102},{"id":1986667313,"name":"负责人","groupName":"默认","type":103},{"id":1986667320,"name":"IT","groupName":"职务","type":0}],"userid":"013725223624084149","isLeaderInDepts":"{1:false}","isBoss":true,"isSenior":false,"department":[1],"orderInDepts":"{1:176245508045154512}","errmsg":"ok","active":true,"avatar":"https://static-legacy.dingtalk.com/media/lADPD3lG17hhp5vNBJTNBJI_1170_1172.jpg","isAdmin":true,"tags":{},"isHide":false,"name":"庹忠东","position":"IT主管","realAuthed":false}


            //{"errcode":0,"exclusiveAccount":false,"unionid":"E5diSWXRceqMCaljo19xKzgiEiE","roles":[],"userid":"013725223624084149","isLeaderInDepts":"{1:false}","isBoss":true,"isSenior":false,"department":[1],"orderInDepts":"{1:176245508045154512}","errmsg":"ok","active":true,"avatar":"https://static-legacy.dingtalk.com/media/lADPD3lG17hhp5vNBJTNBJI_1170_1172.jpg","isAdmin":true,"tags":{},"isHide":false,"name":"庹忠东","position":"IT主管","realAuthed":false}

            //eBase.AppendLog(result);
            return result;
        }
        public void Send()
        {
            // h ttps://open.dingtalk.com/document/orgapp-server/message-types-and-data-format
            // h ttps://blog.csdn.net/qq_45533841/article/details/106193759
            string accessToken = getAccesstoken2();
            string data = "{";
            data += "\"userid_list\" : \"013725223624084149\","; //接受推送userid，不同用户用|分割
            //data += "\"dept_id_list\" : \"013725223624084149\","; //接受推送部门id
            data += "\"agent_id\" : \"" + AgentId + "\",";
            data += "\"msgtype\" : \"text\",";
            data += "\"msg\" : {";
            data += "\"msgtype\" : \"text\",";
            data += "\"text\" : {\"content\": \"月会通知333\"}";
            data += "}";

            data += "}";

            string url = String.Format("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token={0}", accessToken);

            string result = eBase.postRequest(url,data);
            //{"errcode":0,"errmsg":"ok","task_id":2780482218286,"request_id":"16kmcgbx6w91j"}
            eBase.AppendLog(result);
            eBase.Writeln(result);
        }


    }
}