using CallCenter.Utility;
using CallCenterApi.Common;
using CallCenterApi.DB;
using CallCenterApi.Interface.Controllers.Base;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace CallCenterApi.Interface.Controllers
{
    public class SMSController : BaseController
    {
        #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()) + "' ";
            }

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

        }

        [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

        #region 短信聊天
        [Authority]
        /// <summary>
        /// 获取短信消息列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetMsgList()
        {
            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 (F_SendTelNum like '%" + strtel.Trim() + "%' or F_RecvTelNum like '%" + strtel.Trim() + "%') ";
            }
            if (strcont.Trim() != "" && strcont != "undefined")
            {
                sql += " and F_Content like '%" + strcont.Trim() + "%' ";
            }
            if (strstarttime.Trim() != "" && strstarttime != "undefined")
            {
                sql += " and F_CreateTime >= '" + Convert.ToDateTime(strstarttime.Trim()) + "' ";
            }
            if (strendtime.Trim() != "" && strendtime != "undefined")
            {
                sql += " and F_CreateTime <= '" + 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_Msg",
                "F_Id",
                "*",
                sql,
                "ORDER BY F_Id 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="uid"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public ActionResult SendSMSMsg(string tel, string msg)
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            Model.T_Sys_UserAccount userModel = new BLL.T_Sys_UserAccount().GetModel(userId);

            //UnicomSGIP.Main.Model.SubmitRequest vSubmitRequest = new UnicomSGIP.Main.Model.SubmitRequest();
            //vSubmitRequest.UserNumber = tel;
            //vSubmitRequest.MessageContent = msg;
            //UnicomSGIP.Base.SocketConfig sc = new UnicomSGIP.Base.SocketConfig();
            //sc.SocketIp= Configs.GetValue("socketip");
            //sc.Port = int.Parse( Configs.GetValue("socketport"));
            //sc.LoginName = Configs.GetValue("acount");
            //sc.Password = Configs.GetValue("password");
            //sc.SourceNode = long.Parse( Configs.GetValue("sourcenum"));
            //sc.SpNumber = Configs.GetValue("spnum");
            //sc.CorpId = Configs.GetValue("corpid");
            //sc.ServiceType = Configs.GetValue("servicetype");
            //sc.ChargeNumber = Configs.GetValue("chargenumber");
            //UnicomSGIP.Main.UnicomSms vUnicomSms = new UnicomSGIP.Main.UnicomSms();
            //string Result = vUnicomSms.SendSms(vSubmitRequest, sc);
            string Result = "";

            if (Result == tel + ":成功|")
            {
                var msgmodel = new Model.T_SMS_Msg();
                msgmodel.F_RecvTelNum = tel;
                msgmodel.F_Content = msg;
                msgmodel.F_SendTelNum = userModel.F_UserCode;
                msgmodel.F_State = 0;
                msgmodel.F_SendType = 2;
                msgmodel.F_IsDelete = 0;
                msgmodel.F_CreateTime = DateTime.Now;
                msgmodel.F_CreateUser = userModel.F_UserCode;

                new BLL.T_SMS_Msg().Add(msgmodel);

                return Success("成功");
            }
            else
            {
                return Error("失败");
            }
        } 
        #endregion

    }
}