using CallCenter.Utility;
using CallCenterApi.Common;
using CallCenterApi.DB;
using CallCenterApi.Interface.Controllers.Base;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using qcloudsms_csharp;
using qcloudsms_csharp.httpclient;
using qcloudsms_csharp.json;
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.Security;
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Web;
using System.Web.Mvc;
using TencentCloud.Common;
using TencentCloud.Common.Profile;




using TencentCloud.Sms.V20210111;
using TencentCloud.Sms.V20210111.Models;

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

        // 短信应用SDK AppID
        int appid = 1400467981;
        // 短信应用SDK AppKey
        string appkey = "ba3aa1a33da088dac57bcac8ce5f8d41";
        // 需要发送短信的手机号码
        // int templateId = 392016; // NOTE: 这里的模板ID`7839`只是一个示例，真实的模板ID需要在短信控制台中申请
        // 签名
        string smsSign = "巩义市网络舆情研究中心"; // NOTE: 这里的签名只是示例，请使用真实的已申请的签名, 签名参数使用的是`签名内容`，而不是`签名ID`
        private static readonly string signName = "巩义市网络舆情研究中心";
        private static readonly string secretId = "AKIDugJkz1qSq21oPrAHH0Zw63rSq33tb9VQ";
        private static readonly string secretKey = "sZ5eDakngNrodJpQtHgDapyueDcpriQC";
        Log log = LogFactory.GetLogger("SMSSingleshot");



        public SendSmsResponse SmsSingle(int templateId,   string[] msg, string mobiles)
        {

            try
            {
                // 必要步骤：
                // 实例化一个认证对象，入参需要传入腾讯云账户密钥对 SecretId，SecretKey。
                // 为了保护密钥安全，建议将密钥设置在环境变量中或者配置文件中。
                // 硬编码密钥到代码中有可能随代码泄露而暴露，有安全隐患，并不推荐。
                // 这里采用的是从环境变量读取的方式，需要在环境变量中先设置这两个值。
                // SecretId、SecretKey 查询：https://console.cloud.tencent.com/cam/capi
                Credential cred = new Credential
                {
                    SecretId = secretId,// Environment.GetEnvironmentVariable("TENCENTCLOUD_SECRET_ID"),
                    SecretKey = secretKey// Environment.GetEnvironmentVariable("TENCENTCLOUD_SECRET_KEY")
                };

                /* 非必要步骤:
                 * 实例化一个客户端配置对象，可以指定超时时间等配置 */
                ClientProfile clientProfile = new ClientProfile();
                /* SDK 默认用TC3-HMAC-SHA256进行签名
                 * 非必要请不要修改这个字段 */
                clientProfile.SignMethod = ClientProfile.SIGN_TC3SHA256;
                /* 非必要步骤
                 * 实例化一个客户端配置对象，可以指定超时时间等配置 */
                HttpProfile httpProfile = new HttpProfile();
                /* SDK默认使用POST方法。
                 * 如果您一定要使用GET方法，可以在这里设置。GET方法无法处理一些较大的请求 */
                httpProfile.ReqMethod = "POST";
                httpProfile.Timeout = 10; // 请求连接超时时间，单位为秒(默认60秒)
                /* 指定接入地域域名，默认就近地域接入域名为 sms.tencentcloudapi.com ，也支持指定地域域名访问，例如广州地域的域名为 sms.ap-guangzhou.tencentcloudapi.com */
                httpProfile.Endpoint = "sms.tencentcloudapi.com";
                // 代理服务器，当您的环境下有代理服务器时设定（无需要直接忽略）
                // httpProfile.WebProxy = Environment.GetEnvironmentVariable("HTTPS_PROXY");

                clientProfile.HttpProfile = httpProfile;
                /* 实例化要请求产品(以sms为例)的client对象
                 * 第二个参数是地域信息，可以直接填写字符串ap-guangzhou，支持的地域列表参考 https://cloud.tencent.com/document/api/382/52071#.E5.9C.B0.E5.9F.9F.E5.88.97.E8.A1.A8 */
                SmsClient client = new SmsClient(cred, "ap-beijing", clientProfile);

                /* 实例化一个请求对象，根据调用的接口和实际情况，可以进一步设置请求参数
                 * 您可以直接查询SDK源码确定SendSmsRequest有哪些属性可以设置
                 * 属性可能是基本类型，也可能引用了另一个数据结构
                 * 推荐使用IDE进行开发，可以方便的跳转查阅各个接口和数据结构的文档说明 */
                SendSmsRequest req = new SendSmsRequest();

                /* 基本类型的设置:
                 * SDK采用的是指针风格指定参数，即使对于基本类型您也需要用指针来对参数赋值。
                 * SDK提供对基本类型的指针引用封装函数
                 * 帮助链接：
                 * 短信控制台: https://console.cloud.tencent.com/smsv2
                 * 腾讯云短信小助手: https://cloud.tencent.com/document/product/382/3773#.E6.8A.80.E6.9C.AF.E4.BA.A4.E6.B5.81 */
                /* 短信应用ID: 短信SdkAppId在 [短信控制台] 添加应用后生成的实际SdkAppId，示例如1400006666 */
                // 应用 ID 可前往 [短信控制台](https://console.cloud.tencent.com/smsv2/app-manage) 查看
                req.SmsSdkAppId = "1400467981";// "1304639164";

                /* 短信签名内容: 使用 UTF-8 编码，必须填写已审核通过的签名 */
                // 签名信息可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-sign) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-sign) 的签名管理查看
                req.SignName = signName;

                /* 模板 ID: 必须填写已审核通过的模板 ID */
                // 模板 ID 可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-template) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-template) 的正文模板管理查看
                req.TemplateId = templateId.ToString();// "449739";

                /* 模板参数: 模板参数的个数需要与 TemplateId 对应模板的变量个数保持一致，若无模板参数，则设置为空 */
                req.TemplateParamSet = msg;// new String[] { "DH20250808996" };

                /* 下发手机号码，采用 E.164 标准，+[国家或地区码][手机号]
                 * 示例如：+8613711112222， 其中前面有一个+号 ，86为国家码，13711112222为手机号，最多不要超过200个手机号*/
             
                req.PhoneNumberSet = new String[] { mobiles };

                /* 用户的 session 内容（无需要可忽略）: 可以携带用户侧 ID 等上下文信息，server 会原样返回 */
                //req.SessionContext = "";

                /* 短信码号扩展号（无需要可忽略）: 默认未开通，如需开通请联系 [腾讯云短信小助手] */
                //req.ExtendCode = "";

                /* 国内短信无需填写该项；国际/港澳台短信已申请独立 SenderId 需要填写该字段，默认使用公共 SenderId，无需填写该字段。注：月度使用量达到指定量级可申请独立 SenderId 使用，详情请联系 [腾讯云短信小助手](https://cloud.tencent.com/document/product/382/3773#.E6.8A.80.E6.9C.AF.E4.BA.A4.E6.B5.81)。 */
                //req.SenderId = "";

                SendSmsResponse resp = client.SendSmsSync(req);
                return resp;
                // 输出json格式的字符串回包
                //   Console.WriteLine(AbstractModel.ToJsonString(resp));

                /* 当出现以下错误码时，快速解决方案参考
                 * [FailedOperation.SignatureIncorrectOrUnapproved](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Afailedoperation.signatureincorrectorunapproved-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F)
                 * [FailedOperation.TemplateIncorrectOrUnapproved](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Afailedoperation.templateincorrectorunapproved-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F)
                 * [UnauthorizedOperation.SmsSdkAppIdVerifyFail](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Aunauthorizedoperation.smssdkappidverifyfail-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F)
                 * [UnsupportedOperation.ContainDomesticAndInternationalPhoneNumber](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Aunsupportedoperation.containdomesticandinternationalphonenumber-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F)
                 * 更多错误，可咨询[腾讯云助手](https://tccc.qcloud.com/web/im/index.html#/chat?webAppId=8fa15978f85cb41f7e2ea36920cb3ae1&title=Sms)
                 */
            }
            catch (Exception e)
            {
                log.Error("发送短信失败", e);
                return null;
            }
           
        }


        public SendSmsResponse SmsGroup(int templateId, string[] msg, string[] mobiles)
        {

            try
            {
                // 必要步骤：
                // 实例化一个认证对象，入参需要传入腾讯云账户密钥对 SecretId，SecretKey。
                // 为了保护密钥安全，建议将密钥设置在环境变量中或者配置文件中。
                // 硬编码密钥到代码中有可能随代码泄露而暴露，有安全隐患，并不推荐。
                // 这里采用的是从环境变量读取的方式，需要在环境变量中先设置这两个值。
                // SecretId、SecretKey 查询：https://console.cloud.tencent.com/cam/capi
                Credential cred = new Credential
                {
                    SecretId = secretId,// Environment.GetEnvironmentVariable("TENCENTCLOUD_SECRET_ID"),
                    SecretKey = secretKey// Environment.GetEnvironmentVariable("TENCENTCLOUD_SECRET_KEY")
                };

                /* 非必要步骤:
                 * 实例化一个客户端配置对象，可以指定超时时间等配置 */
                ClientProfile clientProfile = new ClientProfile();
                /* SDK 默认用TC3-HMAC-SHA256进行签名
                 * 非必要请不要修改这个字段 */
                clientProfile.SignMethod = ClientProfile.SIGN_TC3SHA256;
                /* 非必要步骤
                 * 实例化一个客户端配置对象，可以指定超时时间等配置 */
                HttpProfile httpProfile = new HttpProfile();
                /* SDK默认使用POST方法。
                 * 如果您一定要使用GET方法，可以在这里设置。GET方法无法处理一些较大的请求 */
                httpProfile.ReqMethod = "POST";
                httpProfile.Timeout = 10; // 请求连接超时时间，单位为秒(默认60秒)
                /* 指定接入地域域名，默认就近地域接入域名为 sms.tencentcloudapi.com ，也支持指定地域域名访问，例如广州地域的域名为 sms.ap-guangzhou.tencentcloudapi.com */
                httpProfile.Endpoint = "sms.tencentcloudapi.com";
                // 代理服务器，当您的环境下有代理服务器时设定（无需要直接忽略）
                // httpProfile.WebProxy = Environment.GetEnvironmentVariable("HTTPS_PROXY");

                clientProfile.HttpProfile = httpProfile;
                /* 实例化要请求产品(以sms为例)的client对象
                 * 第二个参数是地域信息，可以直接填写字符串ap-guangzhou，支持的地域列表参考 https://cloud.tencent.com/document/api/382/52071#.E5.9C.B0.E5.9F.9F.E5.88.97.E8.A1.A8 */
                SmsClient client = new SmsClient(cred, "ap-beijing", clientProfile);

                /* 实例化一个请求对象，根据调用的接口和实际情况，可以进一步设置请求参数
                 * 您可以直接查询SDK源码确定SendSmsRequest有哪些属性可以设置
                 * 属性可能是基本类型，也可能引用了另一个数据结构
                 * 推荐使用IDE进行开发，可以方便的跳转查阅各个接口和数据结构的文档说明 */
                SendSmsRequest req = new SendSmsRequest();

                /* 基本类型的设置:
                 * SDK采用的是指针风格指定参数，即使对于基本类型您也需要用指针来对参数赋值。
                 * SDK提供对基本类型的指针引用封装函数
                 * 帮助链接：
                 * 短信控制台: https://console.cloud.tencent.com/smsv2
                 * 腾讯云短信小助手: https://cloud.tencent.com/document/product/382/3773#.E6.8A.80.E6.9C.AF.E4.BA.A4.E6.B5.81 */
                /* 短信应用ID: 短信SdkAppId在 [短信控制台] 添加应用后生成的实际SdkAppId，示例如1400006666 */
                // 应用 ID 可前往 [短信控制台](https://console.cloud.tencent.com/smsv2/app-manage) 查看
                req.SmsSdkAppId = "1400467981";// "1304639164";

                /* 短信签名内容: 使用 UTF-8 编码，必须填写已审核通过的签名 */
                // 签名信息可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-sign) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-sign) 的签名管理查看
                req.SignName = signName;

                /* 模板 ID: 必须填写已审核通过的模板 ID */
                // 模板 ID 可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-template) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-template) 的正文模板管理查看
                req.TemplateId = templateId.ToString();// "449739";

                /* 模板参数: 模板参数的个数需要与 TemplateId 对应模板的变量个数保持一致，若无模板参数，则设置为空 */
                req.TemplateParamSet = msg;// new String[] { "DH20250808996" };

                /* 下发手机号码，采用 E.164 标准，+[国家或地区码][手机号]
                 * 示例如：+8613711112222， 其中前面有一个+号 ，86为国家码，13711112222为手机号，最多不要超过200个手机号*/

                req.PhoneNumberSet = mobiles;

                /* 用户的 session 内容（无需要可忽略）: 可以携带用户侧 ID 等上下文信息，server 会原样返回 */
                //req.SessionContext = "";

                /* 短信码号扩展号（无需要可忽略）: 默认未开通，如需开通请联系 [腾讯云短信小助手] */
                //req.ExtendCode = "";

                /* 国内短信无需填写该项；国际/港澳台短信已申请独立 SenderId 需要填写该字段，默认使用公共 SenderId，无需填写该字段。注：月度使用量达到指定量级可申请独立 SenderId 使用，详情请联系 [腾讯云短信小助手](https://cloud.tencent.com/document/product/382/3773#.E6.8A.80.E6.9C.AF.E4.BA.A4.E6.B5.81)。 */
                //req.SenderId = "";

                SendSmsResponse resp = client.SendSmsSync(req);
                return resp;
                // 输出json格式的字符串回包
                //   Console.WriteLine(AbstractModel.ToJsonString(resp));

                /* 当出现以下错误码时，快速解决方案参考
                 * [FailedOperation.SignatureIncorrectOrUnapproved](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Afailedoperation.signatureincorrectorunapproved-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F)
                 * [FailedOperation.TemplateIncorrectOrUnapproved](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Afailedoperation.templateincorrectorunapproved-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F)
                 * [UnauthorizedOperation.SmsSdkAppIdVerifyFail](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Aunauthorizedoperation.smssdkappidverifyfail-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F)
                 * [UnsupportedOperation.ContainDomesticAndInternationalPhoneNumber](https://cloud.tencent.com/document/product/382/9558#.E7.9F.AD.E4.BF.A1.E5.8F.91.E9.80.81.E6.8F.90.E7.A4.BA.EF.BC.9Aunsupportedoperation.containdomesticandinternationalphonenumber-.E5.A6.82.E4.BD.95.E5.A4.84.E7.90.86.EF.BC.9F)
                 * 更多错误，可咨询[腾讯云助手](https://tccc.qcloud.com/web/im/index.html#/chat?webAppId=8fa15978f85cb41f7e2ea36920cb3ae1&title=Sms)
                 */
            }
            catch (Exception e)
            {
                log.Error("发送短信失败", e);
                return null;
            }

        }



        /// <summary>
        /// 单发短信
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="cont"></param>
        public SmsSingleSenderResult SMSSingleshot(int templateId, string[] msg, string cusphone)
        {
            try
            {
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                SmsSingleSender ssender = new SmsSingleSender(appid, appkey);
                var result = ssender.sendWithParam("86", cusphone,
                    templateId, msg, smsSign, "", "");
                return result;
            }
            catch (JSONException e)
            {
                log.Error("发送短信失败", e);
                return null;
            }
            catch (HTTPException e)
            {
                log.Error("发送短信失败", e);
                return null;
            }
            catch (Exception e)
            {
                log.Error("发送短信失败", e);
                return null;
            }
        }
        private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {
            return true; //总是接受  
        }
        /// <summary>
        /// 群发短信
        /// </summary>
        /// <param name="phone"></param>
        /// <param name="cont"></param>
        public SmsMultiSenderResult SMSGroupSending(string[] phone,int templateId, string[] msg)
        {
            try
            {
    
                ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
                SmsMultiSender msender = new SmsMultiSender(appid, appkey);
                var sresult = msender.sendWithParam("86", phone, templateId,
                   msg, smsSign, "", "");
                return sresult;
            }
            catch (JSONException e)
            {
                log.Error("发送短信失败", e);
                return null;
            }
            catch (HTTPException e)
            {
                log.Error("发送短信失败", e);
                return null;
            }
            catch (Exception e)
            {
                log.Error("发送短信失败", e);
                return null;
            }
        }
        /// <summary>
        /// 群发短信
        /// </summary>
        /// <param name="templateId"></param>
        /// <param name="userId"></param>
        /// <param name="count"></param>
        /// <param name="mag"></param>
        /// <param name="mobiles"></param>
        /// <returns></returns>
        public bool AddSmSGroup(int templateId, int userId, string count, string[] mag, string[] mobiles
            ,string mobile)
        {
            //  bool res = false ;
            // string  n = SendSms(msg, mobiles, templetid);
            //  string[] mag = { msg, mobiles };
            string SignName = "巩义市网络舆情研究中心";

            var result = SmsGroup(templateId, mag, mobiles);
           // SmsMultiSenderResult result = SMSGroupSending(mobiles,templateId, mag);
            if (result != null)
            {
                Model.T_SMS_RecvSMS dModel = new Model.T_SMS_RecvSMS();
                dModel.CallerNum = mobile.Trim();
                dModel.Content = count.Trim();
                dModel.RecvModemIMEI = "";
                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;
                }
            }
            else
            {
                return false;
            }

        }


        public  bool   AddSmS(int templateId ,int userId,string count, string[] mag, string mobiles)
        {
            
            try
            {
                var result = SmsSingle(templateId, mag, mobiles);

             //   SmsSingleSenderResult result = SMSSingleshot(templateId, mag, mobiles);
                if (result != null)
                {
                    Model.T_SMS_RecvSMS dModel = new Model.T_SMS_RecvSMS();
                    dModel.CallerNum = mobiles.Trim();
                    dModel.Content = count.Trim();
                    dModel.RecvModemIMEI = "";
                    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;
                    }
                }
                else
                {
                    return false;
                }
            }
            catch(Exception e)
            {
                log.Error(e.Message);
                return false;
            }
            

        }
        #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"));

            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()) + "' ";
            }
            sql += "and F_UserID is not null";
            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.F_Name,
                    usercode = new BLL.T_Sys_UserAccount().GetModel((int)x.F_UserID) != null ? new BLL.T_Sys_UserAccount().GetModel((int)x.F_UserID).F_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 userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            Model.T_Sys_UserAccount userModel = new BLL.T_Sys_UserAccount().GetModel(userId);
            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()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            Model.T_Sys_UserAccount userModel = new BLL.T_Sys_UserAccount().GetModel(userId);
            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 = userModel.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 = userModel.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()
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            Model.T_Sys_UserAccount userModel = new BLL.T_Sys_UserAccount().GetModel(userId);
            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 = userModel.F_UserId;
                    dModel.F_Name = userModel.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
    }
}