
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using CallCenterApi.Interface.Controllers.Base;
using System.Data;
using CallCenter.Utility;
using System.Configuration;
using Top.Api;
using Top.Api.Request;
using Top.Api.Response;
using CallCenterApi.Common;

namespace CallCenterApi.Interface.Controllers
{
    public class SMSController : BaseController
    {
        #region 接收短信

        /// <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()) + "' ";
            }

            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
            };

            return Content(obj.ToJson());
        }

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

        /// <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("请选择要删除的接收短信");
            }
        }

        #endregion

        #region 发送短信

        /// <summary>
        /// 获取发送短信任务列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetSendTaskList()
        {
            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
            };

            return Content(obj.ToJson());
        }

        /// <summary>
        /// 新增短信任务
        /// </summary>
        /// <returns></returns>
        public ActionResult AddSendTask()
        {
            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))
                {
                    return Success("修改成功");
                }
                else
                {
                    return 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)
                {
                    return Success("添加成功");
                }
                else
                {
                    return Success("添加失败");
                }
            }
        }

        /// <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("请选择要删除的短信任务");
            }
        }

        /// <summary>
        /// 获取发送短信列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetSendList()
        {
            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
            };

            return Content(obj.ToJson());
        }

        /// <summary>
        /// 新增短信
        /// </summary>
        /// <returns></returns>
        public ActionResult AddSend(string id, string taskid, string tel, string cont)
        {
            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))
                {
                    return Success("修改成功");
                }
                else
                {
                    return 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)
                {
                    return Success("添加成功");
                }
                else
                {
                    return Success("添加失败");
                }
            }
        }

        /// <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("请选择要删除的短信");
            }

        }

        /// <summary>
        /// 导入短信
        /// </summary>
        /// <returns></returns>
        public ActionResult ImportSend()
        {
            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 = CurrentUser.UserData.F_UserId;
                    dModel.F_Name = CurrentUser.UserData.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))
            {
                return Error(msg);
            }
            else
            {
                return Success("导入成功");
            }
        }

        #endregion

        #region 短信服务

        /// <summary>
        /// 获取发送短信列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetSendTaskListByJob(string state, string count)
        {
            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];

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

        /// <summary>
        /// 获取发送短信列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetSendListByJob(string taskid, string count)
        {
            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];

            return Success("成功", dt);

        }

        /// <summary>
        /// 执行发送短信
        /// </summary>
        /// <returns></returns>
        public ActionResult ExecSMSByJob(string taskid, string count)
        {
            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";
            }

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

        }

        /// <summary>
        /// 根据结束时间结束任务
        /// </summary>
        /// <returns></returns>
        public ActionResult EndSMSTask()
        {

            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();
                        }
                    }
                }
            }
            return Success("成功", new { suc = str, err = strerr });

        }

        /// <summary>
        /// 短信服务停止后重置正在执行的任务
        /// </summary>
        /// <returns></returns>
        public ActionResult ResetSMSTask()
        {

            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();
                    }
                }
            }
            return Success("成功", new { suc = str, err = strerr });

        }

        /// <summary>
        /// 更新短信发送状态
        /// </summary>
        /// <returns></returns>
        public ActionResult UpdateSendTaskState(string id, string state)
        {
            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))
                    {
                        return Success("修改成功");
                    }
                    else
                    {
                        return Error("修改失败");
                    }
                }
                else
                {
                    return Error("修改失败");
                }
            }
            else
            {
                return Error("修改失败");
            }
        }

        /// <summary>
        /// 更新短信发送状态
        /// </summary>
        /// <returns></returns>
        public ActionResult UpdateSendState(string id)
        {

            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))
                    {
                        return Success("修改成功");
                    }
                    else
                    {
                        return Error("修改失败");
                    }
                }
                else
                {
                    return Error("修改失败");
                }
            }
            else
            {
                return Error("修改失败");
            }
        }

        #endregion

        #region 发送短信接口

        /// <summary>
        /// 发送短信接口
        /// </summary>
        /// <returns></returns>
        public ActionResult SentSMS()
        {
            //调用示例--/sms/sendsms?tel=15512345678,15812341234&cont={"name":"张三","time":"11:00"}&signname=活动验证&tempcode=SMS_40865007

            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 == "")
            {
                return Success("成功");
            }
            else
            {
                return Error(err);
            }

        }

        /// <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)
                    {
                        return rsp.Result.Msg;
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(rsp.SubErrMsg))
                    {
                        return rsp.SubErrMsg;
                    }
                    else
                    {
                        return rsp.ErrMsg;
                    }
                }
            }
            catch
            {
                return "接口异常！";
            }

            return res;
        }

        #endregion
    }
}