using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using RMYY_CallCenter_Api.Utility;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Mvc;

namespace RMYY_CallCenter_Api.Controllers
{
    public class SMSController : BaseController
    {
        private static string Smsurl = ConfigHelper.GetValue("Smsurl");
        private static string Smsuserid = ConfigHelper.GetValue("Smsuserid");
        static string Smspwd = ConfigHelper.GetValue("Smspwd");
      
        [AllowAnonymous]
        public ActionResult SnedUrl()
        {
           // var byStr =
            //   HttpUtility.UrlEncode(Encoding.GetEncoding("GBK").GetBytes("测试回复8")); 
           var byStr = HttpUtility.UrlDecode("%b2%e2%ca%d4%bb%d8%b8%b48"); 


            return Success("", byStr);
        }
       
        /// <summary>
        /// MD5加密
        /// </summary>
        /// <param name="txt"></param>
        /// <returns></returns>
        public static string Md5(string txt)
        {
            byte[] sor = Encoding.UTF8.GetBytes(txt);
            MD5 md5 = MD5.Create();
            byte[] result = md5.ComputeHash(sor);
            StringBuilder strbul = new StringBuilder(40);
            for (int i = 0; i < result.Length; i++)
            {
                //加密结果"x2"结果为32位,"x3"结果为48位,"x4"结果为64位
                strbul.Append(result[i].ToString("x2"));
            }
            return strbul.ToString().ToLower(); ;
        }
        [AllowAnonymous]
        public ActionResult SendSms1(string mobile, string content)
        {
            var SmS = AddSmS(0, content, mobile, "");
            if (SmS == "")
                return Success("发送成功");
            else
                return Error(SmS);
        }

        public ActionResult SendSms(int id, string mobile, string[] msg)
        {
            var model = new BLL.T_SMS_Template().GetModel(id);
            if (model == null)
                return Error("该模板不存在");
            if (string.IsNullOrEmpty(mobile))
                return Error("请输入手机号");
            if (msg != null && msg.Count() > 0)
            {
                var Contentsprite =Regex.Split(model.F_Content, "#P#", RegexOptions.IgnoreCase);
                var str = "";
                for (int i = 0; i < Contentsprite.Count(); i++)
                {
                    if (i < msg.Count())
                        str += Contentsprite[i] + msg[i];
                    else
                        str += Contentsprite[i];
                   // model.F_Content = model.F_Content.Replace("#P#", msg[i]);
                }
                model.F_Content = str;
            }

            //Model.T_SMS_RecvSMS dModel = new Model.T_SMS_RecvSMS();
            //dModel.CallerNum = mobile;
            //dModel.Content = model.F_Content;
            //dModel.F_CustomerID = model.F_ID;
            //dModel.F_Name = "";
            //dModel.State = 0;
            //dModel.F_UserID = User.F_UserId;
            //dModel.RecvTime = DateTime.Now;
            //int b = new BLL.T_SMS_RecvSMS().Add(dModel);
            //if (b > 0)
            //{
            //    return Success("发送成功");
            //}
            //else
            //{
            //    return Error("发送失败");
            //}
            var SmS = AddSmS(User.F_UserId, model.F_Content, mobile, "", model.F_ID);
            if (SmS == "")
                return Success("发送成功");
            else
                return Error(SmS);
        }


        public static string AddSmS(int userId, string Content, string mobiles, string workorderid = "",int   tempid=0)
        {
            try
            {
                var ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                var currentTime = Convert.ToInt64(ts.TotalSeconds).ToString();
                Dictionary<string, string> values = new Dictionary<string, string>();
                values.Add("userid", Smsuserid);
                values.Add("pwd", Md5(Smsuserid+ "00000000" + Smspwd+ currentTime) );
                values.Add("mobile", mobiles);
                values.Add("content", HttpUtility.UrlEncode(Encoding.GetEncoding("GBK").GetBytes(Content)) );
                values.Add("timestamp", currentTime);
                string responseString = HttpMethods .HttpPost (Smsurl+ "/sms/v2/std/single_send", values.ToJson (), "application/json;charset=UTF-8");
                JObject jo = (JObject)JsonConvert.DeserializeObject(responseString);
                if (jo["result"].ToString() == "0")
                {
                    Model.T_SMS_RecvSMS dModel = new Model.T_SMS_RecvSMS();
                    dModel.CallerNum = mobiles.Trim();
                    dModel.Content = Content.Trim();
                    dModel.RecvModemIMEI = jo["msgid"].ToString();
                    dModel.F_Name = workorderid;
                    dModel.State = 0;
                    dModel.F_UserID = userId;
                    dModel.F_CustomerID = tempid;
                    dModel.RecvTime = DateTime.Now;
                    int b = new BLL.T_SMS_RecvSMS().Add(dModel);
                    if (b > 0)
                    {
                        return "";
                    }
                    else
                    {
                        return "发送失败";
                    }
                }
                else
                {
                    string desc = jo["result"].ToString();
                    LogHelper.Error("sms" + "发送失败：错误码" + "(" + desc + ")");
                    return "发送失败：错误码" + "(" + desc + ")";

                }
            }
            catch (Exception e)
            {
                LogHelper.Error("sms" + e.Message);
                return e.ToString();
            }


        }

        public class mos
        {/// <summary>
         /// 平台流水号
         /// </summary>
            public long msgid { set; get; }
            /// <summary>
            /// 手机号
            /// </summary>
            public string mobile { set; get; }
            /// <summary>
            /// 完整的通道号
            /// </summary>
            public string spno { set; get; }
            /// <summary>
            /// 下行时填写的exno
            /// </summary>
            public string exno { set; get; }
            /// <summary>
            /// 上行返回的时间：  YYYY-MM-DD HH:MM:SS
            /// </summary>
            public string rtime { set; get; }
            /// <summary>
            /// 短信内容：最大支持1000个字(含签名),一个字母或一个汉字都视为一个字。   编码方法：urlencode（UTF-8明文）
            /// </summary>
            public string content { set; get; }
        }
        [AllowAnonymous]
        public ActionResult GetSMSReceive1()
        {
                var ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                var currentTime = Convert.ToInt64(ts.TotalSeconds).ToString();
                Dictionary<string, string> values = new Dictionary<string, string>();
                values.Add("userid", Smsuserid);
                values.Add("pwd", Md5(Smsuserid + "00000000" + Smspwd + currentTime));
                values.Add("timestamp", currentTime);
               
            string responseString = HttpMethods.HttpPost(Smsurl + "/sms/v2/std/get_mo", values.ToJson(), "application/json;charset=UTF-8");
               JObject jo = (JObject)JsonConvert.DeserializeObject(responseString);
                return Success("", responseString);

         }
        [AllowAnonymous]
        public ActionResult GetSMSReceive()
        {

            try
            {
                var ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
                var currentTime = Convert.ToInt64(ts.TotalSeconds).ToString();
                Dictionary<string, string> values = new Dictionary<string, string>();
                values.Add("userid", Smsuserid);
                values.Add("pwd", Md5(Smsuserid + "00000000" + Smspwd + currentTime));
                values.Add("timestamp", currentTime);
                string responseString = HttpMethods.HttpPost(Smsurl + "/sms/v2/std/get_mo", values.ToJson(), "application/json;charset=UTF-8");
                JObject jo = (JObject)JsonConvert.DeserializeObject(responseString);
                if (jo["result"].ToString() == "0")
                {

                    List<mos> moslist = JsonConvert.DeserializeObject<List<mos>>(jo["mos"].ToString());
                    if (moslist != null && moslist.Count > 0)
                    {
                        foreach (var it in moslist)
                        {
                            var RecvSMS = new BLL.T_SMS_RecvSMS().GetModelList($"RecvModemIMEI='{it.msgid.ToString()}' and F_State=1");
                            if (RecvSMS != null && RecvSMS.Count > 0)
                                continue;
                            Model.T_SMS_RecvSMS dModel = new Model.T_SMS_RecvSMS();
                            dModel.CallerNum = it.mobile;
                            dModel.Content = HttpUtility.UrlDecode(it.content);
                            dModel.RecvModemIMEI = it.msgid.ToString();
                            dModel.State = 1;
                            try
                            {
                                dModel.RecvTime = DateTime.Parse(it.rtime);
                            }
                            catch
                            {
                                dModel.RecvTime = DateTime.Now;
                            }
                            int b = new BLL.T_SMS_RecvSMS().Add(dModel);
                            if (b > 0)
                            {
                                return Success("获取成功");
                            }
                            else
                            {
                                return Error("获取失败");
                            }
                        }
                        return Error("暂无数据");
                    }
                    else
                        return Error("暂无数据1");

                }
                else
                {
                    string desc = jo["result"].ToString();
                    return Error("发送失败：错误码" + "(" + desc + ")");

                }
            }
            catch (Exception e)
            {
                return Error("发送失败：" + "(" + e.Message + ")");
            }


        }






        [AllowAnonymous]
        public ActionResult GetReceive() 
        {

            StreamReader reader = new StreamReader( RequestString .GetInputStream());
            var postString = reader.ReadToEnd();

            JObject result = null;

            LogHelper.Warn(postString);
            result = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(postString);

            string userid= result["userid"].ToString();
            string seqid = result["seqid"].ToString();
            string timestamp = result["timestamp"].ToString();
            string pwd = result["pwd"].ToString();
            string mos = result["mos"].ToString();
            if (userid!= Smsuserid)
                {
                    var obj1 =
                        new
                        {
                            cmd = "MO_RESP",
                            seqid = seqid,
                            result = "-100001"
                        };
                    return Content (obj1.ToJson());
                }
            
            var password = Md5(Smsuserid + "00000000" + Smspwd + timestamp);
           
            if (password != pwd)
                {
                    var obj2 =
                        new
                        {
                            cmd = "MO_RESP",
                            seqid = seqid,
                            result = "-100001"
                        };
                LogHelper.Warn(pwd);
                return Content(obj2.ToJson());
                }
            LogHelper.Warn(mos);
            if (!string .IsNullOrEmpty (mos))
            {
                List<mos> moslist = JsonConvert.DeserializeObject<List<mos>>(mos);
                if (moslist != null && moslist.Count > 0)
                {
                    foreach (var it in moslist)
                    {
                        Model.T_SMS_RecvSMS dModel = new Model.T_SMS_RecvSMS();
                        dModel.CallerNum = it.mobile;
                        dModel.Content = it.content;
                        dModel.RecvModemIMEI = it.msgid.ToString();
                        dModel.State = 1;
                        try
                        {
                            dModel.RecvTime = DateTime.Parse(it.rtime);
                        }
                        catch
                        {
                            dModel.RecvTime = DateTime.Now;
                        }
                        int b = new BLL.T_SMS_RecvSMS().Add(dModel);

                    }

                }
            }
          
                var obj =
                     new
                     {
                         cmd = "MO_RESP",
                         seqid = seqid,
                         result = "0"
                     };
                return Content(obj.ToJson());

           


        }





        /// <summary>
        /// 指定Post地址
        /// </summary>
        /// <param name="url">请求后台地址</param>
        /// <returns></returns>
        public static string Post(string url, Dictionary<string, string> dic)
        {
            string result = "";
            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            req.Method = "POST";
            req.ContentType = "application/x-www-form-urlencoded";
            #region 添加Post 参数
            StringBuilder builder = new StringBuilder();
            int i = 0;
            foreach (var item in dic)
            {
                if (i > 0)
                    builder.Append("&");
                builder.AppendFormat("{0}={1}", item.Key, item.Value);
                i++;
            }
            byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
            req.ContentLength = data.Length;
            using (Stream reqStream = req.GetRequestStream())
            {
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
            }
            #endregion
            HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
            Stream stream = resp.GetResponseStream();
            //获取响应内容
            using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
            {
                result = reader.ReadToEnd();
            }
            return result;
        }

        public ActionResult AddTemplate(string title,string content,int state=1)
        {
            if (string.IsNullOrEmpty(title))
                return Error("请输入标题");
            if (string.IsNullOrEmpty(content))
                return Error("请输入内容");
            Model.T_SMS_Template template = new Model.T_SMS_Template();
            template.F_Title = title;
            template.F_Content  = content;
            template.F_State = state;
            template.F_IsDelete = 0;
            template.F_CreateTime = DateTime.Now;
            template.F_CreateUser = User.F_UserCode;
            if (new BLL.T_SMS_Template().Add(template) > 0)
                return Success("添加成功");
            else
                return Error("添加失败");

        }

        public ActionResult UpdateTemplate(string title, string content,int id=0, int state = 1)
        {
            if (string.IsNullOrEmpty(title))
                return Error("请输入标题");
            if (string.IsNullOrEmpty(content))
                return Error("请输入内容");
            var template = new BLL.T_SMS_Template().GetModel(id);
            if (template == null)
                return Error("该模板不存在");
            template.F_Title = title;
            template.F_Content = content;
            template.F_State = state;
            template.F_UpdateTime  = DateTime.Now;
            template.F_UpdateUser  = User.F_UserCode;
            if (new BLL.T_SMS_Template().Update (template) )
                return Success("修改成功");
            else
                return Error("修改失败");

        }
        public ActionResult DelTemplate( int id = 0)
        {
            var template = new BLL.T_SMS_Template().GetModel(id);
            if (template == null)
                return Error("该模板不存在");
            template.F_IsDelete  = 1;
            template.F_DeleteUser = User.F_UserCode;
            if (new BLL.T_SMS_Template().Update(template))
                return Success("删除成功");
            else
                return Error("删除失败");

        }

        public ActionResult GetTemplate(int id = 0)
        {
            var template = new BLL.T_SMS_Template().GetModel(id);
            if (template == null)
                return Error("该模板不存在");
            else
                return Success ("获取成功", template);

        }
        /// <summary>
        /// 获取接收短信列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetTemplateList()
        {
            string sql = "";
            DataTable dt = new DataTable();

            string strtel = HttpUtility.UrlDecode(RequestString.GetQueryString("title"));
            string content = HttpUtility.UrlDecode(RequestString.GetQueryString("content"));
            int State = RequestString.GetInt("state", -1);
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;
            if (State>-1)
            sql += " and F_State= '" + State + "'  ";
            sql += "and F_IsDelete=0";
            if (strtel.Trim() != "" && strtel != "undefined")
            {
                sql += " and F_Title like'%" + strtel.Trim() + "%' ";
            }
            if (content.Trim() != "" && content != "undefined")
            {
                sql += " and F_Content like'%" + content.Trim() + "%' ";
            }

            if (strpageindex.Trim() != "")
            {
                pageindex = Convert.ToInt32(strpageindex);
            }

            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }
      
            int recordCount = 0;
            dt = Bll.PagerBll.GetListPager(
                "T_SMS_Template",
                "F_ID",
                "*",
                sql,
                "ORDER BY F_ID desc",
                pagesize,
                pageindex,
                true,
                out recordCount);
            var obj = new
            {
                state = "success",
                rows = dt,
                total = recordCount
            };

            return Content(obj.ToJson());
        }

        /// <summary>
        /// 获取接收短信列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetRecvList()
        {
            string sql = "";
            DataTable dt = new DataTable();

            string strtel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));
            int template = RequestString.GetInt("template", 0);
             int State = RequestString.GetInt("state", 0);
           
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;
             sql += " and State= '"+ State + "'  ";
            if (strtel.Trim() != "" && strtel != "undefined")
            {
                sql += " and CallerNum= '" + strtel.Trim() + "' ";
            }
            if (strstarttime.Trim() != "" && strstarttime != "undefined")
            {
                sql += " and RecvTime >= '" + Convert.ToDateTime(strstarttime.Trim()) + "' ";
            }
            if (strendtime.Trim() != "" && strendtime != "undefined")
            {
                sql += " and RecvTime <= '" + Convert.ToDateTime(strendtime.Trim()) + "' ";
            }
              if (template>0)
            {
                sql += $"and F_CustomerID='{template}'";
            }

            if (strpageindex.Trim() != "")
            {
                pageindex = Convert.ToInt32(strpageindex);
            }

            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }
          
            int recordCount = 0;
            dt = Bll.PagerBll.GetListPager(
                "T_SMS_RecvSMS",
                "SMSID",
                "*",
                sql,
                "ORDER BY SMSID desc",
                pagesize,
                pageindex,
                true,
                out recordCount);
            List<Model.T_SMS_RecvSMS> modelList = new BLL.T_SMS_RecvSMS().DataTableToList(dt);
            var obj = new
            {
                rows = modelList.Select(x => new
                {
                    x.CallerNum,
                    x.Content,
                    x.SMSID,
                    x.F_Name,
                    type = x.F_CustomerID,
                    usercode = "",
                    x.RecvTime
                }),
                total = recordCount
            };


            return Content(obj.ToJson());

        }
   



    }
}