using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace RMYY_CallCenter_Api.Utility
{
    public class DingTalkHelper
    {
        /// <summary>
        /// 获取AccessToken
        /// </summary>
        /// <returns></returns>
        public static string GetAccessToken()
        {
            var accesstoken = RedisHelper.StringGet("DingTalkToken")?.ToString() ?? "";
            if (string.IsNullOrEmpty(accesstoken))
            {
                string result = HttpHelper.HttpGet(string.Format("https://oapi.dingtalk.com/gettoken?appkey={0}&appsecret={1}", ConfigHelper.GetValue("DingTalk_AppKey"), ConfigHelper.GetValue("DingTalk_AppSecret")));
                var resultobj = result.ToJObject();
                if (resultobj["errcode"].ToString() == "0")
                {
                    accesstoken = resultobj["access_token"].ToString();
                    string cachetime = ConfigHelper.GetValue("DingTalk_TokenCacheTime");
                    RedisHelper.StringSet("DingTalkToken", accesstoken, new TimeSpan(0, 0, cachetime.ToInt()));
                }
            }

            return accesstoken;
        }

        /// <summary>
        /// 根据手机号获取用户id
        /// </summary>
        /// <param name="mobile">手机号</param>
        /// <returns></returns>
        public static string GetUserIdByMobile(string mobile)
        {
            string userid = string.Empty;
            var param = new
            {
                mobile = mobile
            };
            var strresult = HttpHelper.HttpPost(string.Format("https://oapi.dingtalk.com/topapi/v2/user/getbymobile?access_token={0}", GetAccessToken()), param.ToJson(), "application/json");
            if (!string.IsNullOrEmpty(strresult))
            {
                var resultobj = strresult.ToJObject();
                if (resultobj["errcode"].ToString() != "0")
                {
                    LogHelper.Error(strresult);
                    //userid = resultobj["errmsg"].ToString();
                }
                else
                {
                    var robj = resultobj["result"].ToString().ToJObject();
                    userid = robj["userid"].ToString();
                }
            }

            return userid;
        }

        /// <summary>
        /// 发送模板消息
        /// </summary>
        /// <param name="userids">多个用户逗号隔开</param>
        /// <param name="deptids">多个部门逗号隔开</param>
        /// <param name="msgjson">模板参数json</param>
        /// <param name="templateid">模板ID</param>
        /// <returns></returns>
        public static string SendMessageByTemplate(string userids, string deptids, string msgjson, string templateid)
        {
            string result = string.Empty;
            var param = new
            {
                agent_id = ConfigHelper.GetValue("DingTalk_AgentId"),
                template_id = templateid,
                //data = "{\"name\":\"淘宝6\",\"name2\":\"http://www.taobao.com\"}",
                data = msgjson,
                //userid_list = "213,234,123",
                userid_list = userids,
                //dept_id_list = "421,897,262"
                dept_id_list= deptids
            };
            var strresult = HttpHelper.HttpPost(string.Format("https://oapi.dingtalk.com/topapi/message/corpconversation/sendbytemplate?access_token={0}", GetAccessToken()), param.ToJson(), "application/json");
            if (!string.IsNullOrEmpty(strresult))
            {
                var resultobj = strresult.ToJObject();
                if (resultobj["errcode"].ToString() != "0")
                {
                    LogHelper.Error(strresult);
                    result = resultobj["errmsg"].ToString();
                }
            }
            return result;
        }


        /// <summary>
        /// 发送工作通知
        /// </summary>
        /// <param name="userids">多个用户逗号隔开</param>
        /// <param name="deptids">多个部门逗号隔开</param>
        /// <param name="msgjson">内容json</param>
        /// <param name="isall">是否全部群发</param>
        /// <returns></returns>
        public static string SendMessage(string userids, string deptids, string msgjson, bool isall=false)
        {
            string result = string.Empty;
            var param = new JObject();
            param["agent_id"] = ConfigHelper.GetValue("DingTalk_AgentId");
            if (!string.IsNullOrEmpty(userids))
            {
                param["userid_list"] = userids;
            }
            if (!string.IsNullOrEmpty(deptids))
            {
                param["dept_id_list"] = deptids;
            }
            param["to_all_user"] = isall;
            param["msg"] = msgjson.ToJObject();
            //var param=new
            //{
            //    agent_id = ConfigHelper.GetValue("DingTalk_AgentId"),
            //    //userid_list = "213,234,123",
            //    userid_list = userids,
            //    //dept_id_list = "421,897,262"
            //    dept_id_list = deptids,
            //    to_all_user = isall,
            //    //msg = new {
            //    //    msgtype="text",
            //    //    text = new {content="内容" }
            //    //},
            //    //msg = new
            //    //{
            //    //    msgtype = "markdown",
            //    //    markdown = new { text = "内容",title="标题" }
            //    //},
            //    msg
            //};
            var strresult = HttpHelper.HttpPost(string.Format("https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token={0}", GetAccessToken()), param.ToJson(), "application/json");
            if (!string.IsNullOrEmpty(strresult))
            {
                var resultobj = strresult.ToJObject();
                if (resultobj["errcode"].ToString() != "0")
                {
                    LogHelper.Error(strresult);
                    result = resultobj["errmsg"].ToString();
                }
                else
                {
                    result = resultobj["task_id"].ToString();
                }
            }
            return result;
        }

        /// <summary>
        /// 发送工作通知-文本
        /// </summary>
        /// <param name="userids">多个用户逗号隔开</param>
        /// <param name="deptids">多个部门逗号隔开</param>
        /// <param name="content">文本内容</param>
        /// <returns></returns>
        public static string SendMessageText(string userids, string deptids, string content)
        {
            var msg = new
            {
                msgtype = "text",
                text = new { content }
            };
            string result = SendMessage(userids, deptids, msg.ToJson());
            return result;
        }
        /// <summary>
        /// 获取工作通知结果
        /// <returns></returns>
        public static int  GetMessage(string task_id)
        {
            int result = 0;
            var param = new JObject();
            param["agent_id"] = ConfigHelper.GetValue("DingTalk_AgentId");
            if (!string.IsNullOrEmpty(task_id))
            {
                param["task_id"] = task_id;
            }
            var strresult = HttpHelper.HttpPost(string.Format("https://oapi.dingtalk.com/topapi/message/corpconversation/getsendresult?access_token={0}", GetAccessToken()), param.ToJson(), "application/json");
            if (!string.IsNullOrEmpty(strresult))
            {
                var resultobj = strresult.ToJObject();
                if (resultobj["errcode"].ToString() != "0")
                {
                    LogHelper.Error(strresult);
                    result = 0;
                }
                else
                {
                    send_result jo = JsonConvert.DeserializeObject<send_result>(resultobj["send_result"].ToString());
                    if (jo!=null )
                    {
                        if(jo .read_user_id_list !=null && jo.read_user_id_list.Count >0)
                            result = 1;
                        else if (jo.unread_user_id_list != null && jo.unread_user_id_list.Count > 0)
                            result = 2;
                    }
                }
            }
            return result;
        }
        public class send_result
        {
            public List <string > read_user_id_list { set; get; }
            public List <string > unread_user_id_list { set; get; }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="userid"></param>
        /// <returns></returns>
        public static string GetUserInfoByUserId(string userid)
        {
            //WebClient web = new WebClient();
            //web.Encoding = Encoding.UTF8;
            //string strresult = web.DownloadString(string.Format("https://oapi.dingtalk.com/user/get?access_token={0}&userid={1}", GetAccessToken(), userid));

            //JObject jo = (JObject)JsonConvert.DeserializeObject(strresult);


            //return jo.ToJson();


            string url = string.Format("https://oapi.dingtalk.com/user/get?access_token={0}&userid={1}", GetAccessToken(), userid);

            var strresult = HttpHelper.HttpGet(url);

            return strresult;
        }

        //给某个部门的所有的人发消息
        /// <summary>
        /// 获取部门列表 参数传1 是根节点的子部门
        /// https://open.dingtalk.com/document/orgapp-server/obtain-the-department-list-v2
        /// </summary>
        /// <returns></returns>   
        public static string GetDeptlist()
        {
            WebClient web = new WebClient();
            web.Encoding = Encoding.UTF8;
            string strresult = web.DownloadString(string.Format("https://oapi.dingtalk.com/topapi/v2/department/listsub?access_token={0}&dept_id={1}", GetAccessToken(), 1));

            JObject jo = (JObject)JsonConvert.DeserializeObject(strresult);

        
            return jo.ToJson();

        }

        /// <summary>
        ///   获取部门所有的userid
        /// </summary>
        /// <param name="deptid">Get   https://oapi.dingtalk.com/user/getDeptMember </param>
        /// <returns></returns>
        public static string GetUserIdsByDeptId(double deptid) 
        {
             

            WebClient web = new WebClient();
            web.Encoding = Encoding.UTF8;
            string strresult = web.DownloadString(string.Format("https://oapi.dingtalk.com/user/getDeptMember?access_token={0}&deptId={1}", GetAccessToken(), deptid));

            JObject jo = (JObject)JsonConvert.DeserializeObject(strresult);
            if (jo != null && jo["userIds"] != null)
            {
                return jo["userIds"].ToString();
            }

            //JsonConvert.SerializeObject();
            //TreeModel model= JsonConvert.DeserializeObject<TreeModel>(strresult);


            return "";

        }


        
    }
}
 
