using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ZXDT.CallCenter.MVCWeb.Models;
using ZXDT.CallCenter.Model;
using ZXDT.CallCenter.MVCWeb.Commons;

namespace ZXDT.CallCenter.MVCWeb.Controllers
{
    public class SMSController : BaseController
    {
        //
        // GET: /SMS/
        BLL.T_SMS_SendSMSTask smsdll = new BLL.T_SMS_SendSMSTask();
        BLL.T_SMS_SentSMS smsBLL = new BLL.T_SMS_SentSMS();
        #region   初使化页面
        //短信发送
        public ActionResult SMS_Send(int? smsId)
        {
            Model.T_SMS_SendSMSTask viewsmsmodel = new Model.T_SMS_SendSMSTask();
            if (smsId > 0 && smsId != null)
            {
                viewsmsmodel = smsdll.GetModel(int.Parse(smsId.ToString()));
            }
            return View(viewsmsmodel);
        }
        //待发短信
        public ActionResult SMS_SendTask()
        {
            Model.T_SMS_SentSMS sentokmodel = new Model.T_SMS_SentSMS();
            return View(sentokmodel);
        }
        //已发短信
        public ActionResult SMS_SendTaskOK()
        {
            Model.T_SMS_SentSMS sentokmodel = new Model.T_SMS_SentSMS();
            return View(sentokmodel);
        }
        #endregion
        #region   短信发送信息
        /// <summary>
        /// 保存编辑
        /// </summary>
        /// <param name="workOrderBaseModel"></param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Post)]
        public bool SendDataSave(T_SMS_SendSMSTask smsInfoModel)
        {
            bool bl = false;
            int savedata = 0;
            string strtelnum = smsInfoModel.TelNum.Trim();
            string[] strarr = strtelnum.Split(',');
            try {
                //判断是否用非英文逗号
                if (strtelnum.Contains("，"))
                {
                    bl = false;
                    
                }
                else
                {
                    for (int i = 0; i <= strarr.Length - 1; i++)
                    {
                        smsInfoModel.TelNum = strarr[i].Trim();
                        smsInfoModel.CommitTime = DateTime.Now;
                        smsInfoModel.Info = "待发送";
                        smsInfoModel.F_UserID = F_UserID;
                        smsInfoModel.F_Name=HttpUtility.UrlDecode( F_UserName);
                         savedata = smsdll.Add(smsInfoModel);
                        MessageNotice(smsInfoModel.Content, smsInfoModel.TelNum, strarr.Length);
                    }
                }
            //return smsdll.Add(smsInfoModel) > 0;

            if (savedata > 0)
            {
                bl = true;
            }
            else
            {
                bl = false; 
            }
        }
            catch (Exception ex)
            {
            }
            return bl;
        }


        #endregion 
        #region 发送、待发短信
        //获取已发短信
        [ActionName("Sendtoklist")]
        [HttpGet]
        public string Sendtoklist(DateTime? NowDateTime, int page, 
            int limit, string dateParty, string cusName, string cusNum,string content)
        {
            //数据结果集
            ResponseData dataModel = new ResponseData();

            string sql = "";
            if (cusNum != null)
            {
                sql += " and TelNum like '%" + cusNum + "%'";
            }

            //内容模糊查询
            if (content != null)
            {
                sql += " and Content like '%" + content + "%'";
            }


            if (!string.IsNullOrEmpty(dateParty))
            {

                string startDate = dateParty.Substring(0, 19);
                string endDate = dateParty.Substring(21);
                sql += " and SendTime>= '" + startDate + "'";
                sql += " and SendTime<= '" + endDate + "'";
            }
            DataTable dt = new DataTable();
            int recordCount = 0;
            Model.PageData<Model.T_SMS_SentSMS> pageModel = new Model.PageData<Model.T_SMS_SentSMS>();
            dt = BLL.PagerBLL.GetListPager(
                "T_SMS_SentSMS",
                "SMSID",
                " SMSID,TelNum ,Content , CONVERT(varchar(100), CommitTime, 20) CommitTime,CONVERT(varchar(100), SendTime, 20) SendTime,LastSentTime,MaxSendCount , CurSentCount, Info, SendModemIMEI, F_UserID, F_CustomerID, F_Name",
                sql,
                "ORDER BY SMSID desc",
                limit,
                page,
                true,
                out recordCount);


            dataModel.code = 0;
            dataModel.count = recordCount;
            dataModel.data = dt;

            return JsonConvert.SerializeObject(dataModel);
        }
        //
        // GET: /SMS/Details/5
        //获取已发短信
        [ActionName("Sendtlist")]
        [HttpGet]
        public string Sendtlist(DateTime? NowDateTime, int page, int limit, string dateParty, string cusName, string cusNum)
        {
            //数据结果集
            ResponseData dataModel = new ResponseData();

            string sql = " and SendTime is null ";
            if (cusNum != null)
            {
                sql += " and TelNum like '%" + cusNum + "%'";
            }
            if (!string.IsNullOrEmpty(dateParty))
            {

                string startDate = dateParty.Substring(0, 19);
                string endDate = dateParty.Substring(21);
                sql += " and CommitTime>= '" + startDate + "'";
                sql += " and CommitTime<= '" + endDate + "'";
            }
            DataTable dt = new DataTable();
            int recordCount = 0;
            Model.PageData<Model.T_SMS_SentSMS> pageModel = new Model.PageData<Model.T_SMS_SentSMS>();
            dt = BLL.PagerBLL.GetListPager(
                "T_SMS_SendSMSTask",
                "SMSID",
                " SMSID,TelNum ,Content , CONVERT(varchar(100), CommitTime, 20) CommitTime,CONVERT(varchar(100), SendTime, 20) SendTime,LastSentTime,MaxSendCount , CurSentCount, Info,  F_UserID, F_CustomerID, F_Name",
                sql,
                "ORDER BY SMSID desc",
                limit,
                page,
                true,
                out recordCount);


            dataModel.code = 0;
            dataModel.count = recordCount;
            dataModel.data = dt;

            return JsonConvert.SerializeObject(dataModel);
        }

        /// <summary>
        //删除待发短信
        /// </summary>
        /// <param name="workOrderBaseModel"></param>
        /// <returns></returns>
        [AcceptVerbs(HttpVerbs.Get)]
        public bool DeleteSmsData(string smsId)
        {
            return smsdll.DeleteList(smsId);

        }
        #endregion 
        /// <summary>
        /// 发送短信接口
        /// </summary>
        /// <param name="MessageCount">手动发送短信</param>
        /// <returns></returns>
        [ActionName("MessageNotice")]
        [HttpGet]
        public bool MessageNotice(string MessageContent,string TelNum,int Length)
        {
            //数据结果集
            bool SendResult = false;
            try
            {
                //用户名:zzmetro   接口密码:r9ffaa
                //MD5(username+MD5(pwd)),pwd为明文密码，32位小写md5
                string smsUrl = "http://www.jc-chn.cn/smsSend.do?username=zzmetro&password=28fc33e97e092b633f47a456740b636e&mobile=" + TelNum +"&content=";
                System.Web.HttpUtility.UrlEncode("发送短信！" + MessageContent , System.Text.Encoding.UTF8);
                Model.T_SMS_SentSMS model = new Model.T_SMS_SentSMS();
                model.State = 0;
                model.CommitTime = DateTime.Now;
                model.MaxSendCount = 5; //最大发送次数
                model.Content = MessageContent;//发送内容
                for (int i = 1; i <= model.MaxSendCount; i++)
                {
                    model.CurSentCount = i;
                    string addWxResult = HttpHelper.HttpSMSSend(smsUrl+ MessageContent+ "【郑州地铁】");
                    //判断返回接口是否发送成功！
                    if (!string.IsNullOrEmpty(addWxResult)   )
                    {
                        switch (addWxResult)
                        {
                           case "-1": SendResult = false;
                            model.State = 0;//发送成功
                            model.Info = "用户名或者密码不正确!";
                            break;
                            case "0":
                                SendResult = false;
                                model.State = 0;//发送成功
                                model.Info = "失败!";
                                break;
                            case "-5":
                                SendResult = false;
                                model.State = 0;//发送成功
                                model.Info = "余额不够!";
                                break;
                            case "-10":
                                SendResult = false;
                                model.State = 0;//发送成功
                                model.Info = "用户被禁用!";
                                break;
                            case "-11":
                                SendResult = false;
                                model.State = 0;//发送成功
                                model.Info = "短信内容超过500字!";
                                break;
                        }
                        if (addWxResult.Length>7) {
                            SendResult = true;
                            model.State = 1;//发送成功
                            model.Info = "发送成功";
                            }
                        model.SendTime = DateTime.Now;
                        model.F_UserID = F_UserID;
                        model.F_Name = HttpUtility.UrlDecode(F_UserName);
                        model.SendModemIMEI = "用户：" + HttpUtility.UrlDecode(F_UserName) + "提供";

                        model.TelNum = TelNum;
                        //将短信发送信息存储到内容中
                        smsBLL.Add(model); 
                        break;
                    }
                    //将短信发送信息存储到内容中
                   // smsBLL.Add(model);
                } 
            }
            catch (Exception ex) {  }
            return SendResult;
        }

    }
}
