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

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

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

                string strtel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
                string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
                string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));

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

                if (strtel.Trim() != "" && strtel != "undefined")
                {
                    sql += " and Telephone like '%" + strtel.Trim() + "%' ";
                }
                if (strstarttime.Trim() != "" && strstarttime != "undefined")
                {
                    sql += " and CreateDate >= '" + Convert.ToDateTime(strstarttime.Trim()) + "' ";
                }
                if (strendtime.Trim() != "" && strendtime != "undefined")
                {
                    sql += " and 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_Receive",
                    "T_SMS_Receive.ID",
                    "*",
                    sql,
                    "ORDER BY T_SMS_Receive.ID desc",
                    pagesize,
                    pageindex,
                    true,
                    out recordCount);

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

                res = Content(obj.ToJson());

            return res;
        }

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

                string tel = HttpUtility.UrlDecode(RequestString.GetFormString("sender"));
                string cont = HttpUtility.UrlDecode(RequestString.GetFormString("content"));
                string rec = HttpUtility.UrlDecode(RequestString.GetFormString("receiver"));
                string time = HttpUtility.UrlDecode(RequestString.GetFormString("revceivtime"));

                Model.T_SMS_Receive dModel = new Model.T_SMS_Receive();

                dModel.Telephone = tel.Trim();
                dModel.Detail = cont.Trim();
                dModel.State = 0;
                //dModel.CreateDate = DateTime.Now;
                dModel.CreateDate = DateTime.Parse(time);

                int b = new BLL.T_SMS_Receive().Add(dModel);
                if (b > 0)
                {
                    res = Success("添加成功");
                }
                else
                {
                    res = Success("添加失败");
                }

            return res;
        }

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

                    int userId = CurrentUser.UserData.F_UserId;
                    if (userId != 0)
                    {
                        Model.T_Sys_UserAccount ua = new BLL.T_Sys_UserAccount().GetModel(userId);
                        if (ua != null)
                        {
                            if (ids != null && ids.Length > 0)
                            {
                                string idd = " ";
                                foreach (string str in ids)
                                {
                                    idd += str + ",";
                                }

                                string sql = "delete T_SMS_Receive where ID in(" + idd.TrimEnd(',') + ")";
                                if (!string.IsNullOrEmpty(idd.Trim()))
                                {
                                    if (DbHelperSQL.ExecuteSql(sql) > 0)
                                    {
                                        res = Success("删除成功");
                                    }
                                    else
                                    {
                                        res = Error("删除失败");
                                    }
                                }
                                else
                                {
                                    res = Error("请选择记录");
                                }
                            }
                            else
                            {
                                res = Error("获取参数失败");
                            }
                        }
                    }

            }
            return res;
        }

        /// <summary>
        /// 更新接收短信状态
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult UpdateRecvState(string[] ids,string state)
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {

                    int userId = CurrentUser.UserData.F_UserId;
                    if (userId != 0)
                    {
                        Model.T_Sys_UserAccount ua = new BLL.T_Sys_UserAccount().GetModel(userId);
                        if (ua != null)
                        {
                            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_Receive set State='"+ n + "' where ID in(" + idd.TrimEnd(',') + ")";
                                if (!string.IsNullOrEmpty(idd.Trim()))
                                {
                                    if (DbHelperSQL.ExecuteSql(sql) > 0)
                                    {
                                        res = Success("更新成功");
                                    }
                                    else
                                    {
                                        res = Error("更新失败");
                                    }
                                }
                                else
                                {
                                    res = Error("请选择记录");
                                }
                            }
                            else
                            {
                                res = Error("获取参数失败");
                            }
                        }
                    }

            }
            return res;
        }

        #endregion

        #region 发送短信

        /// <summary>
        /// 获取发送短信列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetSendList()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            string sql = "";
            DataTable dt = new DataTable();
     
                int type = 0;
                string strtype = HttpUtility.UrlDecode(RequestString.GetQueryString("type"));
                string strtel = HttpUtility.UrlDecode(RequestString.GetQueryString("tel"));
                string strsendway = HttpUtility.UrlDecode(RequestString.GetQueryString("sendway"));
                string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("starttime"));
                string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("endtime"));
                string strstate = HttpUtility.UrlDecode(RequestString.GetQueryString("state"));
                string strbno = HttpUtility.UrlDecode(RequestString.GetQueryString("bno"));

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

                if (strtype != "" && strtype != "undefined")
                {
                    type = Convert.ToInt32(strtype);
                    sql += " and Type= '" + type + "' ";
                }
                if (strsendway != "" && strsendway != "undefined")
                {
                    sql += " and SendWay= '" + Convert.ToInt32(strsendway) + "' ";
                }
                if (strtel.Trim() != "" && strtel != "undefined")
                {
                    sql += " and Telephone like '%" + strtel.Trim() + "%' ";
                }
                if (strstarttime.Trim() != "" && strstarttime != "undefined")
                {
                    sql += " and CreateDate >= '" + Convert.ToDateTime(strstarttime.Trim()) + "' ";
                }
                if (strendtime.Trim() != "" && strendtime != "undefined")
                {
                    sql += " and CreateDate <= '" + Convert.ToDateTime(strendtime.Trim()) + "' ";
                }
                if (strstate.Trim() != "" && strstate != "undefined")
                {
                    sql += " and IsSend= '" + strstate.Trim() + "' ";
                }
                if (strbno.Trim() != "" && strbno != "undefined")
                {
                    sql += " and BatchNo like '%" + strbno.Trim() + "%' ";
                }

                if (strpageindex.Trim() != "")
                {
                    pageindex = Convert.ToInt32(strpageindex);
                }

                if (strpagesize.Trim() != "")
                {
                    pagesize = Convert.ToInt32(strpagesize);
                }
                int recordCount = 0;
                dt = BLL.PagerBLL.GetListPager(
                    "T_SMS_List",
                    "T_SMS_List.ID",
                    "*,dbo.GetDictionaryName(Type) as TypeName",
                    sql,
                    "ORDER BY T_SMS_List.ID desc",
                    pagesize,
                    pageindex,
                    true,
                    out recordCount);

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

                res = Content(obj.ToJson());
 
            return res;
        }

        /// <summary>
        /// 新增短信
        /// </summary>
        /// <returns></returns>
        public ActionResult AddSend()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {
               
                    int userId = CurrentUser.UserData.F_UserId;
                    if (userId != 0)
                    {
                        Model.T_Sys_UserAccount ua = new BLL.T_Sys_UserAccount().GetModel(userId);
                        if (ua != null)
                        {
                            int id= RequestString.GetFormInt("id",0);
                            int type = RequestString.GetFormInt("type", 0);
                            int sendway = RequestString.GetFormInt("sendway", 0);
                            int mbid = RequestString.GetFormInt("mbid", 0);
                            DateTime? dssj = null;
                            string time = HttpUtility.UrlDecode(RequestString.GetFormString("dssj"));
                            string tel = HttpUtility.UrlDecode(RequestString.GetFormString("tel"));
                            string cont=HttpUtility.UrlDecode(RequestString.GetFormString("cont"));
                            if (!string.IsNullOrEmpty(time))
                            {
                                dssj = DateTime.Parse(time);
                            }
                            Model.T_SMS_List dModel = new Model.T_SMS_List();
                            if (id != 0)
                            {
                                dModel = new BLL.T_SMS_List().GetModel(id);
                                dModel.Type = type;
                                dModel.SendWay = sendway;
                                dModel.DSSendTime = dssj;
                                dModel.Telephone = tel;
                                dModel.Detail = cont;
                                dModel.MBID = mbid;

                                if (new BLL.T_SMS_List().Update(dModel))
                                {
                                    res = Success("修改成功");
                                }
                                else
                                {
                                    res = Success("修改失败");
                                }
                            }
                            else
                            {
                                string bno = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                                string[] tels = tel.Split(',');
                                foreach (string tl in tels)
                                {
                                    dModel.BatchNo = bno;
                                    dModel.Type = type;
                                    dModel.SendWay = sendway;
                                    dModel.DSSendTime = dssj;
                                    dModel.Telephone = tl;
                                    dModel.Detail = cont;
                                    dModel.MBID = mbid;
                                    dModel.IsSend = 0;
                                    dModel.CreateDate = DateTime.Now;
                                    dModel.MID = ua.F_UserCode;
                                    dModel.MName = ua.F_UserName;
                                    int b = new BLL.T_SMS_List().Add(dModel);
                                    //if (b > 0)
                                    //{
                                    //    res = Success("添加成功");
                                    //}
                                    //else
                                    //{
                                    //    res = Success("添加失败");
                                    //}
                                }
                                res = Success("添加成功");
                            }
                        }
                    }

            }
            return res;
        }

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

                int ID = RequestString.GetInt("ID", 0);
                if (ID != 0)
                {
                    Model.T_SMS_List model = new BLL.T_SMS_List().GetModel(ID);
                    if (model != null)
                    {
                        string msg = SendSMS(model.Telephone, model.Detail);
                        if (string.IsNullOrEmpty(msg))
                        {
                            res = Success("成功");
                        }
                        else
                        {
                            Error("失败,错误：" + msg);
                        }
                    }
                }

            return res;
        }

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

                    int userId = CurrentUser.UserData.F_UserId;
                    if (userId != 0)
                    {
                        Model.T_Sys_UserAccount ua = new BLL.T_Sys_UserAccount().GetModel(userId);
                        if (ua != null)
                        {
                            if (ids != null && ids.Length > 0)
                            {
                                string idd = " ";
                                foreach (string str in ids)
                                {
                                    idd += str + ",";
                                }

                                string sql = "delete T_SMS_List where ID in(" + idd.TrimEnd(',') + ")";
                                if (!string.IsNullOrEmpty(idd.Trim()))
                                {
                                    if (DbHelperSQL.ExecuteSql(sql) > 0)
                                    {
                                        res = Success("删除成功");
                                    }
                                    else
                                    {
                                        res = Error("删除失败");
                                    }
                                }
                                else
                                {
                                    res = Error("请选择记录");
                                }
                            }
                            else
                            {
                                res = Error("获取参数失败");
                            }
                        }
                    }
         
            }
            return res;
        }

        /// <summary>
        /// 通过批次号删除记录
        /// </summary>
        /// <param name="bathno"></param>
        /// <returns></returns>
        public ActionResult DelSendByBathNo()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {
                
                    int userId = CurrentUser.UserData.F_UserId;
                    if (userId != 0)
                    {
                        Model.T_Sys_UserAccount ua = new BLL.T_Sys_UserAccount().GetModel(userId);
                        if (ua != null)
                        {
                            string strbno = HttpUtility.UrlDecode(RequestString.GetQueryString("bno"));
                            if (!string.IsNullOrEmpty(strbno))
                            {
                                string sql = "delete T_SMS_List where BathNo ='" + strbno + "'";
                                if (DbHelperSQL.ExecuteSql(sql) > 0)
                                {
                                    res = Success("删除成功");
                                }
                                else
                                {
                                    res = Error("删除失败");
                                }
                            }
                            else
                            {
                                res = Error("获取参数失败");
                            }
                        }
                    }
           
            }
            return res;
        }

        /// <summary>
        /// 导入短信
        /// </summary>
        /// <returns></returns>
        public ActionResult ImportSend()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {
               
                    int userId = CurrentUser.UserData.F_UserId;
                    if (userId != 0)
                    {
                        Model.T_Sys_UserAccount userModel = new BLL.T_Sys_UserAccount().GetModel(userId);
                        if (userModel != null)
                        {
                            HttpPostedFile _upfile = RequestString.GetFile("upFile");
                            int headrow = 1;

                            NPOIHelper np = new NPOIHelper();
                            DataTable dt = np.ExcelToTable(_upfile, headrow);

                            string bno = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                            string msg = string.Empty;
                            string tels = string.Empty;
                            foreach (DataRow dr in dt.Rows)
                            {
                                headrow = headrow + 1;
                                //if (dr[0].ToString() != "" && dr[1].ToString() != "")
                                //{
                                //    Model.T_SMS_List dModel = new Model.T_SMS_List();
                                //    dModel.BatchNo = bno;
                                //    dModel.Telephone = dr[0].ToString();
                                //    dModel.Detail = dr[1].ToString();
                                //    dModel.IsSend = 0;
                                //    dModel.SendWay = 1;
                                //    dModel.MID = userModel.F_UserCode;
                                //    dModel.MName = userModel.F_UserName;
                                //    dModel.CreateDate = DateTime.Now;

                                //    if (new BLL.T_SMS_List().Add(dModel) > 0)
                                //    {
                                //        msg = msg + "第" + headrow + "行，导入失败<br>";
                                //    }
                                //}
                                //else
                                //{
                                //    msg = msg + "第" + headrow + "行，手机号或者内容为空，未导入<br>";
                                //}
                                if (dr[0].ToString() != "")
                                {
                                    if (string.IsNullOrEmpty(tels))
                                    {
                                        tels = dr[0].ToString();
                                    }
                                    else
                                    {
                                        tels = tels + "," + dr[0].ToString();
                                    }
                                }
                            }
                            res = Success("成功", tels);
                            //if (string.IsNullOrEmpty(msg))
                            //{
                            //    res = Error(msg);
                            //}
                        }
                    }
             
            }
            return res;
        }

        #endregion

        #region 短信服务

        /// <summary>
        /// 获取发送短信列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetSendListByJob()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            DataTable dt = new DataTable();
         
                int ct = RequestString.GetInt("count", 0);
                string str = string.Empty;
                if (ct != 0)
                {
                    str = " top " + ct;
                }
                dt = DB.DbHelperSQL.Query(" select " + str + " * from T_SMS_List where IsSend=0 and (SendWay=1 or (SendWay=2 and DSSendTime<=getdate() )) order by CreateDate asc ").Tables[0];

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

        /// <summary>
        /// 更新短信发送状态
        /// </summary>
        /// <returns></returns>
        public ActionResult UpdateSendStateByJob()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
           
                int id = RequestString.GetInt("id", 0);
                if (id != 0)
                {
                    Model.T_SMS_List dModel = new BLL.T_SMS_List().GetModel(id);
                    if (dModel != null && dModel.IsSend == 0)
                    {
                        dModel.IsSend = 1;
                        dModel.SendTime = DateTime.Now;

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

        /// <summary>
        /// 执行发送短信
        /// </summary>
        /// <returns></returns>
        public ActionResult ExecSendByJob()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            DataTable dt = new DataTable();
         
                string suc = string.Empty;
                string err = string.Empty;
                int ct = RequestString.GetInt("count", 0);
                string str = string.Empty;
                if (ct != 0)
                {
                    str = " top " + ct;
                }
                dt = DB.DbHelperSQL.Query(" select " + str + " * from T_SMS_List where IsSend=0 and (SendWay=1 or (SendWay=2 and DSSendTime<=getdate() )) order by CreateDate asc ").Tables[0];
                foreach (DataRow dr in dt.Rows)
                {
                    string msg = SendSMS(dr["Telephone"].ToString(), dr["Detail"].ToString());

                    lock (this)
                    {
                        Model.T_SMS_List dModel = new BLL.T_SMS_List().GetModel(Int32.Parse(dr["ID"].ToString()));
                        if (dModel != null && dModel.IsSend == 0)
                        {
                            if (string.IsNullOrEmpty(msg))
                            {
                                dModel.IsSend = 1;
                                suc = suc + "," + dModel.Telephone;
                            }
                            else
                            {
                                dModel.IsSend = -1;
                                err = err + "," + dModel.Telephone;
                            }
                            dModel.SendTime = DateTime.Now;

                            new BLL.T_SMS_List().Update(dModel);
                        }
                    }
                }
                var obj = new
                {
                    suc = string.IsNullOrEmpty(suc) ? "" : suc.TrimEnd(','),
                    err = string.IsNullOrEmpty(err) ? "" : err.TrimEnd(',')
                };
                res = Success("成功", obj);
       
            return res;
        }

        #endregion

        #region 发送短信接口
        
        /// <summary>
        /// 发送短信接口
        /// </summary>
        /// <returns></returns>
        public string SendSMS(string tel, string cont)
        {
            string msg = string.Empty;
            try
            {
                var date = DateTime.Now;
                string url = Configs.GetValue("smsurl")+ "Send.aspx";
                string sign = Configs.GetValue("smssign") ;
                string username = Configs.GetValue("smsusername");
                string password = Configs.GetValue("smspassword");
                string content = HttpUtility.UrlEncode(System.Text.Encoding.GetEncoding("GB2312").GetBytes(cont + "【" + sign + "】"));

                string param = "username=" + username + "&password=" + CommonHelper.MD5(password+ date.ToString("yyyy-MM-dd HH:mm:ss"));
                param += "&mobiles=" + tel + "&content=" + content + "&f=1&timestamp="+ date.ToString("yyyy-MM-dd HH:mm:ss");
                string result = HttpMethods.HttpPost(url, param);
                //Hashtable res = new Hashtable();
                Dictionary<String, String> res = new Dictionary<string, string>();
                if (!string.IsNullOrEmpty(result))
                {
                    string[] strs = result.Split('&');
                    foreach (string str in strs)
                    {
                        string[] items = str.Split('=');
                        res.Add(items[0], items[1]);
                    }
                }
                if (res.Count > 0)
                {
                    string suc = res["result"];
                    string dec = System.Text.Encoding.GetEncoding("GB2312").GetString(HttpUtility.UrlDecodeToBytes(res["description"]));
                    if (suc != "0")
                    {
                        msg = dec;
                    }
                }
            }
            catch (Exception ex)
            {
                msg = ex.Message;
            }
            return msg;
        }

        /// <summary>
        /// 发送模板短信
        /// </summary>
        /// <param name="cont"></param>
        /// <param name="paras"></param>
        /// <returns></returns>
        public string SendSMSByTemplate(string cont, string paras)
        {
            string msg = string.Empty;
            try
            {
                var date = DateTime.Now;
                string url = Configs.GetValue("smsurl") + "SendVarSms.aspx";
                string sign = Configs.GetValue("smssign");
                string username = Configs.GetValue("smsusername");
                string password = Configs.GetValue("smspassword");

                string param = "username=" + username + "&password=" + password; //CommonHelper.MD5(password + date.ToString("yyyy-MM-dd HH:mm:ss"));
                param +=  "&content=" + cont + "【" + sign + "】" + "&params=" + paras;
                string result = HttpMethods.HttpPost(url, param);
                //Hashtable res = new Hashtable();
                Dictionary<String, String> res = new Dictionary<string, string>();
                if (!string.IsNullOrEmpty(result))
                {
                    string[] strs = result.Split('&');
                    foreach (string str in strs)
                    {
                        string[] items = str.Split('=');
                        res.Add(items[0], items[1]);
                    }
                }
                if (res.Count > 0)
                {
                    string suc = res["result"];
                    //string dec = System.Text.Encoding.GetEncoding("GB2312").GetString(HttpUtility.UrlDecodeToBytes(res["description"]));
                    string dec = HttpUtility.UrlDecode(res["description"]);
                    if (suc != "0")
                    {
                        msg = dec;
                    }
                }
            }
            catch (Exception ex)
            {
                msg = ex.Message;
            }
            return msg;
        }

        /// <summary>
        /// 修改短信接口密码
        /// </summary>
        /// <param name="newpsd"></param>
        /// <returns></returns>
        public string UpdateSMSPassword(string newpsd)
        {
            string msg = string.Empty;
            try
            {
                var date = DateTime.Now;
                string url = Configs.GetValue("smsurl") + "SendVarSms.aspx";
                string sign = Configs.GetValue("smssign");
                string username = Configs.GetValue("smsusername");
                string password = Configs.GetValue("smspassword");

                string param = "username=" + username + "&password=" + password + "&newpwd=" + newpsd;
                string result = HttpMethods.HttpPost(url, param);
                Dictionary<String, String> res = new Dictionary<string, string>();
                if (!string.IsNullOrEmpty(result))
                {
                    string[] strs = result.Split('&');
                    foreach (string str in strs)
                    {
                        string[] items = str.Split('=');
                        res.Add(items[0], items[1]);
                    }
                }
                if (res.Count > 0)
                {
                    string suc = res["result"];
                    string dec = HttpUtility.UrlDecode(res["description"]);
                    if (suc != "0")
                    {
                        msg = dec;
                    }
                    else
                    {
                        Configs.SetValue("smspassword", newpsd);
                    }
                }
            }
            catch (Exception ex)
            {
                msg = ex.Message;
            }
            return msg;
        }

        /// <summary>
        /// 查询余额
        /// </summary>
        /// <returns></returns>
        public string QuerySMSBalance()
        {
            string msg = string.Empty;
            try
            {
                var date = DateTime.Now;
                string url = Configs.GetValue("smsurl") + "Query.aspx";
                string username = Configs.GetValue("smsusername");
                string password = Configs.GetValue("smspassword");

                string param = "username=" + username + "&password=" + password; 

                string result = HttpMethods.HttpPost(url, param);

                Dictionary<String, String> res = new Dictionary<string, string>();
                if (!string.IsNullOrEmpty(result))
                {
                    string[] strs = result.Split('&');
                    foreach (string str in strs)
                    {
                        string[] items = str.Split('=');
                        res.Add(items[0], items[1]);
                    }
                }
                if (res.Count > 0)
                {
                    string suc = res["result"];
                    string dec = System.Text.Encoding.GetEncoding("GB2312").GetString(HttpUtility.UrlDecodeToBytes(res["description"]));
                    if (suc != "0")
                    {
                        msg = dec;
                    }
                }
            }
            catch (Exception ex)
            {
                msg = ex.Message;
            }
            return msg;
        }

        #endregion
    }
}