using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Mvc.Html;
using QMAPP.BLL.QueryTL;
using QMAPP.BLL.Sys;
using QMAPP.Common.Web.Models;
using QMAPP.Entity.QueryTL;
using QMAPP.Entity.Sys;
using QMFrameWork.Common.Util;
using QMFrameWork.Data;
using QMFrameWork.InfoValidate;
using QMFrameWork.WebUI;
using QMFrameWork.WebUI.Attribute;
using QMFrameWork.WebUI.Menu;
using QMFrameWork.WebUI.Util;


namespace QMAPP.Common.Web.Controllers
{
    public class QController:Controller
    {
        public static string ManageCenterRoot { get; set; }

        /// <summary>
        /// 应用程序物理路径
        /// </summary>
        public static string PhysicsRootPath { get; set; }

        #region 模型相关

        /// <summary>
        /// 拷贝原类对象到目标类
        /// </summary>
        /// <typeparam name="T">目标类型</typeparam>
        /// <typeparam name="TModel">原类型</typeparam>
        /// <param name="Model">原对象</param>
        /// <returns>目标对象</returns>
        public T CopyToModel<T, TModel>(TModel Model) where T : new()
        {

            return CopyToModel<T, TModel>(Model, false);
        }

        /// <summary>
        /// 拷贝原类对象到目标类
        /// </summary>
        /// <typeparam name="T">目标类类型</typeparam>
        /// <typeparam name="TModel">原类类型</typeparam>
        /// <param name="Model">原类类型对象</param>
        /// <returns>目标类</returns>
        public T CopyToModel<T, TModel>(TModel Model, bool formatDictionary) where T : new()
        {
            return BindHelper.CopyToModel<T, TModel>(Model, formatDictionary);
        }

        /// <summary>
        /// 获取
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public T GetModel<T>(T model) where T : new()
        {
            return UiBindHelper.GetModel<T>(model, Request);
        }

        /// <summary>
        /// 获取
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public T GetModel<T>() where T : new()
        {
            return UiBindHelper.GetModel<T>(new T(), Request);
        }

        #endregion

        #region 设置消息

        /// <summary>
        /// 设置消息
        /// </summary>
        /// <param name="pMessage"></param>
        public void SetMessage(string pMessage)
        {

            ViewData["QMSMessage"] = pMessage;
        }

        #endregion

        #region 权限控制

        /// <summary>
        /// 当前的Action是否由当前请求发起
        /// </summary>
        /// <returns></returns>
        public bool IsRequestBack()
        {
            try
            {
                if (Request.UrlReferrer == null)
                {
                    return true;
                }
                if (Request.UrlReferrer.LocalPath == "/Home/Main")
                {
                    return true;
                }
                return this.Request.Url.LocalPath == Request.UrlReferrer.LocalPath;
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.Write(ex);
                throw;
            }
        }

        /// <summary>
        /// Action执行时
        /// </summary>
        /// <param name="filterContext"></param>
        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            MenuHelper menuHelper = new MenuHelper();
            string sessionid = HttpContext.Session.SessionID;
            string isLogin = Request.Params["isLogin"];

            //action校验
            string controler = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            string action = filterContext.ActionDescriptor.ActionName;
            //20180124 周晓东增加直接访问大屏幕
            if (controler != "AndonDisplay" && controler != "TempCallLog" && controler != "ShipmentMonitor" && controler != "PackageDisplay")
            {
                //验证当前请求是否有登录信息
                if (AccountController.IsLogin() == false
                    || string.IsNullOrEmpty(AccountController.GetLoginInfo().UserID) == true
                    || string.IsNullOrEmpty(isLogin) == false)
                {
                    //验证登录
                    string sessionID = Request.Params["sessionID"];
                    QMAPP.ServicesAgent.LoginService.LoginInfo remoteLogin = null;

                    if (string.IsNullOrEmpty(sessionID) == false)
                    {
                        //修改登录验证为平台登录方式 2018-9-13 by 张鹏
                        //QMAPP.ServicesAgent.LoginService.LoginServiceClient loginClient =
                        //    new ServicesAgent.LoginService.LoginServiceClient();

                        //获取远程登录信息
                        QMFrameWork.ServiceInterface.CredentialInfo c =
                            new QMFrameWork.ServiceInterface.CredentialInfo();
                        c.CredentialID = sessionID;

                        //修改登录验证为平台登录方式 2018-9-13 by 张鹏
                        //remoteLogin = loginClient.GetLoginInfo(c);
                        remoteLogin = QMAPP.ServicesAgent.LoginService.LoginServiceClient._GetLoginInfo(c);

                        if (remoteLogin != null)
                        {
                            LoginInfo login = new LoginInfo();
                            login.UserID = remoteLogin.UserID;
                            login.LoginUserID = remoteLogin.LoginUserID;
                            login.UserName = remoteLogin.UserName;
                            login.PassWord = remoteLogin.PassWord;
                            login.UserDes = remoteLogin.UserDes;
                            login.ServiceSessionID = remoteLogin.ServiceSessionID;
                            //20140310 wangyunfenf 注释下边代码方便排班计划测试 end

                            //设置登录信息
                            AccountController.SetLoginInfo(login);

                            //将权限放入到session中

                            if (remoteLogin.LoginUserID.ToUpper() != "ADMIN")
                            {
                                menuHelper.Powers = new List<string>();
                                foreach (string powerID in remoteLogin.Powers)
                                {
                                    menuHelper.Powers.Add(powerID);
                                }
                            }

                            menuHelper.GetMenuInfos();

                            Hashtable actionArray = menuHelper.GetActionList();

                            AccountController.SetLimit(actionArray);
                        }
                    }

                    if (remoteLogin == null)
                    {
                        //登录信息不正确
                        string platformroot = System.Configuration.ConfigurationManager.AppSettings["PlatformRoot"];
                        if (platformroot != null
                            && Request.UrlReferrer != null
                            && Request.UrlReferrer.AbsoluteUri.Contains(platformroot)) //如果页面请求来自平台则跳转到平台登录页
                        {
                            Response.Write("<script language=\"javascript\">top.window.location.href=\"" + platformroot +
                                               "Home/Login/\";</script>");
                        }
                        else
                        {
                            Response.Write("<script language=\"javascript\">top.window.location.href=\"" + ManageCenterRoot +
                                           "Home/Login/\";</script>");
                        }
                        Response.End();
                        return;
                    }
                }
            }


            //校验是否为权限受限ation
            Hashtable actions = new MenuHelper().GetAllActions();

            if (actions.ContainsKey(controler + "/" + action) == true)
            {
                Hashtable actionList = AccountController.GetLimit();

                if (actionList != null)
                {
                    bool flag = actionList.ContainsValue(controler + "/" + action);

                    if (flag == false)
                    {
                        //无权限
                        Response.Write("<script language=\"javascript\">alert('你无权访问此页面!');self.window.location.href=\"/\";</script>");
                        Response.End();
                    }
                }
            }

            //20180421闫永刚 
            if (controler != "Login" && controler != "Notice" && controler != "Dict")
            {

                FunctionRecorder recorder = new FunctionRecorder();
                recorder.PID = Guid.NewGuid().ToString();
                recorder.CONTROLLER = controler;
                recorder.ACTION = action;
                recorder.CREATEDATE = System.DateTime.Now;
                recorder.USERID = (controler != "AndonDisplay" && controler != "TempCallLog" && controler != "ShipmentMonitor" && controler != "PackageDisplay") ? AccountController.GetLoginInfo().UserID : "";

                QMAPP.ServicesAgent.ServiceAgent agent = this.GetServiceAgent();
                agent.InvokeServiceFunction("FunctionRecorderBLL_Insert", recorder);
            }
        }

        #endregion

        #region 缓存搜索条件

        /// <summary>
        /// 缓存搜索条件
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="model"></param>
        public void SetSelectBuffer<T>(T model)
        {
            Type temp = typeof(T);
            string keyStr = temp.Namespace + temp.Name;
            ViewBuffer.setViewBuffer(keyStr, model);

        }

        public bool TryGetSelectBuffer<T>(out T model) where T : new()
        {
            Type temp = typeof(T);
            string keyStr = temp.Namespace + temp.Name;

            Type TTemp = typeof(T);

            if (!ViewBuffer.IsViewBuffer(keyStr))
            {
                model = new T();

                return true;
            }
            else
            {
                model = ViewBuffer.GetViewBuffer<T>(keyStr);

                var proper = TTemp.GetProperty("pageCallBack");

                if (proper != null)
                {
                    proper.SetValue(model, true, null);
                }


                return false;
            }

        }

        #endregion

        #region 获取脚本执行视图结果

        public ViewResult GetJsViewResult(string js)
        {
            return new ViewResult
            {
                ViewName = "ExecuteJS",
                MasterName = "Site",
                ViewData = new ViewDataDictionary<JavaScriptResult>(JavaScript(js)),

            };
        }

        #endregion

        #region 获取域信息

        /// <summary>
        /// 获取域信息
        /// </summary>
        /// <returns>域信息</returns>
        public DomainIdentity GetDomainIdentity()
        {
            DomainIdentity info = new DomainIdentity();
            try
            {
                string domainAndName = User.Identity.Name;
                string[] infoes = domainAndName.Split(new char[1] { '/' }, StringSplitOptions.RemoveEmptyEntries);

                if (infoes.Length > 1)
                {
                    info.DomainName = infoes[0];
                    info.UserName = infoes[1];
                }
                return info;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion

        #region 获取分页设置信息

        /// <summary>
        /// 获取分页设置信息
        /// </summary>
        /// <param name="model">模型</param>
        /// <returns>分页设置信息</returns>
        public DataPage GetDataPage(QDGModel model)
        {
            DataPage page = new DataPage();

            if (string.IsNullOrEmpty(model.InitPageSize) == true)
            {
                if (string.IsNullOrEmpty(ConfigurationManager.AppSettings["PageSize"]) == false)
                    model.InitPageSize = ConfigurationManager.AppSettings["PageSize"];
                else
                    model.InitPageSize = "15";
            }

            int pageSize = 0;

            if (!Int32.TryParse(model.pageSize, out pageSize))
            {
                pageSize = int.Parse(model.InitPageSize);
            }
            int pageNumber = 0;
            if (!Int32.TryParse(model.pageNumber, out pageNumber))
            {
                pageNumber = 1;
            }

            if (string.IsNullOrEmpty(model.pageSort) == false)
            {
                page.SortExpression = model.pageSort;
            }
            else
            {
                //从模板提取
                QueryTemplateModel qtModel = SessionHelper.GetSession("QueryTemplate") as QueryTemplateModel;

                if (qtModel != null)
                    page.SortExpression = qtModel.GetSortExpression();
            }

            page.PageSize = pageSize;
            page.PageIndex = pageNumber;

            return page;
        }

        #endregion

        #region 获取服务代理

        public ServicesAgent.ServiceAgent GetServiceAgent()
        {
            try
            {
                //创建代理
                ServicesAgent.ServiceAgent agent = new ServicesAgent.ServiceAgent();

                //设置凭据
                agent.ClientCredential = new QMFrameWork.ServiceInterface.CredentialInfo();
                QMAPP.Entity.Sys.LoginInfo login = AccountController.GetLoginInfo();
                if (login != null)
                {
                    agent.ClientCredential.UserID = login.UserID;
                    agent.ClientCredential.UserName = login.LoginUserID;
                    agent.ClientCredential.PassWord = login.PassWord;
                }
                agent.ClientCredential.CredentialID = System.Web.HttpContext.Current.Session.SessionID;

                return agent;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion

        #region 获取登录凭据

        public QMFrameWork.ServiceInterface.CredentialInfo GetCredentialInfo()
        {
            QMFrameWork.ServiceInterface.CredentialInfo credential = new QMFrameWork.ServiceInterface.CredentialInfo();
            credential.CredentialID = System.Web.HttpContext.Current.Session.SessionID;

            return credential;
        }

        #endregion

        #region 写入操作日志
        /// <summary>
        /// 写入操作日志
        /// </summary>
        public void RecordSystemOperateLog(string OperateType, string OperateContent, string Remark)
        {
            try
            {
                string IPAddress = Request.UserHostAddress.ToString();
                SystemOperateLog log = SetModel(IPAddress, OperateType, OperateContent, Remark);
                SystemOperateLogBLL bll = BLLFactory.CreateBLL<SystemOperateLogBLL>();
                bll.Insert(log);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion

        #region 设置操作日志属性
        /// <summary>
        /// 设置操作日志属性
        /// </summary>
        /// <param name="ClientIP"></param>
        /// <param name="OperateType"></param>
        /// <param name="OperateContent"></param>
        /// <param name="Remark"></param>
        /// <returns></returns>
        public SystemOperateLog SetModel(string ClientIP, string OperateType, string OperateContent, string Remark)
        {
            try
            {
                SystemOperateLog retModel = new SystemOperateLog();
                retModel.ClientIP = ClientIP;
                retModel.OperateType = OperateType;
                retModel.OperateContent = OperateContent;
                retModel.Remark = Remark;
                return retModel;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        #endregion

        #region 应用查询模板

        public T ApplyQueryTemplate<T>(string programName, T searchModel, string templateID) where T : new()
        {
            QueryTemplateBLL qtBll = BLLFactory.CreateBLL<QueryTemplateBLL>();

            if (string.IsNullOrEmpty(templateID) == true)
            {
                //获取默认模板
                templateID = qtBll.GetProgramTemplate(programName);
            }
            else
            {
                //设置默认模板
                ProgramTemplate pt = new ProgramTemplate();
                pt.QUERYPROGRAM = programName;
                pt.TEMPLATEID = templateID;

                qtBll.SetProgramTemplate(pt);
            }

            if (string.IsNullOrEmpty(templateID) == true || templateID == "null")
            {
                return searchModel;
            }

            //应用查询模板
            QueryTemplateModel qtModel = null;
            qtModel = this.GetQuerySetInfo(typeof(T), templateID);

            if (qtModel != null)
            {
                (searchModel as QDGModel).ColumnList = qtModel.GridColumns;
                (searchModel as QDGModel).pageSort = qtModel.GetSortExpression();
                (searchModel as QDGModel).pageSize = qtModel.PAGESIZE;

                qtModel.ModelName = searchModel.ToString();
                SessionHelper.SetSession("QueryTemplate", qtModel);
            }

            return searchModel;
        }

        #endregion

        #region 获取查询模板设置

        /// <summary>
        /// 获取查询模板设置
        /// </summary>
        /// <param name="templateID"></param>
        /// <returns></returns>
        public QueryTemplateModel GetQuerySetInfo(Type t, string templateID)
        {
            List<DGColumn> myColumns = new List<DGColumn>();
            QueryTemplateModel model = new QueryTemplateModel();
            model.GridColumns = QGridView.GetColDefinitions(t);

            //获取模板信息
            QueryTemplate template = new QueryTemplate();
            template.TEMPLATEID = templateID;
            QueryTemplateBLL qtBll = null;
            qtBll = BLLFactory.CreateBLL<QueryTemplateBLL>();
            template = qtBll.Get(template);

            if (template == null)
                return null;

            //设置分页尺寸
            model.PAGESIZE = template.PAGESIZE.ToString();

            #region 绑定列设置信息

            foreach (TemplateColumn item in template.Columns)
            {
                DGColumn find = model.GridColumns.Find(p => p.ColumnName == item.COLUMNNAME);
                switch (item.DATAALIGN)
                {
                    case "left":
                        find.DataAlign = DataAlign.left;
                        break;
                    case "right":
                        find.DataAlign = DataAlign.right;
                        break;
                    case "center":
                        find.DataAlign = DataAlign.center;
                        break;
                }
                find.frozenColumns = item.ISFROZEN == "1" ? true : false;
                find.Hidden = item.ISHIDDEN == "1" ? true : false;
                find.Width = item.WIDTH;
                myColumns.Add(find);
            }


            myColumns.InsertRange(0, model.GridColumns.Where(p => p.Hidden == true));

            model.GridColumns = myColumns;

            #endregion

            #region 设置查询条件信息

            model.Wheres = new List<TemplateWhereModel>();
            foreach (TemplateWhere item in template.Wheres)
            {
                TemplateWhereModel where = new TemplateWhereModel();
                where.QUERYCOLUMN = item.QUERYCOLUMN;
                where.ISDISPLAY = item.ISDISPLAY;

                model.Wheres.Add(where);
            }

            #endregion

            #region 设置排序信息

            model.Sorts = new List<TemplateSortModel>();
            foreach (TemplateSort item in template.Sorts)
            {
                TemplateSortModel sort = new TemplateSortModel();
                sort.COLUMNNAME = item.COLUMNNAME;
                sort.SORTMODE = item.IFASC == "1" ? "ASC" : "DESC";
                model.Sorts.Add(sort);
            }

            #endregion

            return model;
        }

        #endregion

        #region 根据excel文件获取datatable数据

        /// <summary>
        /// 根据excel文件获取datatable数据
        /// </summary>
        /// <param name="infoName"></param>
        /// <param name="file"></param>
        /// <param name="dt"></param>
        /// <returns></returns>
        public DataTable GetTableByExcel(string infoName, string fileName, DataTable dt)
        {
            QMFrameWork.WebUI.Util.IEFileTool efTool = new QMFrameWork.WebUI.Util.IEFileTool();
            List<CheckResult> checkResults = new List<CheckResult>();

            try
            {
                // 修改:文件路径参数拼加fileName 李鹏飞 2015-03-10 开始
                string PhysicsRootPath = Server.MapPath(System.Web.HttpContext.Current.Request.ApplicationPath);
                dt = efTool.ExcelToDataTable(infoName, PhysicsRootPath + "Temp\\"+fileName, dt, out checkResults);
                // 修改:文件路径参数拼加fileName 李鹏飞 2015-03-10 结束

                foreach (DataColumn dc in dt.Columns)
                {
                    foreach (DataRow row in dt.Rows)
                    {
                        if (row[dc.ColumnName] != System.DBNull.Value)
                        {
                            row[dc.ColumnName] = row[dc.ColumnName].ToString().ToUpper();
                        }
                    }
                }

                if (checkResults.Count > 0)
                {
                    CheckResult fileEx = checkResults.Find(p => p.RowIndex == -1);

                    if (fileEx != null)
                    {
                        //文件格式异常
                        QMFrameWork.Log.LogManager.LogHelper.Error(
                            new QMFrameWork.Log.LogInfo
                            {
                                ClientIP = "",
                                UserName = AccountController.GetLoginInfo().UserName
                                ,
                                Info = string.Format("导入{0}数据", infoName),
                                ErrorInfo = new Exception(fileEx.ErrorInfos["ex"])
                            });
                        throw new Exception(fileEx.ErrorInfos["title"]);
                    }
                }

                dt.Columns.Add(new DataColumn("InfoError"));

                foreach (CheckResult r in checkResults)
                {
                    string error = "";
                    foreach (string key in r.ErrorInfos.Keys)
                    {
                        error += key + ":" + r.ErrorInfos[key] + ";";
                    }

                    dt.Rows[r.RowIndex - 1]["InfoError"] = error;
                }

                return dt;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion

        // 添加:获取资源文件值 李鹏飞 2015-03-10 开始
        #region 获取资源文件值
        public string GetResourceValueByCode(string resourceCode)
        {
           return QMAPP.Common.Web.Properties.Resources.ResourceManager.GetString(resourceCode);
        }
        #endregion
        // 添加:获取资源文件值 李鹏飞 2015-03-10 结束

    }
}