using CallCenter.Utility;
using CallCenterApi.Interface.Controllers.Base;
using CallCenterApi.Model;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;

namespace CallCenterApi.Interface.Controllers.weibo
{
    [Authority]
    public class WeiBoController : BaseController
    {
        /// <summary>
        /// 获取最新发表的微博列表 count最多为5
        /// http://localhost:63660/WeiBo/WeiBoList
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public ActionResult WeiBoList()
        {
            string AccessToken = Configs.GetValue("WeiBoAccessToken");
            int recordCount = 0;
            string ReqURL = "https://api.weibo.com/2/statuses/user_timeline.json?access_token=" + AccessToken
                + "&count=20&page=1";
            try
            {
                string resultReq = HttpMethods.HttpGet(ReqURL);
                JObject result = JObject.Parse(resultReq);  // (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(resultReq);
                List<WeiBoList> listWB = new List<WeiBoList>();
                recordCount = int.Parse(result["total_number"].ToString()); //数量
                JArray jar = JArray.Parse(result["statuses"].ToString());  //Json列表
                for (var i = 0; i < jar.Count; i++)
                {
                    WeiBoList WBVariant = new WeiBoList();
                    JObject data = JObject.Parse(jar[i].ToString());
                    WBVariant.W_Id = long.Parse(data["id"].ToString());
                    WBVariant.W_Text = data["text"].ToString();
                    WBVariant.W_Source = data["source"].ToString();
                    WBVariant.W_Name = data["user"]["name"].ToString();
                    //时间转换
                    CultureInfo cultureInfo = CultureInfo.CreateSpecificCulture("en-US");
                    string format = "ddd MMM d HH:mm:ss zz00 yyyy";
                    WBVariant.W_Created_at = DateTime.ParseExact("Wed Aug 25 16:28:03 +0800 2010", format, cultureInfo);
                    WBVariant.W_Url = GetUrl(data["text"].ToString());
                    listWB.Add(WBVariant);
                }
                var obj = new
                {
                    rows = listWB,
                    total = recordCount
                };
                return Content(obj.ToJson());
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("403"))
                {
                    return Error("微博访问频次权限，已超出访问次数");
                }
                else
                {
                    return Error(ex.Message);
                }
            }



        }


        /// <summary>
        /// 获取一条微博详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult WeiBoInfoByIn(long id)
        {
            long idd = 0;
            long.TryParse(id.ToString(), out idd);
            string AccessToken = Configs.GetValue("WeiBoAccessToken");
            if (idd == 0)
            {
                return Error("获取失败");
            }
            string ReqURL = "https://api.weibo.com/2/statuses/show.json?access_token=" + AccessToken
                + "&id=" + idd;
            string resultReq = HttpMethods.HttpGet(ReqURL);
            JObject result = JObject.Parse(resultReq);

            WeiBoList model = new WeiBoList();
            model.W_Id = long.Parse(result["id"].ToString());
            model.W_Text = result["text"].ToString();
            model.W_Source = result["source"].ToString();
            model.W_Name = result["user"]["name"].ToString();
            //时间转换
            CultureInfo cultureInfo = CultureInfo.CreateSpecificCulture("en-US");
            string format = "ddd MMM d HH:mm:ss zz00 yyyy";
            model.W_Created_at = DateTime.ParseExact("Wed Aug 25 16:28:03 +0800 2010", format, cultureInfo);
            model.W_Url = GetUrl(result["text"].ToString());
            return Success("获取成功", model);
        }

        /// <summary>
        /// 根据微博ID返回某条微博的评论列表 20 3509146026498138
        /// </summary>
        /// <param name="type"></param>
        /// <param name="count"></param>
        /// <param name="page"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public ActionResult CommentsList(long id, int pagesize, int page)
        {
            string AccessToken = Configs.GetValue("WeiBoAccessToken");
            int recordCount = 0;
            int pageindex = 1;
            int pagesizes = 5;
            int.TryParse(page.ToString(), out pageindex);
            int.TryParse(pagesize.ToString(), out pagesizes);
            //获取用户最新发表的微博列表
            string ReqURL = "https://api.weibo.com/2/comments/show.json?access_token=" + AccessToken
                        + "&id=" + id + "&count=" + pagesizes + "&page=" + pageindex;
            string resultReq = HttpMethods.HttpGet(ReqURL);
            JObject result = JObject.Parse(resultReq);  // (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(resultReq);

            List<WeiBoCommentList> listWB = new List<WeiBoCommentList>();
            recordCount = int.Parse(result["total_number"].ToString()); //数量
            JArray jar = JArray.Parse(result["comments"].ToString());  //Json列表
            for (var i = 0; i < jar.Count; i++)
            {
                WeiBoCommentList WBVariant = new WeiBoCommentList();
                JObject data = JObject.Parse(jar[i].ToString());
                WBVariant.W_Id = long.Parse(data["id"].ToString());
                WBVariant.W_Text = data["text"].ToString();
                WBVariant.W_Source = data["source"].ToString();
                WBVariant.W_Name = data["user"]["name"].ToString();
                //时间转换
                CultureInfo cultureInfo = CultureInfo.CreateSpecificCulture("en-US");
                string format = "ddd MMM d HH:mm:ss zz00 yyyy";
                WBVariant.W_Created_at = DateTime.ParseExact("Wed Aug 25 16:28:03 +0800 2010", format, cultureInfo);
                WBVariant.W_Url = GetUrl(data["text"].ToString());
                WBVariant.W_Location = data["user"]["location"].ToString();
                listWB.Add(WBVariant);
            }
            var obj = new
            {
                rows = listWB,
                total = recordCount
            };
            return Content(obj.ToJson());
        }

        string AppKey = Configs.GetValue("WeiBoAppKey");
        string AppSercet = Configs.GetValue("WeiBoAppSercet");
        string CallBackUrl = Configs.GetValue("WeiBoCallBackUrl");

        #region 获取access_token
        /// <summary>
        /// 登录部分（获取access_token）
        /// </summary>
        /// <returns></returns>
        public ActionResult GetLogin()
        {
            //state参数用于防止CSRF攻击，成功授权后回调时会原样带回    
            Session["requeststate"] = Guid.NewGuid().ToString().Replace("-", "");
            string scope = "all";
            string Dialog_url = "https://api.weibo.com/oauth2/authorize?response_type=code&client_id="
               + AppKey + "&scope=" + scope + "&redirect_uri=" + Server.UrlEncode(CallBackUrl) + "&state="
               + Session["requeststate"];
            return Redirect(Dialog_url);
        }

        /// <summary>
        /// 授权回调页（获取access_token）
        /// </summary>
        /// <returns></returns>
        public ActionResult CallBack()
        {
            string code = RequestString.GetQueryString("code");
            string state = Session["requeststate"].ToString();

            if (code != null)
            {
                if (RequestString.GetQueryString("state").Equals(state))
                {
                    try
                    {
                        //获取授权过的Access Token    通过Authorization Code 
                        string token_url = "https://api.weibo.com/oauth2/access_token?grant_type=authorization_code&"
                        + "client_id=" + AppKey + "&redirect_uri=" + Server.UrlEncode(CallBackUrl)
                        + "&client_secret=" + AppSercet + "&code=" + code;
                        string response = HttpMethods.HttpPost(token_url);
                        //获取用户信息    使用Access Token来获取用户的OpenID
                        JObject result = JObject.Parse(response);
                        WeiBoLog.WriteLog("access_token:" + result["access_token"] + "uid:" + result["uid"] + "");
                    }
                    catch (Exception ex)
                    {
                        WeiBoLog.WriteLog("err:" + ex.Message + "");
                    }
                }
                else
                {
                    WeiBoLog.WriteLog("err:state参数失效");
                }
            }
            else
            {
                WeiBoLog.WriteLog("err:code参数获取为null");
            }
            return View();
        }
        #endregion



        /// <summary>
        /// 获取网址
        /// </summary>
        /// <param name="Str"></param>
        /// <returns></returns>
        public static string GetUrl(string Str)
        {
            string se = @"((http|https)://)?(www.)?[a-z0-9\.]+(\.(com|net|cn|com\.cn|com\.net|net\.cn))(/[^\s\n]*)?";
            Regex rg = new Regex(se);
            string link = rg.Match(Str).Value;
            return link;
        }

        /// <summary>
        /// 获取标准列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetList()
        {
            int type = RequestString.GetInt("type", 0);
            string key = RequestString.GetQueryString("key");
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;

            var sql = " and 1=1 ";
            if (type != 0)
            {
                sql += " and F_Type = '" + type + "'";
            }
            if (!string.IsNullOrEmpty(key))
            {
                sql += " and F_Text like '%" + key + "%'";
            }
            if (strpageindex.Trim() != "")
            {
                pageindex = Convert.ToInt32(strpageindex);
            }
            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }

            var recordCount = 0;
            var dt = BLL.PagerBLL.GetListPager(
              "T_Sina_Msg",
              "F_Id",
              "*",
              sql,
              "ORDER BY F_CreateTime desc ",
              pagesize,
              pageindex,
              true,
              out recordCount);

            var obj = new
            {
                rows = dt,
                total = recordCount
            };
            return Content(obj.ToJson());

        }

        /// <summary>
        /// 发送私信给用户
        /// </summary>
        /// <param name="uid"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public ActionResult SendText(string uid,string msg)
        {
            string AccessToken = Configs.GetValue("WeiBoAccessToken");
            string data = Url.Encode("{\"text\":\"" + msg + "\"}");
            string url = "https://m.api.weibo.com/2/messages/reply.json";
            string paras = "access_token=" + AccessToken + "&type=text&receiver_id=" + uid + "&data=" + data;
            string response = HttpMethods.HttpPost(url, paras);
            //获取用户信息    使用Access Token来获取用户的OpenID
            JObject result = JObject.Parse(response);
            if (result["result"].ToString() == "true")
            {
                var msgmodel = new Model.T_Sina_Msg();
                msgmodel.F_Sender = "";
                msgmodel.F_Receiver = uid.ToString();
                msgmodel.F_Type = "text";
                msgmodel.F_Text = msg;
                msgmodel.F_IsDelete = 0;
                msgmodel.F_State = 0;
                msgmodel.F_SendType = 2;
                msgmodel.F_CreateTime = DateTime.Now;

                new BLL.T_Sina_Msg().Add(msgmodel);

                return Success("成功");
            }
            else
            {
                return Error("失败");
            }
        }
    }
}