using CallCenter.Utility;
using CallCenterApi.Common;
using CallCenterApi.DB;
using CallCenterApi.Interface.Controllers.Base;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Mvc;


namespace CallCenterApi.Interface.Controllers
{
    public class SMSController : BaseController
    {

        private static string Smsurl = "http://rcsapi.wo.cn:8000/umcinterface/sendtempletmsg";
        private static string Smsurl1 = "http://220.250.65.184:9014/union-gjdx-sms-api/sms/submit";
        static string cpcode = "AABJYC";
        static string key = "724ee6be83d8d6f4d64ef5a537a9985d";

        //private static string Smsurl = Configs.GetValue("Smsurl");
        //private static string Smsurl1 = Configs.GetValue("Smsurl1");
        //static string cpcode = Configs.GetValue("Smscpcode");
        //static string key = Configs.GetValue("Smskey");

        /// <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 (); ;
        }
        public static  string   SendSms(string  msg,string mobiles,string templetid,string excode = "")
        {
            bool n=false ;
            string sign = Md5(cpcode + msg + mobiles + excode + templetid + key);
            var dic = new SortedDictionary<string, string>
            {
                {"cpcode", cpcode},
                {"msg", msg},
                {"mobiles", mobiles},
                {"excode", excode},
                {"templetid",templetid},
                {"sign", sign},
            };
            //序列化参数
            var jsonParam = JsonConvert.SerializeObject(dic);
            ////发送请求
            //var request = (HttpWebRequest)WebRequest.Create(Smsurl);
            //request.Method = "POST";
            //request.ContentType = "application/json;charset=UTF-8";
            //var byteData = Encoding.UTF8.GetBytes(jsonParam);
            //var length = byteData.Length;
            //request.ContentLength = length;
            //var writer = request.GetRequestStream();
            //writer.Write(byteData, 0, length);
            //writer.Close();
            ////接收数据
            //var response = (HttpWebResponse)request.GetResponse();
            //var responseString = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")).ReadToEnd();
            var responseString = HttpMethods.HttpPost(Smsurl, jsonParam, "application/json;charset=UTF-8");
            JObject jo = (JObject)JsonConvert.DeserializeObject(responseString );
            string access_token = jo["resultcode"].ToString();
            string taskid = jo["taskid"].ToString();
            return access_token;
        }


        private static readonly HttpClient client = new HttpClient();
        public static string SendSms1( string mobiles, string   templetid, string  templet="" )
        {
            bool n = false;
         //   string sign = Md5(cpcode + msg + mobiles + excode + templetid + key);
             Dictionary<string, string> values = new Dictionary<string, string>();
               values.Add("account", "ayxzfwzx");
              values.Add("passwd", "ayxzfwzx123");
              values.Add("mobile", mobiles);
              values.Add("templateId", templetid);
               values.Add("templateParams", templet);
              //  var content = new FormUrlEncodedContent(values);
            var content = new StringContent(values.ToJson(), Encoding.UTF8, "application/json");
            var response = client.PostAsync(Smsurl1, content).Result;
                    var responseString = response.Content.ReadAsByteArrayAsync().Result;
                    string ret = Encoding.Default.GetString(responseString);//"\"success\": true";
              return ret;
        }
        public class Reply
        {
            public string fisp { set; get; }
            public string mobile { set; get; }
            public string msg { set; get; }
            public string time { set; get; }
        }
        /// <summary>
        /// 获取接收短信列表
        /// </summary>
        /// <returns></returns>
        [HttpPost ]
        public ActionResult GetReply()
        {
            StreamReader reader = new StreamReader(System.Web.HttpContext.Current.Request.InputStream);
            var postString = reader.ReadToEnd();
            var replies = JsonConvert.DeserializeObject<List<Reply>>(postString);
            if (replies!=null && replies.Count >0)
            {
                foreach (var it  in replies)
                {
                    var dModel = new BLL.T_SMS_RecvSMS()
              .GetModelList("CallerNum='" + it.mobile + "'and F_Name !='' and F_Name is not null"
           + " order by RecvTime desc  ");
                    if (dModel != null && dModel.Count > 0)
                    {
                        dModel[0].Content += it.msg;
                        new BLL.T_SMS_RecvSMS().Update(dModel[0]);
                    }
                }
            }
            var obj = new
            {
                status = 0
            };
            return Content(obj.ToJson ());
        }
        public static bool   AddSmS(int userId,string msg,string Content, string mobiles, string templetid
            ,string templet = "",string workorderid="")
        {
            bool res = false ;
            //  string  n = SendSms(msg,mobiles, templetid, templet);

            string sign = Md5(cpcode + msg + mobiles + "" + templetid + key);
            var dic = new SortedDictionary<string, string>
            {
                {"cpcode", cpcode},
               {"msg", msg},
                {"mobiles", mobiles},
                {"excode", ""},
                {"templetid",templetid},
                {"sign", sign},
            };
            //序列化参数
            var jsonParam = JsonConvert.SerializeObject(dic);
           // 发送请求
            var request = (HttpWebRequest)WebRequest.Create(Smsurl);
            request.Method = "POST";
            request.ContentType = "application/json;charset=UTF-8";
            var byteData = Encoding.UTF8.GetBytes(jsonParam);
            var length = byteData.Length;
            request.ContentLength = length;
            var writer = request.GetRequestStream();
            writer.Write(byteData, 0, length);
            writer.Close();
            //接收数据
            var response = (HttpWebResponse)request.GetResponse();
            var responseString = new StreamReader(response.GetResponseStream(), Encoding.GetEncoding("utf-8")).ReadToEnd();

           //  var responseString = HttpMethods.HttpPost(Smsurl, jsonParam, "application/json;charset=UTF-8");
             JObject jo = (JObject)JsonConvert.DeserializeObject(responseString);
             string access_token = jo["resultcode"].ToString();
              string taskid = jo["taskid"].ToString();
          
           // string result = SmsNewHelper.Send(mobiles, Content);
          
            if (access_token=="0")
            {
                Model.T_SMS_RecvSMS dModel = new Model.T_SMS_RecvSMS();
                dModel.CallerNum = mobiles.Trim();
                dModel.Content = Content.Trim();
                dModel.RecvModemIMEI = "";
                dModel.F_Name = workorderid;
                dModel.State = 0;
                dModel.F_UserID = userId;
                dModel.RecvTime = DateTime.Now;
                int b = new BLL.T_SMS_RecvSMS().Add(dModel);
                if (b > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
                return res;
        }

        public ActionResult GetReceive(string mobile,string smsContent,string sendTime,string addSerial)
        {

            Model.T_SMS_RecvSMS dModel = new Model.T_SMS_RecvSMS();
            dModel.CallerNum = mobile.Trim();
            dModel.Content = smsContent.Trim();
            dModel.RecvModemIMEI = addSerial;
           // dModel.F_Name = workorderid;
            dModel.State = 1;
           // dModel.F_UserID = userId;
           try
            {
                dModel.RecvTime = DateTime.Parse(addSerial);
            }
            catch
            {
                dModel.RecvTime = DateTime .Now ;
            }
            
            int b = new BLL.T_SMS_RecvSMS().Add(dModel);
            if (b > 0)
            {
                return Success ("获取成功");
            }
            else
            {
                return Error ("获取失败");
            }
        }
        /// <summary>
        /// 发送市长信箱短信
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="WorkOrderId"></param>
        /// <returns></returns>
        public ActionResult SendMailbox(string phone)
        {

           
              string result = SmsNewHelper.Send(phone, "市长信箱留言网址：https://zwfw.anyang.gov.cn/#/mayor_mail");
           
            if (result==string .Empty )
                return Success("发送成功");
            else
                return Error("发送失败");
           
        }

        #region 接收短信
        [Authority]
        /// <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  type = RequestString.GetInt("type", 0);
            int State = RequestString.GetInt ("state", 0);
            int acceptance = RequestString.GetInt("acceptance", 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 (type>0)
            {
                if (type ==1)
                {
                    sql += " and F_CustomerID=1 ";
                }
                else
                {
                    sql += " and F_CustomerID is null ";

                }
            }

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

            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }
            if (acceptance>0)
            {
                if (acceptance==1)
                {
                    sql += " and F_Name   !=''";
                }
                else
                {
                    sql += " and (F_Name ='' or F_Name is null )";
                }
            }
            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());

        }
        [Authority]
        /// <summary>
        /// 新增接收短信
        /// </summary>
        /// <returns></returns>
        public ActionResult AddRecv(string tel, string cont)
        {
            Model.T_SMS_RecvSMS dModel = new Model.T_SMS_RecvSMS();
            dModel.CallerNum = tel.Trim();
            dModel.Content = cont.Trim();
            dModel.State = 0;
            dModel.RecvTime = DateTime.Now;
            int b = new BLL.T_SMS_RecvSMS().Add(dModel);
            if (b > 0)
            {
                return Success("添加成功");
            }
            else
            {
                return Success("添加失败");
            }
        }

        [Authority]
        /// <summary>
        /// 删除接收短信
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult DelRecv(string[] ids)
        {
            if (ids != null && ids.Length > 0)
            {
                string idd = " ";
                foreach (string str in ids)
                {
                    idd += str + ",";
                }
                if (new BLL.T_SMS_RecvSMS().DeleteList(idd.TrimEnd(',')))
                {
                    return Success("删除成功");
                }
                else
                {
                    return Error("删除失败");
                }
            }
            else
            {
                return Error("请选择要删除的接收短信");
            }

        }

        [Authority]
        /// <summary>
        /// 更新接收短信状态
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult UpdateRecvState(string[] ids, string state)
        {
            
            
            int n = -1;
            if (ids != null && ids.Length > 0 && Int32.TryParse(state, out n))
            {
                string idd = " ";
                foreach (string str in ids)
                {
                    idd += str + ",";
                }

                string sql = "update T_SMS_RecvSMS set State='" + n + "' where ID in(" + idd.TrimEnd(',') + ")";
                if (!string.IsNullOrEmpty(idd.Trim()))
                {
                    if (DbHelperSQL.ExecuteSql(sql) > 0)
                    {
                        return Success("更新成功");
                    }
                    else
                    {
                        return Error("更新失败");
                    }
                }
                else
                {
                    return Error("请选择记录");
                }
            }
            else
            {
                return Error("获取参数失败");
            }
        }

        #endregion

        #region 发送短信

        [Authority]
        /// <summary>
        /// 获取发送短信任务列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetSendTaskList()
        {
            string sql = "";
            DataTable dt = new DataTable();

            string strtel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
            string strcont = HttpUtility.UrlDecode(RequestString.GetQueryString("cont"));
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));

            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;

            if (strtel.Trim() != "" && strtel != "undefined")
            {
                sql += " and TelNum like '%" + strtel.Trim() + "%' ";
            }
            if (strcont.Trim() != "" && strcont != "undefined")
            {
                sql += " and Content like '%" + strcont.Trim() + "%' ";
            }
            if (strstarttime.Trim() != "" && strstarttime != "undefined")
            {
                sql += " and CommitTime >= '" + Convert.ToDateTime(strstarttime.Trim()) + "' ";
            }
            if (strendtime.Trim() != "" && strendtime != "undefined")
            {
                sql += " and CommitTime <= '" + Convert.ToDateTime(strendtime.Trim()) + "' ";
            }

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

            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }
            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_SMS_SendSMSTask",
                "SMSID",
                "*",
                sql,
                "ORDER BY SMSID desc",
                pagesize,
                pageindex,
                true,
                out recordCount);

            var obj = new
            {
                state = "success",
                message = "成功",
                rows = dt,
                total = recordCount
            };

            return Content(obj.ToJson());

        }

        [Authority]
        /// <summary>
        /// 新增短信任务
        /// </summary>
        /// <returns></returns>
        public ActionResult AddSendTask()
        {
            
            
            string strid = HttpUtility.UrlDecode(RequestString.GetFormString("id"));
            string strtel = HttpUtility.UrlDecode(RequestString.GetFormString("tel"));
            string strtype = HttpUtility.UrlDecode(RequestString.GetFormString("type"));
            string strdssj = HttpUtility.UrlDecode(RequestString.GetFormString("dssj"));
            string strcusid = HttpUtility.UrlDecode(RequestString.GetFormString("cusid"));
            string strcont = HttpUtility.UrlDecode(RequestString.GetFormString("cont"));
            string strmax = HttpUtility.UrlDecode(RequestString.GetFormString("max"));

            Model.T_SMS_SendSMSTask dModel = new Model.T_SMS_SendSMSTask();
            if (strid != "")
            {
                int id = Int32.Parse(strid);
                dModel = new BLL.T_SMS_SendSMSTask().GetModel(id);
                if (dModel != null)
                {
                    dModel.TelNum = strtel.Trim();
                    dModel.Content = strcont;
                    dModel.CurSentCount = 0;
                    dModel.MaxSendCount = Int32.Parse(strmax);
                    dModel.Info = "立即短信";
                    dModel.SendTime = DateTime.Now;

                    if (strtype == "1")
                    {
                        dModel.Info = "定时短信";
                        dModel.SendTime = DateTime.Parse(strdssj);
                    }

                    dModel.F_UserID = User.F_UserId;
                    if (!string.IsNullOrEmpty(strcusid))
                    {
                        int cid = Int32.Parse(strcusid);
                        var user = new BLL.T_Sys_UserAccount().GetModel(cid);
                        if (user != null)
                        {
                            dModel.F_CustomerID = User.F_UserId;
                            dModel.F_Name = user.F_UserName;
                        }
                    }

                    dModel.State = 0;
                    dModel.CommitTime = DateTime.Now;
                    if (new BLL.T_SMS_SendSMSTask().Update(dModel))
                    {
                        return Success("修改成功");
                    }
                    else
                    {
                        return Error("修改失败");
                    }
                }
                else
                {
                    return Error("修改失败");
                }
            }
            else
            {
                foreach (string tel in strtel.Split(','))
                {
                    dModel.TelNum = tel;
                    dModel.Content = strcont;
                    dModel.CurSentCount = 0;
                    dModel.MaxSendCount = Int32.Parse(strmax);
                    dModel.Info = "立即短信";
                    dModel.SendTime = DateTime.Now;

                    if (strtype == "1")
                    {
                        dModel.Info = "定时短信";
                        dModel.SendTime = DateTime.Parse(strdssj);
                    }

                    dModel.F_UserID = User.F_UserId;
                    if (!string.IsNullOrEmpty(strcusid))
                    {
                        int cid = Int32.Parse(strcusid);
                        var user = new BLL.T_Sys_UserAccount().GetModel(cid);
                        if (user != null)
                        {
                            dModel.F_CustomerID = User.F_UserId;
                            dModel.F_Name = user.F_UserName;
                        }
                    }

                    dModel.State = 0;
                    dModel.CommitTime = DateTime.Now;
                    new BLL.T_SMS_SendSMSTask().Add(dModel);
                    //int b = new BLL.T_SMS_SendSMSTask().Add(dModel);
                    //if (b > 0)
                    //{
                    //    return Success("添加成功");
                    //}
                    //else
                    //{
                    //    return Success("添加失败");
                    //}
                }
                return Success("成功");
            }
        }

        [Authority]
        /// <summary>
        /// 删除短信任务
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult DelSendTask(string[] ids)
        {
            if (ids != null && ids.Length > 0)
            {
                string idd = " ";
                foreach (string str in ids)
                {
                    idd += str + ",";
                }
                if (new BLL.T_SMS_SendSMSTask().DeleteList(idd.TrimEnd(',')))
                {
                    return Success("删除成功");
                }
                else
                {
                    return Error("删除失败");
                }
            }
            else
            {
                return Error("请选择要删除的短信任务");
            }

        }

        [Authority]
        /// <summary>
        /// 获取发送短信列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetSendList()
        {
            string sql = "";
            DataTable dt = new DataTable();

            string strtel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
            string strcont = HttpUtility.UrlDecode(RequestString.GetQueryString("cont"));
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));
            string strstate = HttpUtility.UrlDecode(RequestString.GetQueryString("state"));

            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;

            if (strtel.Trim() != "" && strtel != "undefined")
            {
                sql += " and TelNum like '%" + strtel.Trim() + "%' ";
            }
            if (strcont.Trim() != "" && strcont != "undefined")
            {
                sql += " and Content like '%" + strcont.Trim() + "%' ";
            }
            if (strstarttime.Trim() != "" && strstarttime != "undefined")
            {
                sql += " and CommitTime >= '" + Convert.ToDateTime(strstarttime.Trim()) + "' ";
            }
            if (strendtime.Trim() != "" && strendtime != "undefined")
            {
                sql += " and CommitTime <= '" + Convert.ToDateTime(strendtime.Trim()) + "' ";
            }
            if (strstate.Trim() != "" && strstate != "undefined")
            {
                sql += " and State= '" + strstate.Trim() + "' ";
            }

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

            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }
            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_SMS_SentSMS",
                "SMSID",
                "*",
                sql,
                "ORDER BY SMSID desc",
                pagesize,
                pageindex,
                true,
                out recordCount);

            var obj = new
            {
                state = "success",
                message = "成功",
                rows = dt,
                total = recordCount
            };

            return Content(obj.ToJson());

        }

        [Authority]
        /// <summary>
        /// 删除短信
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult DelSend(string[] ids)
        {
            if (ids != null && ids.Length > 0)
            {
                string idd = " ";
                foreach (string str in ids)
                {
                    idd += str + ",";
                }
                if (new BLL.T_SMS_SentSMS().DeleteList(idd.TrimEnd(',')))
                {
                    return Success("删除成功");
                }
                else
                {
                    return Error("删除失败");
                }
            }
            else
            {
                return Error("请选择要删除的短信");
            }

        }

        [Authority]
        /// <summary>
        /// 导入短信
        /// </summary>
        /// <returns></returns>
        public ActionResult ImportSend()
        {
            
            
            string strtype = HttpUtility.UrlDecode(RequestString.GetFormString("type"));
            string strdssj = HttpUtility.UrlDecode(RequestString.GetFormString("dssj"));
            HttpPostedFile _upfile = RequestString.GetFile("upFile");
            int headrow = 1;

            NPOIHelper np = new NPOIHelper();
            DataTable dt = np.ExcelToTable(_upfile, headrow);

            string msg = string.Empty;
            foreach (DataRow dr in dt.Rows)
            {
                headrow = headrow + 1;
                if (dr[0].ToString() != "" && dr[1].ToString() != "")
                {
                    Model.T_SMS_SendSMSTask dModel = new Model.T_SMS_SendSMSTask();
                    dModel.TelNum = dr[0].ToString();
                    dModel.Content = dr[1].ToString();
                    dModel.CurSentCount = 0;
                    //dModel.MaxSendCount = Int32.Parse(strmax);
                    dModel.Info = "立即短信";
                    dModel.SendTime = DateTime.Now;

                    if (strtype == "1")
                    {
                        dModel.Info = "定时短信";
                        dModel.SendTime = DateTime.Parse(strdssj);
                    }
                    dModel.State = 0;
                    dModel.F_UserID = User.F_UserId;
                    dModel.F_Name = User.F_UserName;

                    if (new BLL.T_SMS_SendSMSTask().Add(dModel) <= 0)
                    {
                        msg = msg + "第" + headrow + "行，导入失败<br>";
                    }
                }
                else
                {
                    msg = msg + "第" + headrow + "行，手机号或者内容为空，未导入<br>";
                }
            }
            if (!string.IsNullOrEmpty(msg))
            {
                return Error(msg);
            }
            else
            {
                return Success("成功");
            }
        }

        #endregion

        #region 短信服务

        /// <summary>
        /// 执行发送短信
        /// </summary>
        /// <returns></returns>
        public ActionResult ExecSendByJob()
        {
            DataTable dt = new DataTable();

            int ct = RequestString.GetInt("count", 10);
            string str = string.Empty;
            if (ct != 0)
            {
                str = " top " + ct;
            }
            dt = DB.DbHelperSQL.Query(" select " + ct + " * from T_SMS_SendSMSTask where State=0 and SendTime<=getdate()  order by CommitTime asc ").Tables[0];
            foreach (DataRow dr in dt.Rows)
            {

                Model.T_SMS_SendSMSTask dModel = new BLL.T_SMS_SendSMSTask().GetModel(Int32.Parse(dr["ID"].ToString()));
                if (dModel != null && dModel.State == 0)
                {
                    lock (this)
                    {
                        dModel.State = 1;
                        new BLL.T_SMS_SendSMSTask().Update(dModel);

                        string msg = SendSMS(dr["Telephone"].ToString(), dr["Detail"].ToString());

                        int State = 2;
                        if (!string.IsNullOrEmpty(msg))
                        {
                            State = -1;
                        }

                        Model.T_SMS_SentSMS model = new Model.T_SMS_SentSMS();
                        model.State = State;
                        model.TelNum = dModel.TelNum;
                        model.LastSentTime = DateTime.Now;
                        model.F_UserID = dModel.F_UserID;
                        model.F_Name = dModel.F_Name;
                        model.F_CustomerID = dModel.F_CustomerID;
                        model.CurSentCount = dModel.CurSentCount;
                        model.Content = dModel.Content;
                        model.CommitTime = dModel.CommitTime;
                        model.Info = dModel.Info;
                        model.MaxSendCount = dModel.MaxSendCount;
                        model.SendTime = dModel.SendTime;

                        new BLL.T_SMS_SentSMS().Add(model);

                        new BLL.T_SMS_SendSMSTask().Delete(dModel.SMSID);
                    }
                }
            }

            return Success("成功", dt);
        }

        /// <summary>
        /// 发送短信接口
        /// </summary>
        /// <returns></returns>
        public string SendSMS(string tel, string cont)
        {
            string msg = string.Empty;
            try
            {

            }
            catch (Exception ex)
            {
                msg = ex.Message;
            }
            return msg;
        }

      
        #endregion
    }
}