

using CallCenterApi.Interface.Controllers.Base;
using System;
using System.Web.Mvc;
using qcloudsms_csharp;
using qcloudsms_csharp.json;
using qcloudsms_csharp.httpclient;
using System.Data;
using System.Collections.Generic;
using CallCenter.Utility;

namespace CallCenterApi.Interface.Controllers
{
    public class SMSController : BaseController
    {
        #region 接收短信
        // 短信应用SDK AppID
        int appid = 1400238721;
        // 短信应用SDK AppKey
        string appkey = "2b2094bcaf2c841fdb50bcaebabf6f54";
        // 需要发送短信的手机号码
        // int templateId = 392016; // NOTE: 这里的模板ID`7839`只是一个示例，真实的模板ID需要在短信控制台中申请
        // 签名
        string smsSign = "心连心客服中心"; // NOTE: 这里的签名只是示例，请使用真实的已申请的签名, 签名参数使用的是`签名内容`，而不是`签名ID`
        BLL.T_Sys_UserAccount sysUserAccountBll = new BLL.T_Sys_UserAccount();
        #endregion
        public ActionResult SMSSend(string name, string phone, string cusphone)
        {
            int userId = CurrentUser.UserData.F_UserId;
            if (userId > 0)
            {
                Model.T_Sys_UserAccount ua = sysUserAccountBll.GetModel(userId);
                if (string.IsNullOrEmpty(name))
                    return Error("请输入联系人姓名");
                if (string.IsNullOrEmpty(phone))
                    return Error("请输入联系人电话");
                if (string.IsNullOrEmpty(cusphone))
                    return Error("请输入发送号码");
                string msg = "您好！感谢您的来电，有关化肥详细问题可联系市场经理，姓名：" + name + "，电话：" + phone + "。您也可以微信关注“心连心农资快讯”公众号进行咨询。祝您生活愉快！";
                string[] mag = { name, phone };
                SmsSingleSenderResult result = SMSSingleshot(466863, mag, cusphone);

                if (result != null)
                {
                    AddSmS(cusphone, msg, userId);
                    return Success("发送短信", result);
                }
                else
                {
                    return Error("发送失败，请检查客户电话");
                }
            }
            else
            {
                return Error("无操作权限");
            }

        }
        public ActionResult GetSmSList(string starttime, string endtime,string phone, int pageindex = 1, int pagesize = 10)
        {
            int userId = CurrentUser.UserData.F_UserId;
            if (userId > 0)
            {
                string sql = "";
                DataTable dt = new DataTable();
                if (!string.IsNullOrEmpty(starttime))
                    sql += " and datediff(day,RecvTime,'" + starttime + "')<=0 ";
                if (!string.IsNullOrEmpty(endtime))
                    sql += " and datediff(day,RecvTime,'" + endtime + "')>=0   ";
                if (!string.IsNullOrEmpty(phone))
                    sql += " and CallerNum= '" + phone + "'";
                
                int recordCount = 0;
                dt = BLL.PagerBLL.GetListPager(
                        "T_SMS_RecvSMS",
                        "SMSID",
                        "*",
                        sql,
                        "ORDER BY T_SMS_RecvSMS.SMSID desc",
                        pagesize,
                        pageindex,
                        true,
                        out recordCount);

                List<Model.T_SMS_RecvSMS> modlelist = new BLL.T_SMS_RecvSMS().DataTableToList(dt);
                if (modlelist.Count > 0)
                {
                    List<RecvSMS> Input = modeltooip(modlelist);
                    var obj = new
                    {
                        state = "success",
                        message = "成功",
                        rows = Input,
                        total = recordCount
                    };

                    return Content(obj.ToJson()); ;
                }
                else
                {

                    return Success("暂无短信"); ;
                }

            }
            else
            {
                return Error("无操作权限");
            }
        }
        public List<RecvSMS> modeltooip(List<Model.T_SMS_RecvSMS> model)
        {
            List<RecvSMS> SMS = new List<RecvSMS>();

            foreach (var it in model)
            {
                RecvSMS Recv = new RecvSMS();
                Recv.SMSID = it.SMSID;
                Recv.CallerNum = it.CallerNum;
                Recv.Content = it.Content;
                if (it.F_UserID > 0)
                {
                    Model.T_Sys_UserAccount ua = sysUserAccountBll.GetModel(int.Parse(it.F_UserID.ToString()));
                    if (ua != null)
                    {
                        Recv.F_UserID = ua.F_UserCode + "(" + ua.F_UserName + ")";
                    }
                }
                else
                {
                    Recv.F_UserID = "";
                }
                Recv.RecvTime = it.RecvTime.ToString();
                SMS.Add(Recv);
            }
            return SMS;
        }
        public class RecvSMS
        {
            public int SMSID;
            public string CallerNum;
            public string Content;
            public string F_UserID;
            public string RecvTime;

        }
        public bool AddSmS(string tel, string cont, int F_UserID,string RecvModemIMEI="")
        {
            Model.T_SMS_RecvSMS dModel = new Model.T_SMS_RecvSMS();
            dModel.CallerNum = tel.Trim();
            dModel.Content = cont.Trim();
            dModel.F_UserID = F_UserID;
            dModel.RecvTime = DateTime.Now;
            dModel.RecvModemIMEI = "";
            int b = new BLL.T_SMS_RecvSMS().Add(dModel);
            if (b > 0)
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        public ActionResult SMSSendSalesman(string name, string phone, string cusphone)
        {
            int userId = CurrentUser.UserData.F_UserId;
            if (userId > 0)
            {
                if (string.IsNullOrEmpty(name))
                    return Error("请输入联系人姓名");
                if (string.IsNullOrEmpty(phone))
                    return Error("请输入联系人电话");
                if (string.IsNullOrEmpty(cusphone))
                    return Error("请输入发送号码");
                string msg = "您好，刚有客户意向购买、咨询产品政策问题，客服已做简单解答，但该区域市场详细的产品价格政策及业务情况，还请您及时与客户联系提供具体服务。客户姓名：" + name + "，电话：" + phone + "。祝您工作顺利!";
                string[] mag = { name, phone };
                SmsSingleSenderResult result = SMSSingleshot(433866, mag, cusphone);

                if (result != null)
                {

                    AddSmS(cusphone, msg, userId);
                    return Success("发送短信", result);

                }
                else
                {
                    return Error("发送失败，请检查电话");
                }
            }
            else
            {
                return Error("无操作权限");
            }
        }
        /// <summary>
        /// 单发短信
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="cont"></param>
        public SmsSingleSenderResult SMSSingleshot(string  phone,string  cont)
        {
            string sms = Configs.GetValue("sms");
            if (sms == "1")
            {
                try
                {
                    SmsSingleSender ssender = new SmsSingleSender(appid, appkey);
                    var result = ssender.send(0, "86", phone,
                  cont, "", "");
                    Console.WriteLine(result);
                    return result;
                }
                catch (JSONException e)
                {
                    Console.WriteLine(e);
                    return null;
                }
                catch (HTTPException e)
                {
                    Console.WriteLine(e);
                    return null;
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    return null;
                }
            }
            else
                return null;
        }
        /// <summary>
        /// 单发短信
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="cont"></param>
        public SmsSingleSenderResult SMSSingleshot(int templateId, string [] msg,string cusphone)
        {
            string sms = Configs.GetValue("sms");
            if (sms == "1")
            {
                try
                {
                    SmsSingleSender ssender = new SmsSingleSender(appid, appkey);
                    var result = ssender.sendWithParam("86", cusphone,
                        templateId, msg, smsSign, "", "");
                    return result;
                }
                catch (JSONException e)
                {
                    Console.WriteLine(e);
                    return null;
                }
                catch (HTTPException e)
                {
                    Console.WriteLine(e);
                    return null;
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    return null;
                }
            }
            else
                return null;
           
        }
        /// <summary>
        /// 群发短信
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="cont"></param>
        public SmsMultiSenderResult SMSGroupSending(string[] phone, string cont)
        {
            try
            {
                SmsMultiSender msender = new SmsMultiSender(appid, appkey);
                var result = msender.send(0, "86", phone,
                   cont, "", "");
                Console.WriteLine(result);
                return result;
            }
            catch (JSONException e)
            {
                Console.WriteLine(e);
                return null;
            }
            catch (HTTPException e)
            {
                Console.WriteLine(e);
                return null;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return null;
            }
        }
        /// <summary>
        /// int beginTime = 1511125600;  // 开始时间（UNIX timestamp）
        ///  int endTime = 1511841600;    // 结束时间（UNIX timestamp）
        ///   int maxNum = 10;             // 单次拉取最大量
        ///   拉取单个手机回执
        /// </summary>
        /// <param name="beginTime"></param>
        public SmsStatusPullCallbackResult SMSSingleReceipt(int maxNum = 10)
        {
            try
            {
                // Note: 短信拉取功能需要联系腾讯云短信技术支持（QQ：3012203387）开通权限
                SmsStatusPuller spuller = new SmsStatusPuller(appid, appkey);
                // 拉取短信回执
                var callbackResult = spuller.pullCallback(maxNum);
                Console.WriteLine(callbackResult);
                return callbackResult;
            }
            catch (JSONException e)
            {
                Console.WriteLine(e);
                return null;
            }
            catch (HTTPException e)
            {
                Console.WriteLine(e);
                return null;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return null;
            }
        }
        /// <summary>
        /// 短信拉取
        /// </summary>
        /// <returns></returns>
        BLL.T_Wo_MaterialManage mmBLL = new BLL.T_Wo_MaterialManage();
        public ActionResult SMSReply()
        {
            Model.T_Wo_MaterialManage dModel = new Model.T_Wo_MaterialManage();
           
            SmsStatusPullReplyResult result = SMSSingleReply(1);
            if (result != null)
            {
                return Success("短信测试", result);
            }
            else
            {
                return null;
            }
        }
        BLL.T_Wo_WorkOrder workOrder = new BLL.T_Wo_WorkOrder();
        /// <summary>
        /// int beginTime = 1511125600;  // 开始时间（UNIX timestamp）
        ///  int endTime = 1511841600;    // 结束时间（UNIX timestamp）
        ///   int maxNum = 10;             // 单次拉取最大量
        ///   拉取手机回复
        /// </summary>
        /// <param name="beginTime"></param>
        public SmsStatusPullReplyResult SMSSingleReply( int maxNum=1)
        {
            try
            {
               
                SmsStatusPuller spuller = new SmsStatusPuller(appid, appkey);
                // 拉取短信回执
                var callbackResult = spuller.pullCallback(maxNum);
                Console.WriteLine(callbackResult);
                // 拉取回复，仅国内短信支持拉取回复状态
                var replyResult = spuller.pullReply(maxNum);
                if (callbackResult != null )
                {
                    if (callbackResult.callbacks.Count >0)
                    {
                        for (int i=0;i< callbackResult.callbacks.Count;i++)
                        {
                            if (!string .IsNullOrEmpty (callbackResult.callbacks[i ].sid .Trim ()))
                            {
                                Model.T_Wo_WorkOrder model = new BLL.T_Wo_WorkOrder().GetModelSid(callbackResult.callbacks[i].sid.Trim());
                                if (model !=null )
                                {
                                    try
                                    {
                                        model.F_SMSReply = int.Parse(replyResult.replys[i].text);
                                        AddSmS(replyResult.replys[i].mobile, replyResult.replys[i].text, 0,"1");
                                        workOrder.Update(model);
                                        string msg = "【心连心客服中心】您好，心连心感谢您的评价，祝您生活愉快！";
                                        SMSSingleshot(replyResult.replys[i].mobile, msg);
                                        string mag = "心连心感谢您的评价，祝你生活愉快！";
                                        AddSmS(replyResult.replys[i].mobile, mag, 0);
                                    }
                                    catch
                                    {
                                        model.F_SMSReply =0;
                                    }
                                   
                                   
                                }
                            }
                           
                        }
                    }
                   
                }
              
                Console.WriteLine(replyResult);
                return replyResult;
            }
            catch (JSONException e)
            {
                Console.WriteLine(e);
                return null;
            }
            catch (HTTPException e)
            {
                Console.WriteLine(e);
                return null;
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return null;
            }
        }

        //    /// <summary>
        //    /// 新增接收短信
        //    /// </summary>
        //    /// <returns></returns>
        //    public ActionResult AddRecv(string tel,string cont)
        //    {
        //        ActionResult res = NoToken("未知错误，请重新登录");

        //            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;
        //            dModel.F_CreateDate = DateTime.Now;
        //            int b = new BLL.T_SMS_RecvSMS().Add(dModel);
        //            if (b > 0)
        //            {
        //                res = Success("添加成功");
        //            }
        //            else
        //            {
        //                res = Success("添加失败");
        //            }

        //        return res;
        //    }
        #region 

        ////    /// <summary>
        ////    /// 获取接收短信列表
        ////    /// </summary>
        ////    /// <returns></returns>
        ////    public ActionResult GetRecvList()
        ////    {
        ////        ActionResult res = NoToken("未知错误，请重新登录");
        ////        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"));

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

        ////            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 (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);

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

        ////            res = Content(obj.ToJson());

        ////        return res;
        ////    }

        ////    /// <summary>
        ////    /// 新增接收短信
        ////    /// </summary>
        ////    /// <returns></returns>
        ////    public ActionResult AddRecv(string tel,string cont)
        ////    {
        ////        ActionResult res = NoToken("未知错误，请重新登录");

        ////            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;
        ////            dModel.F_CreateDate = DateTime.Now;
        ////            int b = new BLL.T_SMS_RecvSMS().Add(dModel);
        ////            if (b > 0)
        ////            {
        ////                res = Success("添加成功");
        ////            }
        ////            else
        ////            {
        ////                res = Success("添加失败");
        ////            }

        ////        return res;
        ////    }

        ////    /// <summary>
        ////    /// 删除接收短信
        ////    /// </summary>
        ////    /// <param name="ids"></param>
        ////    /// <returns></returns>
        ////    public ActionResult DelRecv(string[] ids)
        ////    {
        ////        ActionResult res = NoToken("未知错误，请重新登录");

        ////            if (ids != null && ids.Length > 0)
        ////            {
        ////                string idd = " ";
        ////                foreach (string str in ids)
        ////                {
        ////                    idd += str + ",";
        ////                }
        ////                if (new BLL.T_SMS_RecvSMS().DeleteList(idd.TrimEnd(',')))
        ////                {
        ////                    res = Success("删除成功");
        ////                }
        ////                else
        ////                {
        ////                    res = Error("删除失败");
        ////                }
        ////            }
        ////            else
        ////            {
        ////                res = Error("请选择要删除的接收短信");
        ////            }

        ////        return res;
        ////    }

        ////    #endregion

        ////    #region 发送短信

        ////    /// <summary>
        ////    /// 获取发送短信任务列表
        ////    /// </summary>
        ////    /// <returns></returns>
        ////    public ActionResult GetSendTaskList()
        ////    {
        ////        ActionResult res = NoToken("未知错误，请重新登录");
        ////        string sql = "";
        ////        DataTable dt = new DataTable();

        ////            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 (strstarttime.Trim() != "" && strstarttime != "undefined")
        ////            {
        ////                sql += " and F_CreateDate >= '" + Convert.ToDateTime(strstarttime.Trim()) + "' ";
        ////            }
        ////            if (strendtime.Trim() != "" && strendtime != "undefined")
        ////            {
        ////                sql += " and F_CreateDate <= '" + 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
        ////            };

        ////            res = Content(obj.ToJson()); ;

        ////        return res;
        ////    }

        ////    /// <summary>
        ////    /// 新增短信任务
        ////    /// </summary>
        ////    /// <returns></returns>
        ////    public ActionResult AddSendTask()
        ////    {
        ////        ActionResult res = NoToken("未知错误，请重新登录");

        ////            string strid = HttpUtility.UrlDecode(RequestString.GetQueryString("id"));
        ////            string strname = HttpUtility.UrlDecode(RequestString.GetQueryString("name"));
        ////            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
        ////            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));
        ////            string strstarttime1 = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime1"));
        ////            string strendtime1 = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime1"));
        ////            string strstarttime2 = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime2"));
        ////            string strendtime2 = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime2"));
        ////            string strsignname = HttpUtility.UrlDecode(RequestString.GetQueryString("signname"));
        ////            string strtempcode = HttpUtility.UrlDecode(RequestString.GetQueryString("tempcode"));

        ////            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);
        ////                dModel.Name = strname.Trim();
        ////                if (!string.IsNullOrEmpty(strstarttime))
        ////                {
        ////                    dModel.StartTime = DateTime.Parse(strstarttime);
        ////                }
        ////                else
        ////                {
        ////                    dModel.StartTime = null;
        ////                }
        ////                if (!string.IsNullOrEmpty(strendtime))
        ////                {
        ////                    dModel.EndTime = DateTime.Parse(strendtime);
        ////                }
        ////                else
        ////                {
        ////                    dModel.EndTime = null;
        ////                }
        ////                dModel.PeriodStartTime = strstarttime1;
        ////                dModel.PeriodEndTime = strendtime1;
        ////                dModel.PeriodStartTime1 = strstarttime2;
        ////                dModel.PeriodEndTime1 = strendtime2;
        ////                dModel.SignName = strsignname;
        ////                dModel.TempCode = strtempcode;
        ////                if (dModel.State == 1) { dModel.State = 0; }//短信服务
        ////                if (new BLL.T_SMS_SendSMSTask().Update(dModel))
        ////                {
        ////                    res = Success("修改成功");
        ////                }
        ////                else
        ////                {
        ////                    res = Success("修改失败");
        ////                }
        ////            }
        ////            else
        ////            {
        ////                dModel.Name = strname.Trim();
        ////                if (!string.IsNullOrEmpty(strstarttime))
        ////                {
        ////                    dModel.StartTime = DateTime.Parse(strstarttime);
        ////                }
        ////                if (!string.IsNullOrEmpty(strendtime))
        ////                {
        ////                    dModel.EndTime = DateTime.Parse(strendtime);
        ////                }
        ////                dModel.PeriodStartTime = strstarttime1;
        ////                dModel.PeriodEndTime = strendtime1;
        ////                dModel.PeriodStartTime1 = strstarttime2;
        ////                dModel.PeriodEndTime1 = strendtime2;
        ////                dModel.SignName = strsignname;
        ////                dModel.TempCode = strtempcode;
        ////                dModel.State = 0;
        ////                dModel.F_CreateDate = DateTime.Now;
        ////                int b = new BLL.T_SMS_SendSMSTask().Add(dModel);
        ////                if (b > 0)
        ////                {
        ////                    res = Success("添加成功");
        ////                }
        ////                else
        ////                {
        ////                    res = Success("添加失败");
        ////                }
        ////            }

        ////        return res;
        ////    }

        ////    /// <summary>
        ////    /// 删除短信任务
        ////    /// </summary>
        ////    /// <param name="ids"></param>
        ////    /// <returns></returns>
        ////    public ActionResult DelSendTask(string[] ids)
        ////    {
        ////        ActionResult res = NoToken("未知错误，请重新登录");

        ////            if (ids != null && ids.Length > 0)
        ////            {
        ////                string idd = " ";
        ////                foreach (string str in ids)
        ////                {
        ////                    idd += str + ",";
        ////                }
        ////                if (new BLL.T_SMS_SendSMSTask().DeleteList(idd.TrimEnd(',')))
        ////                {
        ////                    res = Success("删除成功");
        ////                }
        ////                else
        ////                {
        ////                    res = Error("删除失败");
        ////                }
        ////            }
        ////            else
        ////            {
        ////                res = Error("请选择要删除的短信任务");
        ////            }

        ////        return res;
        ////    }

        ////    /// <summary>
        ////    /// 获取发送短信列表
        ////    /// </summary>
        ////    /// <returns></returns>
        ////    public ActionResult GetSendList()
        ////    {
        ////        ActionResult res = NoToken("未知错误，请重新登录");
        ////        string sql = "";
        ////        DataTable dt = new DataTable();

        ////            int taskid = 0;
        ////            string strtaskid = HttpUtility.UrlDecode(RequestString.GetQueryString("id"));
        ////            string strtel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
        ////            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 (strtaskid != "" && strtaskid != "undefined")
        ////            {
        ////                taskid = Convert.ToInt32(strtaskid);
        ////            }
        ////            if (strtel.Trim() != "" && strtel != "undefined")
        ////            {
        ////                sql += " and TelNum= '" + strtel.Trim() + "' ";
        ////            }
        ////            if (strstarttime.Trim() != "" && strstarttime != "undefined")
        ////            {
        ////                sql += " and F_CreateDate >= '" + Convert.ToDateTime(strstarttime.Trim()) + "' ";
        ////            }
        ////            if (strendtime.Trim() != "" && strendtime != "undefined")
        ////            {
        ////                sql += " and F_CreateDate <= '" + 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
        ////            };

        ////            res = Content(obj.ToJson()); ;

        ////        return res;
        ////    }

        ////    /// <summary>
        ////    /// 新增短信
        ////    /// </summary>
        ////    /// <returns></returns>
        ////    public ActionResult AddSend(string id,string taskid,string tel,string cont)
        ////    {
        ////        ActionResult res = NoToken("未知错误，请重新登录");
        ////            Model.T_SMS_SentSMS dModel = new Model.T_SMS_SentSMS();
        ////            if (id != "")
        ////            {
        ////                int sid = Int32.Parse(id);
        ////                dModel = new BLL.T_SMS_SentSMS().GetModel(sid);
        ////                dModel.TelNum = tel.Trim();
        ////                dModel.Content = cont;

        ////                if (new BLL.T_SMS_SentSMS().Update(dModel))
        ////                {
        ////                    res = Success("修改成功");
        ////                }
        ////                else
        ////                {
        ////                    res = Success("修改失败");
        ////                }
        ////            }
        ////            else
        ////            {
        ////                dModel.TaskID = Int32.Parse(taskid);
        ////                dModel.TelNum = tel.Trim();
        ////                dModel.Content = cont;
        ////                dModel.State = 0;
        ////                dModel.F_CreateDate = DateTime.Now;
        ////                int b = new BLL.T_SMS_SentSMS().Add(dModel);
        ////                if (b > 0)
        ////                {
        ////                    res = Success("添加成功");
        ////                }
        ////                else
        ////                {
        ////                    res = Success("添加失败");
        ////                }
        ////            }

        ////        return res;
        ////    }

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

        ////        return res;
        ////    }

        ////    /// <summary>
        ////    /// 导入短信
        ////    /// </summary>
        ////    /// <returns></returns>
        ////    public ActionResult ImportSend()
        ////    {
        ////        ActionResult res = NoToken("未知错误，请重新登录");
        ////        if (Request.IsAuthenticated)
        ////        {

        ////                int userId = CurrentUser.UserData.F_UserId;
        ////                if (userId != 0)
        ////                {
        ////                    Model.T_Sys_UserAccount userModel = new BLL.T_Sys_UserAccount().GetModel(userId);
        ////                    if (userModel != null)
        ////                    {
        ////                        HttpPostedFile _upfile = RequestString.GetFile("upFile");
        ////                        int taskid = RequestString.GetInt("taskid", 0);
        ////                        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_SentSMS dModel = new Model.T_SMS_SentSMS();
        ////                                dModel.TaskID = taskid;
        ////                                dModel.TelNum = dr[0].ToString();
        ////                                dModel.Content = dr[1].ToString();
        ////                                dModel.State = 0;
        ////                                dModel.F_UserID = userModel.F_UserId;
        ////                                dModel.F_Name = userModel.F_UserName;
        ////                                dModel.F_CreateDate = DateTime.Now;

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

        ////        }
        ////        return res;
        ////    }

        ////    #endregion

        ////    #region 短信服务

        ////    /// <summary>
        ////    /// 获取发送短信列表
        ////    /// </summary>
        ////    /// <returns></returns>
        ////    public ActionResult GetSendTaskListByJob(string state, string count)
        ////    {
        ////        ActionResult res = NoToken("未知错误，请重新登录");
        ////        DataTable dt = new DataTable();

        ////            string str = "";
        ////            if (!string.IsNullOrEmpty(count))
        ////            {
        ////                int ct = Int32.Parse(count);
        ////                str = "top " + ct;
        ////            }

        ////            dt = DB.DbHelperSQL.Query(" select " + str + " * from T_SMS_SendSMSTask where isnull(State,0)='" + state + "' and getdate() between isnull(StartTime,'1900-01-01 00:00:00') and isnull(EndTime,'9999-12-31 23:59:59')  order by F_CreateDate ").Tables[0];

        ////            res = Success("成功", dt);

        ////        return res;
        ////    }

        ////    /// <summary>
        ////    /// 获取发送短信列表
        ////    /// </summary>
        ////    /// <returns></returns>
        ////    public ActionResult GetSendListByJob(string taskid, string count)
        ////    {
        ////        ActionResult res = NoToken("未知错误，请重新登录");
        ////        DataTable dt = new DataTable();

        ////            string str = "";
        ////            if (!string.IsNullOrEmpty(count))
        ////            {
        ////                int ct = Int32.Parse(count);
        ////                str = "top " + ct;
        ////            }
        ////            //dt = DB.DbHelperSQL.Query(" select top "+ ct+ " s.*,t.PeriodStartTime,t.PeriodStartTime1,t.PeriodEndTime,t.PeriodEndTime1 from T_SMS_SentSMS s left join T_SMS_SendSMSTask t on s.TaskID=t.SMSID where isnull(s.State,0)=0 and getdate() between t.StartTime and  t.EndTime order by s.F_CreateDate ").Tables[0];
        ////            dt = DB.DbHelperSQL.Query(" select " + str + " * from T_SMS_SentSMS where TaskID='" + taskid + "' and isnull(State,0)='0' order by F_CreateDate ").Tables[0];

        ////            res = Success("成功", dt);

        ////        return res;
        ////    }

        ////    /// <summary>
        ////    /// 执行发送短信
        ////    /// </summary>
        ////    /// <returns></returns>
        ////    public ActionResult ExecSMSByJob(string taskid, string count)
        ////    {
        ////        ActionResult res = NoToken("未知错误，请重新登录");
        ////        DataTable dt = new DataTable();

        ////            string tels = string.Empty;
        ////            string errtels = string.Empty;
        ////            string isdel = string.Empty;
        ////            string str = string.Empty;
        ////            if (!string.IsNullOrEmpty(count))
        ////            {
        ////                int ct = Int32.Parse(count);
        ////                str = "top " + ct;
        ////            }
        ////            var task = new BLL.T_SMS_SendSMSTask().GetModel(Int32.Parse(taskid));
        ////            if (task != null)
        ////            {
        ////                bool bl = true;
        ////                DateTime dte = DateTime.Now;
        ////                if (task.StartTime != null)
        ////                {
        ////                    bl = dte >= task.StartTime.Value;
        ////                }
        ////                if (bl && task.EndTime != null)
        ////                {
        ////                    bl = dte <= task.EndTime.Value;
        ////                }
        ////                if (bl)
        ////                {
        ////                    //dt = DB.DbHelperSQL.Query(" select top "+ ct+ " s.*,t.PeriodStartTime,t.PeriodStartTime1,t.PeriodEndTime,t.PeriodEndTime1 from T_SMS_SentSMS s left join T_SMS_SendSMSTask t on s.TaskID=t.SMSID where isnull(s.State,0)=0 and getdate() between t.StartTime and  t.EndTime order by s.F_CreateDate ").Tables[0];
        ////                    dt = DB.DbHelperSQL.Query(" select " + str + " * from T_SMS_SentSMS where TaskID='" + task.SMSID + "' and isnull(State,0)=0 order by F_CreateDate ").Tables[0];

        ////                    foreach (DataRow dr in dt.Rows)
        ////                    {
        ////                        string err = SendSMS(dr["TelNum"].ToString(), dr["Content"].ToString(), task.SignName, task.TempCode);
        ////                        if (err == "")
        ////                        {
        ////                            UpdateSendState(dr["SMSID"].ToString());
        ////                            if (string.IsNullOrEmpty(tels))
        ////                            {
        ////                                tels = dr["TelNum"].ToString();
        ////                            }
        ////                            else
        ////                            {
        ////                                tels = tels + "," + dr["TelNum"].ToString();
        ////                            }
        ////                        }
        ////                        else
        ////                        {
        ////                            if (string.IsNullOrEmpty(tels))
        ////                            {
        ////                                errtels = dr["TelNum"].ToString();
        ////                            }
        ////                            else
        ////                            {
        ////                                errtels = errtels + "," + dr["TelNum"].ToString();
        ////                            }
        ////                        }
        ////                    }
        ////                    isdel = "0";
        ////                }
        ////                else
        ////                {
        ////                    isdel = "1";
        ////                }
        ////            }
        ////            else
        ////            {
        ////                isdel = "1";
        ////            }

        ////            res = Success("成功", new { suc = tels, err = errtels, isdel = isdel });

        ////        return res;
        ////    }

        ////    /// <summary>
        ////    /// 根据结束时间结束任务
        ////    /// </summary>
        ////    /// <returns></returns>
        ////    public ActionResult EndSMSTask()
        ////    {
        ////        ActionResult res = NoToken("未知错误，请重新登录");

        ////            string str = string.Empty;
        ////            string strerr = string.Empty;
        ////            BLL.T_SMS_SendSMSTask bll = new BLL.T_SMS_SendSMSTask();
        ////            var list = bll.GetModelList(" isnull(State,0)=1 ");
        ////            foreach (var l in list)
        ////            {
        ////                if (l.EndTime <= DateTime.Now)
        ////                {
        ////                    l.State = 9;
        ////                    if (bll.Update(l))
        ////                    {
        ////                        if (string.IsNullOrEmpty(str))
        ////                        {
        ////                            str = l.SMSID.ToString();
        ////                        }
        ////                        else
        ////                        {
        ////                            str = str + "," + l.SMSID.ToString();
        ////                        }
        ////                    }
        ////                    else
        ////                    {
        ////                        if (string.IsNullOrEmpty(strerr))
        ////                        {
        ////                            strerr = l.SMSID.ToString();
        ////                        }
        ////                        else
        ////                        {
        ////                            strerr = strerr + "," + l.SMSID.ToString();
        ////                        }
        ////                    }
        ////                }
        ////            }
        ////            res = Success("成功", new { suc = str, err = strerr});

        ////        return res;
        ////    }

        ////    /// <summary>
        ////    /// 短信服务停止后重置正在执行的任务
        ////    /// </summary>
        ////    /// <returns></returns>
        ////    public ActionResult ResetSMSTask()
        ////    {
        ////        ActionResult res = NoToken("未知错误，请重新登录");

        ////            string str = string.Empty;
        ////            string strerr = string.Empty;
        ////            BLL.T_SMS_SendSMSTask bll = new BLL.T_SMS_SendSMSTask();
        ////            var list = bll.GetModelList(" isnull(State,0)=1 ");
        ////            foreach (var l in list)
        ////            {
        ////                l.State = 0;
        ////                if (bll.Update(l))
        ////                {
        ////                    if (string.IsNullOrEmpty(str))
        ////                    {
        ////                        str = l.SMSID.ToString();
        ////                    }
        ////                    else
        ////                    {
        ////                        str = str + "," + l.SMSID.ToString();
        ////                    }
        ////                }
        ////                else
        ////                {
        ////                    if (string.IsNullOrEmpty(strerr))
        ////                    {
        ////                        strerr = l.SMSID.ToString();
        ////                    }
        ////                    else
        ////                    {
        ////                        strerr = strerr + "," + l.SMSID.ToString();
        ////                    }
        ////                }
        ////            }
        ////            res = Success("成功", new { suc = str, err = strerr });

        ////        return res;
        ////    }

        ////    /// <summary>
        ////    /// 更新短信发送状态
        ////    /// </summary>
        ////    /// <returns></returns>
        ////    public ActionResult UpdateSendTaskState(string id, string state)
        ////    {
        ////        ActionResult res = NoToken("未知错误，请重新登录");

        ////            Model.T_SMS_SendSMSTask dModel = new Model.T_SMS_SendSMSTask();
        ////            if (id != "")
        ////            {
        ////                int sid = Int32.Parse(id);
        ////                dModel = new BLL.T_SMS_SendSMSTask().GetModel(sid);
        ////                if (dModel != null)
        ////                {
        ////                    dModel.State = Int32.Parse(state);

        ////                    if (new BLL.T_SMS_SendSMSTask().Update(dModel))
        ////                    {
        ////                        res = Success("修改成功");
        ////                    }
        ////                    else
        ////                    {
        ////                        res = Success("修改失败");
        ////                    }
        ////                }
        ////            }

        ////        return res;
        ////    }

        ////    /// <summary>
        ////    /// 更新短信发送状态
        ////    /// </summary>
        ////    /// <returns></returns>
        ////    public ActionResult UpdateSendState(string id)
        ////    {
        ////        ActionResult res = NoToken("未知错误，请重新登录");


        ////            Model.T_SMS_SentSMS dModel = new Model.T_SMS_SentSMS();
        ////            if (id != "")
        ////            {
        ////                int sid = Int32.Parse(id);
        ////                dModel = new BLL.T_SMS_SentSMS().GetModel(sid);
        ////                if (dModel != null && dModel.State == 0)
        ////                {
        ////                    dModel.State = 1;
        ////                    dModel.SendTime = DateTime.Now;

        ////                    if (new BLL.T_SMS_SentSMS().Update(dModel))
        ////                    {
        ////                        res = Success("修改成功");
        ////                    }
        ////                    else
        ////                    {
        ////                        res = Success("修改失败");
        ////                    }
        ////                }
        ////            }

        ////        return res;
        ////    } 

        ////    #endregion

        ////    #region 发送短信接口

        ////    /// <summary>
        ////    /// 发送短信接口
        ////    /// </summary>
        ////    /// <returns></returns>
        ////    public ActionResult SentSMS()
        ////    {
        ////        //调用示例--/sms/sendsms?tel=15512345678,15812341234&cont={"name":"张三","time":"11:00"}&signname=活动验证&tempcode=SMS_40865007
        ////        ActionResult res = NoToken("未知错误，请重新登录");

        ////            string signname = HttpUtility.UrlDecode(RequestString.GetQueryString("signname"));//"活动验证";
        ////            string tempcode = HttpUtility.UrlDecode(RequestString.GetQueryString("tempcode"));//"SMS_40865007";

        ////            string tel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));//多个用 , 隔开
        ////            string cont = HttpUtility.UrlDecode(RequestString.GetQueryString("cont"));

        ////            string err = SendSMS(tel, cont, signname, tempcode);
        ////            if (err == "")
        ////            {
        ////                res = Success("成功");
        ////            }
        ////            else
        ////            {
        ////                res = Error(err);
        ////            }

        ////        return res;
        ////    }

        ////    /// <summary>
        ////    /// 发送短信
        ////    /// </summary>
        ////    /// <param name="tel"></param>
        ////    /// <param name="cont"></param>
        ////    /// <param name="signname"></param>
        ////    /// <param name="tempcode"></param>
        ////    /// <returns></returns>
        ////    public string SendSMS(string tel, string cont, string signname, string tempcode)
        ////    {
        ////        string res = string.Empty;
        ////        string url = ConfigurationManager.AppSettings["url"];
        ////        string key = ConfigurationManager.AppSettings["key"];
        ////        string secret = ConfigurationManager.AppSettings["secret"];

        ////        try
        ////        {
        ////            ITopClient client = new DefaultTopClient(url, key, secret);
        ////            AlibabaAliqinFcSmsNumSendRequest req = new AlibabaAliqinFcSmsNumSendRequest();
        ////            req.Extend = "123456";//公共回传参数
        ////            req.SmsType = "normal";//短信类型，传入值请填写normal
        ////            req.SmsFreeSignName = signname;//签名 
        ////            req.SmsParam = cont; //短信模参数示例: "{\"name\":\"张三\",\"time\":\"11:00\"}";
        ////            req.RecNum = tel; //短信接收号码
        ////            req.SmsTemplateCode = tempcode;//短信模板ID

        ////                AlibabaAliqinFcSmsNumSendResponse rsp = client.Execute(req);
        ////                if (!rsp.IsError)
        ////                {
        ////                    if (!rsp.Result.Success)
        ////                    {
        ////                        res = rsp.Result.Msg;
        ////                    }
        ////                }
        ////                else
        ////                {
        ////                    if (!string.IsNullOrEmpty(rsp.SubErrMsg))
        ////                    {
        ////                        res = rsp.SubErrMsg;
        ////                    }
        ////                    else
        ////                    {
        ////                        res = rsp.ErrMsg;
        ////                    }
        ////                }
        ////            }
        ////            catch
        ////            {
        ////                res = "接口异常！";
        ////            }

        ////        return res;
        ////    }

        #endregion

    }
}

