using CallCenter.Utility;
using CallCenterApi.Common;
using CallCenterApi.DB;
using CallCenterApi.Interface.Controllers.Base;
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 NoticeController : BaseController
    {
        private BLL.T_Sys_SystemConfig configBll = new BLL.T_Sys_SystemConfig();
        BLL.T_Msg_NoticeInfo dBLL = new BLL.T_Msg_NoticeInfo();
        private BLL.T_Sys_RoleInfo rolebll = new BLL.T_Sys_RoleInfo();
        /// <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)
            {
                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 datetime)
        {
            DataTable dt = new DataTable();
            string strpageindex = RequestString.GetQueryString("page");
            int pageindex = 1;
            string strpagesize = RequestString.GetQueryString("pagesize");
            int pagesize = 10;
            string sql = " ";
            if (datetime != null && datetime.Trim() != "")
            {
                sql += " and Datediff(day,F_Startdate,'" + datetime.Trim() + "')>=0";
                sql += " and Datediff(day,F_Enddate,'" + datetime.Trim() + "')<=0";
            }
            //else
            //{
            //    sql += " and Datediff(day,F_Startdate,getdate())>=0";
            //    sql += " and Datediff(day,F_Enddate,getdate())<=0";
            //}

            if (strpageindex.Trim() != "")
            {
                pageindex = Convert.ToInt32(strpageindex);
            }
            if (strpagesize.Trim() != "")
            {
                pagesize = Convert.ToInt32(strpagesize);
            }
            int recordCount = 0;
            dt = BLL.PagerBLL.GetListPager(
                "T_Msg_NoticeInfo a",
                "F_NoticeId",
                "*,dbo.GetUserNameByID(F_CreateBy) as F_CreateByName",
                sql,
                "ORDER BY F_NoticeId desc",
                pagesize,
                pageindex,
                true,
                out recordCount);
            var obj = new
            {
                rows = dt,
                total = recordCount
            };
            return Content(obj.ToJson());

        }

        [Authority]
        //首页获取公告
        public ActionResult GetListTop(int top)
        {
            int userID = User.F_UserId, roleId = User.F_RoleId;
            DataTable dt = new DataTable();
            //string sql = " 1 = 1 and (ISNULL(F_RoleId,0) = 0 or ISNULL(F_RoleId,0) = " + roleId + ") and (ISNULL(F_UserId,0) = 0 or ISNULL(F_UserId,0) = " + userID + ") ";

            string sql = " 1 = 1 and (ISNULL(F_UserId,'') = '' or ISNULL(F_UserId,'') like '%," + userID + ",%') ";
            //and(ISNULL(F_RoleId, '') = '' or ISNULL(F_RoleId, '') like '%," + roleId + ",%')

            sql += " and Datediff(day,F_Startdate,getdate())>=0";
            sql += " and Datediff(day,F_Enddate,getdate())<=0";
            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 User = new Model.T_Sys_UserAccount();
            Model.T_Msg_NoticeInfo dModel = dBLL.GetModel(int.Parse(noticeid.Trim()));
            if (dModel != null)
            {
                if (dModel.F_CreateBy != null)
                    User = new BLL.T_Sys_UserAccount().GetModel(dModel.F_CreateBy.Value);
                var uname = ""; var sdate = ""; var edate = "";
                if (User != null)
                    uname = User.F_UserName;
                if (dModel.F_StartDate != null)
                    sdate = dModel.F_StartDate.Value.ToString("yyyy-MM-dd");
                if (dModel.F_EndDate != null)
                    edate = dModel.F_EndDate.Value.ToString("yyyy-MM-dd");
                var configfj = configBll.GetModelList(" F_ParamCode='FileUrlPath' ").FirstOrDefault();
                if (dModel.F_Frequency != null)
                    dModel.F_Frequency = dModel.F_Frequency + 1;
                else
                    dModel.F_Frequency = 1;
                new BLL.T_Msg_NoticeInfo().Update(dModel);
                     DataTable dt = new DataTable();
                if (configfj != null)
                {
                   dt = BindFileData(dt,dModel.F_File , configfj.F_ParamValue);
                }
                var obj = new
                {
                    F_NoticeId = dModel.F_NoticeId,
                    F_Title = dModel.F_Title,
                    F_Content = dModel.F_Content,
                    F_StartDate = sdate,
                    F_EndDate = edate,
                    F_CreateOn = dModel.F_CreateOn,
                    F_CreateBy = dModel.F_CreateBy,
                    F_CreateByName = uname,
                    F_UserId =  dModel.F_UserId  ,//== null ? 0 : dModel.F_UserId,
                    F_RoleId =  dModel.F_RoleId  ,// == null ? 0 : dModel.F_RoleId,
                    F_FilePath= dt,
                    F_Frequency = dModel.F_Frequency
                };
                return Success("获取公告信息成功", obj);
            }
            else
            {
                return Error("获取公告信息失败");
            }
        }
        /// <summary>
        /// 绑定附件信息
        /// </summary>
        /// <param name="dt"></param>
        /// <param name="prefix"></param>
        /// <returns></returns>
        public DataTable BindFileData(DataTable dt ,string F_File, string prefix)
        {
           
           if (!string .IsNullOrEmpty (F_File))
            {
               
                dt = GetFileData(F_File, prefix);
            }
            else
            {
                return null;
            }
           
            return dt;
        }
        /// <summary>
        /// 获取附件数据
        /// </summary>
        /// <param name="ids">附件id，多个用英文逗号,隔开</param>
        /// <param name="prefix">前缀</param>
        /// <returns></returns>
        public DataTable GetFileData(string ids, string prefix)
        {
            DataTable dt = DbHelperSQL.Query("select * from T_Sys_Accessories WITH(NOLOCK) where F_FileId in (" + ids + ")").Tables[0];

            foreach (DataRow dr in dt.Rows)
            {
                dr["F_FileUrl"] = prefix + dr["F_FileUrl"].ToString();
            }

            return dt;
        }
        [Authority]
        //添加公告
        public ActionResult AddNotice(string title, string content, string stime, string etime, string userid, string roleid,string file)
        {
            Model.T_Msg_NoticeInfo dModel = new Model.T_Msg_NoticeInfo();
            //int userId = 0, roleId = 0;
            //int.TryParse(userid, out userId);
            //int.TryParse(roleid, out roleId);

            if (title != null)
                dModel.F_Title = title.Trim();
            if (content != null)
                //dModel.F_Content = content.Trim();
                dModel.F_Content= WebHelper.UrlDecode(content);

            if (stime != null)
                dModel.F_StartDate = DateTime.Parse(stime);
            if (etime != null)
                dModel.F_EndDate = DateTime.Parse(etime);
            //添加权限
            dModel.F_RoleId = "," + roleid + ",";
            dModel.F_UserId = "," + userid + ",";
            dModel.F_File = file;
            dModel.F_CreateOn = DateTime.Now;
            dModel.F_CreateBy = User.F_UserId;
            dModel.F_Frequency = 0;
            int b = dBLL.Add(dModel);
            if (b > 0)
            {
                return Success("添加成功");
            }
            else
            {
                return Success("添加失败");
            }
        }

        //编辑公告
        public ActionResult EditNotice(string nid, string title, string content, string stime, string etime, string userid, string roleid,string file)
        {
            if (nid != null && nid.Trim() != "")
            {
                Model.T_Msg_NoticeInfo dModel = dBLL.GetModel(int.Parse(nid.Trim()));
                if (dModel != null)
                {
                    if (title != null)
                        dModel.F_Title = title.Trim();
                    if (content != null)
                        //dModel.F_Content = content.Trim();
                        dModel.F_Content = WebHelper.UrlDecode(content);
                    if (stime != null)
                        dModel.F_StartDate = DateTime.Parse(stime);
                    if (etime != null)
                        dModel.F_EndDate = DateTime.Parse(etime);
                    dModel.F_File = file;
                    //添加权限
                    dModel.F_RoleId = "," + roleid.Trim() + ",";//= roleid
                    dModel.F_UserId = "," + userid.Trim() + ",";//= userid
                    dModel.F_ModifyDate = DateTime.Now;
                    if (dModel.F_Frequency >0)
                        dModel.F_Frequency = dModel.F_Frequency - 1;
                    //  dModel.F_ModifyBy = User.F_UserId;
                    bool b = dBLL.Update(dModel);
                    if (b)
                    {
                        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)
                    return Success("删除成功");
                else
                {
                    return Error("删除失败");
                }
            }
            else
            {
                return Error("获取参数失败");
            }

        }

        #region 官网接口
        //首页获取公告
        public ActionResult GetWebListTop(int top)
        {
            DataTable dt = new DataTable();
            string sql = " 1=1 ";
            sql += " and Datediff(day,F_Startdate,getdate())>=0";
            sql += " and Datediff(day,F_Enddate,getdate())<=0";
            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());
        }
        #endregion
    }
}