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

namespace CallCenterApi.Interface.Controllers.information
{
    [Authority]
    public class InternalMessagesController : BaseController
    {
        BLL.T_SMS_InternalMessages bll = new BLL.T_SMS_InternalMessages();
        /// <summary>
        /// 获取所有列表 分页
        /// </summary>
        /// <returns></returns>
        public ActionResult GetAllList()
        {
            DataTable dt = new DataTable();
            string SMS_Title = HttpUtility.UrlDecode(RequestString.GetQueryString("title"));
            string SMS_ReceiveUserCode = HttpUtility.UrlDecode(RequestString.GetQueryString("receiveUserCode"));
            string SMS_SendUserCode = HttpUtility.UrlDecode(RequestString.GetQueryString("sendUserCode"));
            string SMS_Content = HttpUtility.UrlDecode(RequestString.GetQueryString("content"));
            string strstarttime = HttpUtility.UrlDecode(RequestString.GetQueryString("strstarttime"));
            string strendtime = HttpUtility.UrlDecode(RequestString.GetQueryString("strendtime"));
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;

            string sql = string.Empty;
            if (SMS_Title.Trim() != "")
            {
                sql += " and SMS_Title like '%" + SMS_Title + "%'";
            }
            if (SMS_ReceiveUserCode.Trim() != "")
            {
                sql += " and SMS_ReceiveUserCode = '" + SMS_ReceiveUserCode + "'";
            }
            if (SMS_SendUserCode.Trim() != "")
            {
                sql += " and SMS_SendUserCode = '" + SMS_SendUserCode + "'";
            }
            if (SMS_Content.Trim() != "")
            {
                sql += " and SMS_Content like '%" + SMS_Content + "%'";
            }
            if (strstarttime.Trim() != "" && strstarttime != "undefined")
            {
                sql += " and datediff(day,SMS_SendUserCode,'" + strstarttime + "')<=0 ";
            }
            if (strendtime.Trim() != "" && strendtime != "undefined")
            {
                sql += " and datediff(day,SMS_SendUserCode,'" + strendtime + "')>=0   ";
            }
            if (strpageindex.Trim() != "")
            {
                pageindex = Convert.ToInt32(strpageindex);
            }
            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }
            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                    "T_SMS_InternalMessages",
                    "F_Id",
                    "*",
                    sql,
                    "ORDER BY SMS_Id desc",
                    pagesize,
                    pageindex,
                    true,
                    out recordCount);
            var obj = new
            {
                rows = dt,
                total = recordCount
            };
            return Content(obj.ToJson());
        }

        /// <summary>
        /// 获取前几条列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetTopList()
        {
            DataTable dt = new DataTable();
            string strWhere = string.Empty;
            int Top = RequestString.GetInt("top", 5);
            string SMS_ReceiveUserCode = RequestString.GetQueryString("receiveUserCode");
            if (SMS_ReceiveUserCode.Trim() != "")
            {
                strWhere += " and SMS_ReceiveUserCode = '" + SMS_ReceiveUserCode + "'";
            }
            dt = bll.GetList(Top, strWhere, " SMS_Order,SMS_SendTime ").Tables[0];
            var obj = new
            {
                rows = dt,
                total = Top
            };
            return Content(obj.ToJson());
        }

        /// <summary>
        /// 获取一条详细信息
        /// </summary>
        /// <param name="infoid"></param>
        /// <returns></returns>
        public ActionResult GetInfo(string infoid)
        {
            if (infoid != null && infoid.Trim() != "")
            {
                Model.T_SMS_InternalMessages model = bll.GetModel(int.Parse(infoid.Trim()));
                
                if (model != null)
                {
                    if (model.SMS_IsRead == 0)
                    {
                        model.SMS_IsRead = 1;
                        model.SMS_ReadTime = DateTime.Now;
                        bool b = bll.Update(model);
                        if (b)
                        {
                            return Success("获取成功", model);
                        }
                        else
                        {
                            return Error("获取失败，无更新权限");
                        }
                    }
                    else {
                        return Success("获取成功", model);
                    }
                }
                else
                {
                    return Error("获取失败");
                };
            }
            else
            {
                return Error("获取参数失败");
            }
        }

        /// <summary>
        /// 保存信息
        /// </summary>
        /// <returns></returns>
        public ActionResult SaveInfo()
        {
            int id = RequestString.GetInt("id", 0);
            string SMS_Title = RequestString.GetFormString("title");
            string SMS_ReceiveUserCode = RequestString.GetFormString("receiveUserCode");
            string SMS_SendUserCode = RequestString.GetFormString("sendUserCode");
            string SMS_Content = RequestString.GetFormString("content");
            int SMS_IsDelete = RequestString.GetInt("isDelete", 0);
            int SMS_IsRead = RequestString.GetInt("isRead", 0);
            int SMS_Order = RequestString.GetInt("order", 0);
            int SMS_IsTop = RequestString.GetInt("isTop", 0);
            int SMS_Type = RequestString.GetInt("smstype", 0);

            if (!string.IsNullOrWhiteSpace(SMS_Title) || !string.IsNullOrWhiteSpace(SMS_ReceiveUserCode) || !string.IsNullOrWhiteSpace(SMS_ReceiveUserCode))
            {
                Model.T_SMS_InternalMessages model = new Model.T_SMS_InternalMessages();
                if (id == 0)
                {
                    model.SMS_Title = SMS_Title;
                    model.SMS_Content = SMS_Content;
                    model.SMS_ReceiveUserCode = SMS_ReceiveUserCode;
                    model.SMS_SendUserCode = SMS_SendUserCode;
                    model.SMS_IsRead = SMS_IsRead;
                    model.SMS_SendTime = DateTime.Now;
                    //model.SMS_ReadTime = SMS_ReadTime;
                    //model.SMS_DeleteTime = SMS_DeleteTime;
                    model.SMS_IsDelete = 0;
                    model.SMS_Order = SMS_Order;
                    model.SMS_IsTop = SMS_IsTop;
                    model.SMS_Type = SMS_Type;
                    int n = bll.Add(model);
                    if (n > 0)
                    {
                        return Success("添加成功", n);
                    }
                    else
                    {
                        return Error("添加失败");
                    }
                }
                else
                {
                    model = bll.GetModel(id);
                    if (model != null)
                    {
                        model.SMS_Id = id;
                        model.SMS_Title = SMS_Title;
                        model.SMS_Content = SMS_Content;
                        model.SMS_ReceiveUserCode = SMS_ReceiveUserCode;
                        model.SMS_SendUserCode = SMS_SendUserCode;
                        model.SMS_IsRead = SMS_IsRead;
                        model.SMS_SendTime = model.SMS_SendTime;
                        //model.SMS_ReadTime = DateTime.Now;
                        //model.SMS_DeleteTime = SMS_DeleteTime;
                        model.SMS_IsDelete = 0;
                        model.SMS_Order = SMS_Order;
                        model.SMS_IsTop = SMS_IsTop;
                        model.SMS_Type = SMS_Type;
                        if (bll.Update(model))
                        {
                            return Success("修改成功");
                        }
                        else
                        {
                            return Error("修改失败");
                        }
                    }
                    return Error("信息不存在");
                }
            }
            else
            {
                return Error("获取参数失败");
            }
        }

        /// <summary>
        /// 删除信息
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult DelInfo(string[] ids)
        {
            if (ids != null && ids.Length > 0)
            {
                string idd = " ";
                foreach (string str in ids)
                {
                    idd += str + ",";
                }
                if (bll.DeleteList(idd.TrimEnd(',')))
                {
                    return Success("删除成功");
                }
                else
                    return Error("删除失败");
            }
            else
            {
                return Error("获取参数失败");
            }
        }

        /// <summary>
        /// 添加信息
        /// </summary>
        /// <param name="title"></param>
        /// <param name="content"></param>
        /// <param name="receiveUserCode"></param>
        /// <param name="sendUserCode"></param>
        /// <returns></returns>
        public bool AddInternalMessagesInfo(string title,string content,string receiveUserCode,string sendUserCode, int smstype = 0,int smstop=0)
        {
            if (!string.IsNullOrWhiteSpace(title) || !string.IsNullOrWhiteSpace(receiveUserCode) || !string.IsNullOrWhiteSpace(sendUserCode))
            {
                Model.T_SMS_InternalMessages model = new Model.T_SMS_InternalMessages();
                model.SMS_Title = title;
                model.SMS_Content = content;
                model.SMS_ReceiveUserCode = receiveUserCode;
                model.SMS_SendUserCode = sendUserCode;
                model.SMS_IsRead = 0;
                model.SMS_SendTime = DateTime.Now;
                //model.SMS_ReadTime = SMS_ReadTime;
                //model.SMS_DeleteTime = SMS_DeleteTime;
                model.SMS_IsDelete = 0;
                model.SMS_Order = 0;
                model.SMS_IsTop = smstop;
                model.SMS_Type = smstype;
                int n = bll.Add(model);
                if (n > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else {
                return false;
            }
        }

        /// <summary>
        /// 更新状态
        /// </summary>
        /// <param name="ids"></param>
        /// <param name="state"></param>
        /// <returns></returns>
        public ActionResult UpdateState(string[] ids, int state=0)
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            if (userId <= 0)
                return Error("权限不足");
            Model.T_Sys_UserAccount ua = new BLL.T_Sys_UserAccount().GetModel(userId);
            if (ua == null)
                return Error("权限不足！");
            if (ids != null && ids.Length > 0)
            {
                string idd = " ";
                foreach (string str in ids)
                {
                    idd += str + ",";
                }
                string sj = "null";
                if (state == 1)
                {
                    sj = "getdate()";
                }
                string sql = "update T_SMS_InternalMessages set SMS_IsRead=" + state + ",SMS_ReadTime=" + sj + " where SMS_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("获取参数失败");
            }
        }

        /// <summary>
        /// 获取消息提醒
        /// </summary>
        /// <returns></returns>
        public ActionResult GetMsg(int smstype=0)
        {
            int userId = Utils.StrToInt(User.UserData["F_UserID"], 0);
            Model.T_Sys_UserAccount userModel = new BLL.T_Sys_UserAccount().GetModel(userId);
            if(userModel!=null)
            {
                var sql = " SMS_IsDelete=0 and SMS_IsRead=0 ";
                sql += " and SMS_ReceiveUserCode='" + userModel.F_UserCode + "'";
                if (smstype > 0)
                    sql += " and SMS_Type="+ smstype;
                var msglist = bll.GetModelList(sql + " order by SMS_IsTop desc,SMS_SendTime  desc");
                return Success("获取消息成功", msglist);
            }
            return Error("权限不足");
        }
    }
}