using CallCenter.Utility;
using CallCenterApi.Common;
using CallCenterApi.DB;
using CallCenterApi.Interface.Controllers.Base;
using CallCenterApi.Model;
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 MsgController : BaseController
    {
        /// <summary>
        /// 获取消息列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetList()
        {
            ActionResult res = NoToken("未知错误，请重新登录");
            if (Request.IsAuthenticated)
            {
                string sql = " and isdel=0 ";
                DataTable dt = new DataTable();
          
                    int userId = CurrentUser.UserData.F_UserId;
                    if (userId != 0)
                    {
                        Model.T_Sys_UserAccount ua = new BLL.T_Sys_UserAccount().GetModel(userId);
                        if (ua != null)
                        {
                        sql += " and ToUser='" + ua.F_UserCode + "' ";

                            int state = RequestString.GetInt("state", -1);
                            string strkey = HttpUtility.UrlDecode(RequestString.GetQueryString("key"));
                            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 (state != -1)
                            {
                                sql += " and State='" + state + "'";
                            }
                            if (strkey.Trim() != "" && strkey != "undefined")
                            {
                                sql += " and Detail like '%" + strkey.Trim() + "%' ";
                            }
                            if (strstarttime.Trim() != "" && strstarttime != "undefined")
                            {
                                sql += " and datediff(day,CreateDate,'" + strstarttime + "')<=0 ";
                            }
                            if (strendtime.Trim() != "" && strendtime != "undefined")
                            {
                                sql += " and datediff(day,CreateDate,'" + strendtime + "')>=0   ";
                            }

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

                            if (strpagesize.Trim() != "")
                            {
                                pagesize = Convert.ToInt32(strpagesize);
                            }
                            int recordCount = 0;
                            dt = BLL.PagerBLL.GetListPager(
                                "T_Msg_List",
                                "ID",
                                "*,dbo.GetUserName(CreateUser) as CreateUserName, dbo.GetUserName(ToUser) as ToUserName",
                                sql,
                                "ORDER BY 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 AddMsg()
        {
            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.GetInt("id", 0);
                            int type = RequestString.GetInt("type", 0);
                            int toid = RequestString.GetInt("toid", 0);
                            string usercode = RequestString.GetFormString("usercode");
                            string cont = RequestString.GetFormString("cont");

                            Model.T_Msg_List model = new Model.T_Msg_List();

                            if (id == 0)
                            {
                                model.Detail = cont;
                                model.Type = type;
                                model.ToUser = usercode;
                                model.ToID = toid;
                                model.State = 0;
                                model.IsDel = 0;
                                model.CreateDate = DateTime.Now;
                                model.CreateUser = ua.F_UserCode;

                                if (new BLL.T_Msg_List().Add(model) > 0)
                                {
                                    res = Success("新增成功！");
                                }
                                else
                                {
                                    res = Error("新增失败！");
                                }
                            }
                            else
                            {
                                model = new BLL.T_Msg_List().GetModel(id);
                                if (model != null)
                                {
                                    model.Detail = cont;
                                    model.Type = type;
                                    model.ToUser = usercode;
                                    model.ToID = toid;

                                    if (new BLL.T_Msg_List().Update(model))
                                    {
                                        res = Success("修改成功！");
                                    }
                                    else
                                    {
                                        res = Error("修改失败！");
                                    }
                                }
                                else
                                {
                                    res = Error("修改失败！");
                                }
                            }
                        }
                    }
      
            }
            return res;
        }

        /// <summary>
        /// 删除消息
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ActionResult DelMsg(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 = "update T_Msg_List set IsDel=1,DelUser='" + ua.F_UserCode + "',DelTime=getdate() 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>
        /// <param name="state"></param>
        /// <returns></returns>
        public ActionResult UpdateState(string[] ids,int 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)
                        {
                            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_Msg_List set State=" + state + ",ReadDate=" + sj + " 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>
        /// <returns></returns>
        public ActionResult ReadMsg()
        {
            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.GetInt("id", 0);

                            Model.T_Msg_List model = new BLL.T_Msg_List().GetModel(id);
                            if (model != null)
                            {
                                model.State = 0;
                                model.ReadDate = DateTime.Now;
                                if (new BLL.T_Msg_List().Update(model))
                                {
                                    res = Success("成功！");
                                }
                                else
                                {
                                    res = Error("失败！");
                                }
                            }
                            else
                            {
                                res = Error("失败");
                            }
                        }
                    }
   
            }
            return res;
        }

        /// <summary>
        /// 获取服务周期到期提醒
        /// </summary>
        public ActionResult GetServerMsg()
        {
            string usercode = CurrentUser.UserData.F_UserCode;
            //获取一个月内服务周期到期的客户信息
            //var cusbaseList = new BLL.T_Cus_CustomerBaseNew().GetModelList(" F_DeleteFlag=0 and DATEDIFF(month,F_CycleEnd,getdate())<=1 ");
            //获取一个月内当前登录工号的消息提醒
            //var msgList = new BLL.T_Msg_List().GetModelList(" ToUser='" + usercode + "'and IsDel=0 and DATEDIFF(month,CreateDate,getdate())<=1  ");
            //获取一个月内的开票信息
            //var billList = new BLL.T_Wo_Bill().GetModelList(" F_State=0 and F_IsDel=0 and DATEDIFF(month,F_CreateOn,getdate())<=1 ");

            #region 服务周期到期客户消息
            //foreach (var cusbase in cusbaseList)
            //{
            //    var msgnew = msgList.Where(m => m.ToID == cusbase.F_CustomerId && m.Type== (int)Model.MSGType.cusserver);
            //    //若消息列表中不能存在该客户信息，则添加
            //    if (msgnew.Count() > 0)
            //    {
            //        continue;
            //    }
            //    Model.T_Msg_List msg = new Model.T_Msg_List();
            //    msg.Type = (int)Model.MSGType.cusserver;//服务周期
            //    msg.ToUser = usercode;
            //    msg.ToID = cusbase.F_CustomerId;
            //    msg.Detail = "客户编号为：“" + cusbase.F_CustomerCode + "”的客户服务周期即将到期，请及时处理！";
            //    msg.State = 0;
            //    msg.IsDel = 0;
            //    msg.CreateDate = DateTime.Now;

            //    new BLL.T_Msg_List().Add(msg);
            //}
            #endregion
            #region 开票消息提醒
            //foreach (var billbase in billList)
            //{
            //    var msgnew = msgList.Where(m => m.ToID == billbase.F_ID && m.Type == (int)Model.MSGType.bill);
            //    //若消息列表中不能存在该客户信息，则添加
            //    if (msgnew.Count() > 0)
            //    {
            //        continue;
            //    }
            //    Model.T_Msg_List msg = new Model.T_Msg_List();
            //    msg.Type = (int)Model.MSGType.bill;//开票
            //    msg.ToUser = usercode;
            //    msg.ToID = billbase.F_ID;
            //    msg.Detail = "新增一条客户" + billbase.F_CusName + "的开票信息，请及时处理！";
            //    msg.State = 0;
            //    msg.IsDel = 0;
            //    msg.CreateDate = DateTime.Now;

            //    new BLL.T_Msg_List().Add(msg);
            //}
            #endregion
            
            var msgListnew = new BLL.T_Msg_List().GetModelList(" ToUser='" + usercode + "' and Type in (2,8) and State=0 and IsDel=0 order by CreateDate desc");
            return Success("获取消息", msgListnew);
        }

    }
}