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

namespace CallCenterApi.Interface.Controllers.information
{
    public class NoticeController : BaseController
    {
        BLL.T_Msg_NoticeInfo dBLL = new BLL.T_Msg_NoticeInfo();
        BLL.T_Msg_List msgBLL = new BLL.T_Msg_List();
        private BLL.T_Sys_RoleInfo rolebll = new BLL.T_Sys_RoleInfo();
        BLL.T_Sys_UserAccount userBLL = new BLL.T_Sys_UserAccount();
        /// <summary>
        /// 获取角色列表
        /// </summary>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <param name="code"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public ActionResult GetRoleList()
        {
            DataTable dt = new DataTable();
            dt = rolebll.GetAllList().Tables[0];
            return Success("获取成功", dt);
        }
        /// <summary>
        /// 获取坐席列表
        /// </summary>
        /// <param name="roleid"></param>
        /// <returns></returns>
        public ActionResult GetUserListByRoleId(string roleid)
        {
            DataTable dt = new DataTable();
            var sql = " F_DeleteFlag=0 ";
            if (!string.IsNullOrWhiteSpace(roleid))
            {
                sql += " and F_RoleId in( " + roleid + ")";
            }
            string sqldt = "SELECT F_UserId,F_UserCode,F_RoleId,F_UserName FROM T_Sys_UserAccount WHERE " + sql + " ";
            dt = DbHelperSQL.Query(sqldt).Tables[0];
            return Success("获取成功", dt);
        }
        /// <summary>
        /// 获取角色用户列表
        /// </summary>
        /// <returns></returns>
        public ActionResult GetRoleUsersList(string noticeid)
        {
            DataTable dtuser = new DataTable();
            var sql = " F_DeleteFlag=0  ";
            string sqldt = "SELECT F_UserId as F_Id,('('+F_UserCode+')'+F_UserName)as F_Name,F_RoleId as F_Pid,0 as F_ischeck FROM T_Sys_UserAccount WHERE " + sql + " ";
            dtuser = DbHelperSQL.Query(sqldt).Tables[0];

            DataTable dtrole = new DataTable();
            dtrole = rolebll.GetAllList().Tables[0];

            var users = ""; var roles = "";
            if (noticeid != null && noticeid.Trim()!="")
            {
                Model.T_Msg_NoticeInfo dModel = dBLL.GetModel(int.Parse(noticeid.Trim()));
                if (dModel != null)
                {
                    users = dModel.F_UserId.Trim(',');
                    roles = dModel.F_RoleId.Trim(',');
                }
            }

            string[] userlist = users.Split(',');
            string[] rolelist = roles.Split(',');
            #region 绑定是否选中用户
            foreach (DataRow dr in dtuser.Rows)
            {
                if (userlist.Length > 0)
                {
                    for (int j = 0; j < userlist.Length; j++)
                    {
                        if (dr["F_Id"].ToString() == userlist[j])
                        {
                            dr["F_ischeck"] = 1;
                        }
                    }
                }
            }
            #endregion

            DataTable newdt = new DataTable();
            newdt = dtuser;
            foreach (DataRow dr in dtrole.Rows)
            {
                DataRow drnew = newdt.NewRow();
                drnew["F_Id"] = dr["F_RoleId"];
                drnew["F_Name"] = dr["F_RoleName"];
                drnew["F_Pid"] = 0;
                drnew["F_ischeck"] = 0;
                #region 绑定是否选中角色
                if (rolelist.Length > 0)
                {
                    for (int j = 0; j < rolelist.Length; j++)
                    {
                        if (dr["F_RoleId"].ToString() == rolelist[j])
                        {
                            drnew["F_ischeck"] = 1;
                        }
                    }
                }
                #endregion
                newdt.Rows.Add(drnew);
            }
            return Success("获取角色用户成功", newdt);
        }
        
        // 获取公告列表
        public ActionResult GetList(string sdate,string edate,int pageindex=1,int pagesize=10)
        {
            DataTable dt = new DataTable();
            string sql = " and F_isDel=0 ";
            if (sdate != null && sdate.Trim() != "")
            {
                sql += " and Datediff(day,F_CreateOn,'" + sdate.Trim() + "')>=0";
            }
            if (edate != null && edate.Trim() != "")
            {
                sql += " and Datediff(day,F_CreateOn,'" + edate.Trim() + "')<=0";
            }

            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_Msg_NoticeInfo",
                "F_NoticeId",
                "*",
                sql,
                "ORDER BY F_NoticeId desc",
                pagesize,
                pageindex,
                true,
                out recordCount);
            List<Model.T_Msg_NoticeInfo> msgList = new BLL.T_Msg_NoticeInfo().DataTableToList(dt);
            List<Model.T_Sys_UserAccount> userList = new BLL.T_Sys_UserAccount().GetModelList("");
            var obj = new
            {
                rows = msgList.Select(m =>
                {
                    Model.T_Sys_UserAccount usermodel = userList.Where(u => u.F_UserId == m.F_CreateBy.Value).FirstOrDefault();
                    var uname = "";
                    if (usermodel != null)
                        uname = usermodel.F_UserName;
                    return new
                    {
                        F_NoticeId = m.F_NoticeId,
                        F_Title = m.F_Title,
                        F_Content = m.F_Content,
                        F_isCus = m.F_isCus,
                        F_CreateOn = m.F_CreateOn,
                        F_CreateBy = m.F_CreateBy,
                        F_CreateByName = uname
                    };
                }),
                total = recordCount
            };

            return Content(obj.ToJson());

        }

        [Authority]
        //首页获取公告
        public ActionResult GetListTop(int top)
        {
            int userID = CurrentUser.UserData.F_UserId;
            int roleId = CurrentUser.UserData.F_RoleId;
            DataTable dt = new DataTable();
            
            string sql = " F_isDel=0 and (ISNULL(F_UserId,'') = '' or ISNULL(F_UserId,'') like '%," + userID + ",%') ";
            dt = new BLL.T_Msg_NoticeInfo().GetList(top, sql, " F_NoticeId desc ").Tables[0];
            int recordCount = dt.Rows.Count;
            var obj = new
            {
                rows = dt,
                total = recordCount
            };
            return Content(obj.ToJson());

        }

        //获取公告
        public ActionResult GetNotice(string noticeid)
        {
            Model.T_Sys_UserAccount userModel = new Model.T_Sys_UserAccount();
            Model.T_Msg_NoticeInfo dModel = dBLL.GetModel(int.Parse(noticeid.Trim()));
            if (dModel != null)
            {
                if (dModel.F_CreateBy != null)
                    userModel = new BLL.T_Sys_UserAccount().GetModel(dModel.F_CreateBy.Value);
                var uname = ""; 
                if (userModel != null)
                    uname = userModel.F_UserName;
                var obj = new
                {
                    F_NoticeId = dModel.F_NoticeId,
                    F_Title = dModel.F_Title,
                    F_Content = dModel.F_Content,
                    F_isCus = dModel.F_isCus,
                    F_CreateOn = dModel.F_CreateOn,
                    F_CreateBy = dModel.F_CreateBy,
                    F_CreateByName = uname,
                    F_UserId = dModel.F_UserId,
                    F_RoleId = dModel.F_RoleId,
                };
                return Success("获取公告信息成功", obj);
            }
            else
            {
                return Error("获取公告信息失败");
            }

        }
        [Authority]
        //添加公告
        public ActionResult AddNotice(string title, string content, string userid, string roleid, int iscus = 0)
        {
            Model.T_Msg_NoticeInfo dModel = new Model.T_Msg_NoticeInfo();

            if (title != null)
                dModel.F_Title = title.Trim();
            if (content != null)
                dModel.F_Content = content.Trim();
            dModel.F_isCus = iscus;
            //添加权限
            dModel.F_RoleId = "," + roleid + ",";
            dModel.F_UserId = "," + userid + ",";
            dModel.F_CreateOn = DateTime.Now;
            dModel.F_CreateBy = CurrentUser.UserData.F_UserId;
            dModel.F_isDel = 0;
            int b = dBLL.Add(dModel);
            if (b > 0)
            {
                #region 给员工发送消息提醒
                var usercodes = new List<string>();
                if (!string.IsNullOrWhiteSpace(roleid))
                {
                    var userslist = userBLL.GetModelList(" F_RoleId in (" + roleid + ")").ToList();
                    foreach (var item in userslist)
                    {
                        usercodes.Add(item.F_UserCode);
                    }
                }
                if(!string.IsNullOrWhiteSpace(userid))
                {
                    var userslist = userBLL.GetModelList(" F_UserId in (" + roleid + ")").ToList();
                    foreach (var item in userslist)
                    {
                        usercodes.Add(item.F_UserCode);
                    }
                }

                usercodes = usercodes.Distinct().ToList();
                foreach (var item in usercodes)
                {
                    Model.T_Msg_List msg = new Model.T_Msg_List();
                    msg.Type = (int)Model.MSGType.notice;//处理
                    msg.ToUser = item;
                    msg.ToID = b;
                    msg.Detail = title.Trim();
                    msg.State = 0;
                    msg.IsDel = 0;
                    msg.CreateUser = CurrentUser.UserData.F_UserCode;
                    msg.CreateDate = DateTime.Now;

                    new BLL.T_Msg_List().Add(msg);
                }

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

        //编辑公告
        public ActionResult EditNotice(string noticeid, string title, string content, string userid, string roleid, int iscus = 0)
        {
            if (noticeid != null && noticeid.Trim() != "")
            {
                Model.T_Msg_NoticeInfo dModel = dBLL.GetModel(int.Parse(noticeid.Trim()));
                if (dModel != null)
                {
                    if (title != null)
                        dModel.F_Title = title.Trim();
                    if (content != null)
                        dModel.F_Content = content.Trim();
                    dModel.F_isCus = iscus;
                    //添加权限
                    dModel.F_RoleId = "," + roleid.Trim() + ",";//= roleid
                    dModel.F_UserId = "," + userid.Trim() + ",";//= userid
                    dModel.F_ModifyDate = DateTime.Now;
                    dModel.F_ModifyBy = CurrentUser.UserData.F_UserId;

                    bool b = dBLL.Update(dModel);
                    if (b)
                    {
                        #region 给员工发送消息提醒
                        var usercodes = new List<string>();
                        if (!string.IsNullOrWhiteSpace(roleid))
                        {
                            var userslist = userBLL.GetModelList(" F_RoleId in (" + roleid + ")").ToList();
                            foreach (var item in userslist)
                            {
                                usercodes.Add(item.F_UserCode);
                            }
                        }
                        if (!string.IsNullOrWhiteSpace(userid))
                        {
                            var userslist = userBLL.GetModelList(" F_UserId in (" + roleid + ")").ToList();
                            foreach (var item in userslist)
                            {
                                usercodes.Add(item.F_UserCode);
                            }
                        }

                        usercodes = usercodes.Distinct().ToList();
                        foreach (var item in usercodes)
                        {
                            Model.T_Msg_List msg = new BLL.T_Msg_List().GetModelList(" ToUser='"+item+ "' and ToID='"+ dModel.F_NoticeId + "' and IsDel=0 and State=0").FirstOrDefault();
                            if (msg == null)
                            {
                                msg = new Model.T_Msg_List();
                                msg.Type = (int)Model.MSGType.notice;
                                msg.ToUser = item;
                                msg.ToID = dModel.F_NoticeId;
                                msg.Detail = title.Trim();
                                msg.State = 0;
                                msg.IsDel = 0;
                                msg.CreateUser = CurrentUser.UserData.F_UserCode;
                                msg.CreateDate = DateTime.Now;

                                new BLL.T_Msg_List().Add(msg);
                            }
                            else
                            {
                                msg.Detail = title.Trim();
                                msg.State = 0;
                                new BLL.T_Msg_List().Update(msg);
                            }
                        }
                        #endregion
                        return Success("编辑成功");
                    }
                    else
                    {
                        return Success("编辑失败");
                    }
                }
                else
                    return Error("获取信息失败");
            }
            else
            {
                return Error("请选择要编辑的知识库分类");
            }

        }
        [Authority]
        //删除公告
        public ActionResult DelNotice(string[] ids)
        {
            if (ids != null && ids.Length > 0)
            {
                string idds = "";
                for (int i = 0; i < ids.Length; i++)
                {
                    idds += ids[i] + ",";
                }
                bool r = dBLL.DeleteList(idds.Trim(','));

                if (r)
                {
                    //若通知删除则取消消息提醒
                    DbHelperSQL.ExecuteSql("update T_Msg_List set IsDel=1 where ToID in (" + idds.Trim(',') + ") and Type=5");
                    return Success("删除成功");
                }
                else
                {
                    return Error("删除失败");
                }
            }
            else
            {
                return Error("获取参数失败");
            }

        }
    }
}