
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using ZXDT.CallCenter.Model;
using ZXDT.CallCenter.MVCWeb.Models;
using ZXDT.Common;

namespace ZXDT.CallCenter.MVCWeb.Controllers
{
    public class BaseController : Controller
    {
        //字典表
        BLL.T_Sys_DictionaryValue dicValueBll = new BLL.T_Sys_DictionaryValue();
        BLL.T_Sys_SystemConfig bll_T_Sys_SystemConfig = new BLL.T_Sys_SystemConfig();
        BLL.T_Com_LogAction busLog = new BLL.T_Com_LogAction();

        /// <summary>
        /// 时间转换
        /// </summary>
        private JsonSerializerSettings timeConvert = new JsonSerializerSettings() { DateFormatString = "yyyy'-'MM'-'dd' 'HH':'mm':'ss" };


        #region 登录用户信息

        private int _f_UserID;
        private string _userName;
        private string _f_UserCode;
        private int _roleId;
        private int _f_DeptId;
        private string _f_Telephone;
        private bool _f_SeatFlag;
        /// <summary>
        /// 用户id
        /// </summary>
        public int F_UserID
        {
            get
            {
                //从cookie集合中读取用户信息
                HttpCookie loginInfoCookies = Request.Cookies["BaseCallCenter_T_User"];
                if (loginInfoCookies != null)
                {

                    _f_UserID = int.Parse(loginInfoCookies.Values["F_UserID"]);
                }

                return _f_UserID;
            }
            set { _f_UserID = value; }
        }

        /// <summary>
        /// 用户账号
        /// </summary>
        public string F_UserCode
        {
            get
            {
                //从cookie集合中读取用户信息
                HttpCookie loginInfoCookies = Request.Cookies["BaseCallCenter_T_User"];
                if (loginInfoCookies != null)
                {
                    _f_UserCode = loginInfoCookies.Values["F_UserCode"];
                }
                return _f_UserCode;
            }
            set { _f_UserCode = value; }
        }
        /// <summary>
        /// 部门Id
        /// </summary>
        public int F_DeptId
        {
            get
            {
                //从cookie集合中读取用户信息
                HttpCookie loginInfoCookies = Request.Cookies["BaseCallCenter_T_User"];
                if (loginInfoCookies != null)
                {
                    _f_DeptId = int.Parse(loginInfoCookies.Values["F_DeptId"]);
                }
                return _f_DeptId;
            }
            set { _f_DeptId = value; }
        }

        /// <summary>
        /// 用户名
        /// </summary>
        public string F_UserName
        {
            get
            {
                //从cookie集合中读取用户信息
                HttpCookie loginInfoCookies = Request.Cookies["BaseCallCenter_T_User"];
                if (loginInfoCookies != null)
                {
                    _userName = HttpUtility.UrlDecode(HttpUtility.UrlDecode(loginInfoCookies.Values["F_UserName"], Encoding.UTF8));
                }

                return _userName;
            }
            set { _userName = value; }
        }



        /// <summary>
        /// 电话
        /// </summary>
        public string F_Telephone
        {
            get
            {
                //从cookie集合中读取用户信息
                HttpCookie loginInfoCookies = Request.Cookies["BaseCallCenter_T_User"];
                if (loginInfoCookies != null)
                {
                    _f_Telephone = loginInfoCookies.Values["F_Telephone"];
                }

                return _f_Telephone;
            }
            set { _f_Telephone = value; }
        }

        /// <summary>
        /// 角色Id
        /// </summary>
        public int F_RoleID
        {
            get
            {
                //从cookie集合中读取用户信息
                HttpCookie loginInfoCookies = Request.Cookies["BaseCallCenter_T_User"];
                if (loginInfoCookies != null)
                {
                    _roleId = int.Parse(loginInfoCookies.Values["F_RoleID"]);
                }
                return _roleId;
            }
            set { _roleId = value; }
        }


        private int _f_Id;
        /// <summary>
        ///微信微博映射id
        /// </summary>
        public int F_PId
        {
            get
            {
                //从cookie集合中读取用户信息
                HttpCookie loginInfoCookies = Request.Cookies["BaseCallCenter_T_User"];
                if (loginInfoCookies != null)
                {
                    _f_Id = loginInfoCookies.Values["F_PId"].ToInt32();
                }
                return _f_Id;
            }
            set { _f_Id = value; }
        }


        /// <summary>
        /// 坐席标志
        /// </summary>
        public bool F_SeatFlag
        {
            get
            {
                //从cookie集合中读取用户信息
                HttpCookie loginInfoCookies = Request.Cookies["BaseCallCenter_T_User"];
                if (loginInfoCookies != null)
                {
                    _f_SeatFlag = bool.Parse(loginInfoCookies.Values["F_SeatFlag"]);
                }
                return _f_SeatFlag;
            }
            set { _f_SeatFlag = value; }
        }




        #endregion

        #region 验证用户是否已经登录

        /// <summary>
        /// Action执行前判断
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (!this.checkLogin())// 判断是否登录
            {
                filterContext.Result = RedirectToRoute("Default", new { Controller = "Default", Action = "SSO" });
            }
            base.OnActionExecuting(filterContext);

        }


        /// <summary>
        /// 判断是否登录
        /// </summary>
        protected bool checkLogin()
        {
            HttpCookie loginInfoCookies = Request.Cookies["BaseCallCenter_T_User"];//用户信息
            if (loginInfoCookies != null)
            {
                return true;
            }
            else
            {
                return false;
            }

        }



        /// <summary>
        /// 退出登录
        /// </summary>
        /// <returns></returns>
        public void Exit()
        {
            HttpCookie loginInfoCookies = Request.Cookies["BaseCallCenter_T_User"];//用户信息
            if (loginInfoCookies != null)
            {
                loginInfoCookies.Expires = DateTime.Now.AddDays(-1);
                Response.Cookies.Add(loginInfoCookies);
            }

        }
        #endregion

        #region 公共方法
        #region 获取业务类型
        /// <summary>
        /// 获取业务类型
        /// </summary>
        public List<Model.T_Wo_WorkOrderType> GetWorkTypeModelList()
        {
            //最终需要返回的菜单
            List<Model.T_Wo_WorkOrderType> newModelList = new List<T_Wo_WorkOrderType>();

            Model.PageData<Model.T_Wo_WorkOrderType> pageModel = new Model.PageData<Model.T_Wo_WorkOrderType>();
            BLL.T_Wo_WorkOrderType bll = new BLL.T_Wo_WorkOrderType();
            //获取业务类型列表
            List<Model.T_Wo_WorkOrderType> WorkTypeModelList = bll.GetModelList("");

            if (WorkTypeModelList != null && WorkTypeModelList.Count > 0)
            {
                //获取默认根节点
                Model.T_Wo_WorkOrderType rootNode = WorkTypeModelList.FirstOrDefault(m => m.F_ParentId == 0);
                //获取一级节点
                List<Model.T_Wo_WorkOrderType> rootModelList = WorkTypeModelList.Where(t => t.F_ParentId == rootNode.F_WorkOrderTypeId).ToList();
                if (rootModelList != null && rootModelList.Count > 0)
                {
                    foreach (T_Wo_WorkOrderType WorkOrderTypeModel in rootModelList)
                    {
                        List<Model.T_Wo_WorkOrderType> nullModelList = new List<T_Wo_WorkOrderType>();
                        WorkOrderTypeModel.WorkTypeModelList = nullModelList;
                        newModelList.Add(GetWorkTypeModelChild(WorkOrderTypeModel, WorkOrderTypeModel, WorkTypeModelList));
                    }
                }
            }
            return newModelList;
        }

        //获取所有子集
        public Model.T_Wo_WorkOrderType GetWorkTypeModelChild(T_Wo_WorkOrderType rootNode, T_Wo_WorkOrderType WorkOrderTypeModel, List<Model.T_Wo_WorkOrderType> WorkTypeModelList)
        {
            //获取子集节点
            List<Model.T_Wo_WorkOrderType> sonModelList = WorkTypeModelList.Where(t => t.F_ParentId == WorkOrderTypeModel.F_WorkOrderTypeId).ToList();

            if (sonModelList != null && sonModelList.Count > 0)
            {
                foreach (T_Wo_WorkOrderType workOrderTypeModel in sonModelList)
                {
                    //获取子子集
                    List<Model.T_Wo_WorkOrderType> childModelList = WorkTypeModelList.Where(t => t.F_ParentId == workOrderTypeModel.F_WorkOrderTypeId).ToList();

                    if (childModelList != null && childModelList.Count > 0)
                    {
                        GetWorkTypeModelChild(rootNode, workOrderTypeModel, WorkTypeModelList);
                    }
                    else
                    {
                        rootNode.WorkTypeModelList.Add(workOrderTypeModel);
                    }


                }

            }

            return rootNode;
        }
        #endregion


        #region 获取处理类型字典

        /// <summary>
        /// 获取处理类型字典
        /// </summary>
        /// <returns></returns>
        public List<T_Sys_DictionaryValue> GetCodeType(string dicCodeType)
        {

            return dicValueBll.GetModelList("F_DictionaryFlag='" + dicCodeType + "'");

        }
        #endregion



        /// <summary>
        ///  根据key获取网站基础配置值
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public string GetSysconfig(string key)
        {
            return bll_T_Sys_SystemConfig.GetParamValueByParamCode(key);
        }


        /// <summary>
        /// 数据库日志
        /// </summary>
        /// <param name="TableName"></param>
        /// <param name="id"></param>
        /// <param name="ActionName"></param>
        /// <param name="oldobj"></param>
        /// <param name="newobj"></param>
        /// <returns></returns>
        public bool AddLog(string TableName, string id,string ActionName,string oldobj,object newobj)
        {
            Model.T_Com_LogAction modellog = new T_Com_LogAction();
            modellog.ActionName = ActionName;            
            modellog.AddUser = HttpUtility.UrlDecode(F_UserName);
            modellog.AddUserId = F_UserID;
            modellog.Atime = DateTime.Now;
            modellog.ActionUrl = string.Format("/{0}/{1}", RouteData.Values["controller"], RouteData.Values["action"]);
            modellog.ContentNew = newobj == null ? "":JsonConvert.SerializeObject(newobj);
            modellog.ContentOld = oldobj == null ?  "": oldobj;
            modellog.TableId = id;
            modellog.TableName = TableName.ToLower();

            return busLog.Add(modellog);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="TableName"></param>
        /// <param name="id"></param>
        /// <param name="ActionName"></param>
        /// <param name="oldobj"></param>
        /// <param name="ContentNew">操作记录  敏感信息 主要设置</param>
        /// <returns></returns>
        public bool AddAction(string TableName, string id, string ActionName, string oldobj="",string ContentNew= "操作记录")
        {
            Model.T_Com_LogAction modellog = new T_Com_LogAction();
            modellog.ActionName = ActionName;
            modellog.AddUser = HttpUtility.UrlDecode(F_UserName);
            modellog.AddUserId = F_UserID;
            modellog.Atime = DateTime.Now;
            modellog.ActionUrl = string.Format("/{0}/{1}", RouteData.Values["controller"], RouteData.Values["action"]);
            modellog.ContentNew = ContentNew;
            modellog.ContentOld = oldobj.ToMyString();
            modellog.TableId = id.ToMyString();
            modellog.TableName = TableName.ToLower();

            return busLog.Add(modellog);
        }

        #endregion

        #region 公共返回参数
        /// <summary>
        /// 成功的消息格式化
        /// </summary>
        /// <param name="message"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        protected virtual string Success(string message, object data=null,int count=0)
        {
            var jsonMsg = new ReturnData { code =0, msg = message, data = data ,count= count };
            // LogDefault.Info(jsonMsg);
            return JsonConvert.SerializeObject(jsonMsg, timeConvert);
        }

        /// <summary>
        /// 成功的消息格式化
        /// </summary>
        /// <param name="message"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        protected virtual string Success(string message)
        {
            var jsonMsg = new ReturnData { code = 0, msg = message };
            // LogDefault.Info(jsonMsg);
            return JsonConvert.SerializeObject(jsonMsg, timeConvert);
        }

        /// <summary>
        /// 错误的消息格式化
        /// </summary>
        /// <param name="message"></param>
        /// <returns></returns>
        protected virtual string Error(string message)
        {
            var jsonMsg = new ReturnData { code = -1, msg = message };
            return JsonConvert.SerializeObject(jsonMsg);
        }
        #endregion
    }

}
