using System;
using System.IO;
using System.Xml;
using System.Data;
using System.Collections;
using System.Data.OracleClient;
using Core.Mes.IBaseInterface;
using Core.Mes.ServerFrameWork;
using System.Configuration;
using System.Collections.Specialized;
using System.Text.RegularExpressions;
using System.Reflection;
using System.Threading;

namespace Core.Mes.ServerCommon
{
    /// <summary>
    /// Class1 的摘要说明。
    /// </summary>
    public class UserInfoManager : IComponent
    {
        string sTableSpace = "";
        static DataTable ServicesList = new DataTable();
        static Thread t_MasterConnector = null;

        public UserInfoManager()
        {
            try
            {

                sTableSpace = ServerConfig.UserTableSpace;
                if (!string.IsNullOrEmpty(sTableSpace.Trim())) sTableSpace = sTableSpace.Trim() + ".";
            }
            catch { }

            ArrayList col_names = new ArrayList() { "ServerName", "URL", "MD5_KEY", "SHA256_KEY" };

            foreach (string col_name in col_names)
            {
                if (!ServicesList.Columns.Contains(col_name))
                    ServicesList.Columns.Add(col_name, typeof(string));
            }
            ServicesList.AcceptChanges();
        }

        #region "	用户登录	"
        public ReturnObject GetPurviewInfo(string userID, string passwd, string hostname, string ipaddress)
        {
            lock (this)
            {
                string err = "";

                DataRow dr = GetPurviewRow(userID, passwd, out err);

                if (err != "")
                {
                    return new ReturnObject(null, err);
                }
                if (dr == null || dr["MEMO"] == null)
                    return new ReturnObject(null, 10009, "用户名或密码错误！");
                UserInfo useInfo = new UserInfo();

                useInfo = SetUserInfo(dr);

                string v_CheckPwd = "";
                v_CheckPwd = ServerConfig.CheckPassword > 0 ? CheckPWDRule(passwd) : "";

                if (ServerConfig.CheckIpRule > 0 && !CheckUserIPRule(ipaddress, dr["COMPUTERIP"].ToString().Trim()))
                {
                    throw new Exception("帐号被限制不能在当前计算机IP登录！");
                }

                return new ReturnObject(useInfo, 0, v_CheckPwd);
            }
        }

        private bool CheckUserIPRule(string IpAddress, string IpRule)
        {
            if (string.IsNullOrEmpty(IpRule)) return true;
            string[] ips = IpAddress.Split(new string[] { ".", @"。" }, StringSplitOptions.None);

            string[] ipR = IpRule.Split(new string[] { ";", @"；" }, StringSplitOptions.None);
            for (int i = 0; i < ipR.GetLength(0); i++)
            {
                string iprs = ipR[i].Trim();
                string[] ipRules = iprs.Split(new string[] { ".", @"。" }, StringSplitOptions.None);
                int min_len = Math.Min(ipRules.GetLength(0), ips.GetLength(0));
                for (int idx = 0; idx < (min_len >= 4 ? 4 : min_len); idx++)
                {
                    string ip_segment = ipRules[idx].Trim();
                    string ip = ips[idx].Trim();
                    if (string.IsNullOrEmpty(ip_segment) || string.IsNullOrEmpty(ip)) continue;

                    //检查ip规则配置是否正确  只允许包含  [数字]、[*]、[?] 三种字符;
                    Regex regex_segment = new Regex(@"^[0-9\?\*]{1,3}$");
                    if (!regex_segment.IsMatch(ip_segment))
                    {
                        throw new Exception(string.Format("IP规则第三段配置不正确！[{0}]", ip_segment));
                    }
                    ip_segment = ip_segment.Replace("*", @"\d*").Replace("?", @"\d?");
                    ip_segment = string.Format(@"^{0}$", ip_segment);

                    Regex regex_Ip = new Regex(ip_segment);
                    if (!regex_Ip.IsMatch(ip))
                    {
                        return false;
                    }
                }
            }
            return true;
        }

        public ReturnObject CheckPWD(string passwd)
        {
            string v_CheckPwd = "";
            try
            {
                v_CheckPwd = ServerConfig.CheckPassword > 0 ? CheckPWDRule(passwd) : "";
            }
            catch
            {
            }
            return new ReturnObject(null, string.IsNullOrEmpty(v_CheckPwd) ? 0 : 1, v_CheckPwd);
        }

        private string CheckPWDRule(string passwd)
        {
            string sReason = "";
            Boolean ContainLetter = false;
            Boolean ContainNumeric = false;
            Boolean ContailOthers = false;
            int len_pwd = passwd.Length;

            if (len_pwd < 6)
            {
                sReason += "  密码位数太少\n";
            }

            for (int idx = 0; idx < passwd.Length; idx++)
            {
                Char[] cp = passwd.Substring(idx, 1).ToLower().ToCharArray();
                if ((int)'a' <= (int)(cp[0]) && (int)'z' >= (int)(cp[0]))
                {
                    ContainLetter = true;
                }
                else if ((int)'0' <= (int)(cp[0]) && (int)'9' >= (int)(cp[0]))
                {
                    ContainNumeric = true;
                }
                else
                {
                    ContailOthers = true;
                }
            }

            if (!ContailOthers && (!ContainLetter || !ContainNumeric))
            {
                sReason += "  密码不能全是字母或数字;\n";
            }

            if (!string.IsNullOrEmpty(sReason))
            {
                sReason = string.Format("{0}", sReason);
            }
            return sReason;
        }

        private DataRow GetPurviewRow(string userID, string passwd, out string err)
        {
            string sqlstr = string.Format(@"SELECT A.*, B.MEMO, C.NAME, C.BB, C.BC, B.ROLENAME, C.DEPARTMENTID, C.COMPUTERIP,
                      D.DEPARTMENTNAME FROM {0}UAM_AUTHORIZATION A, {0}UAM_ROLE B, {0}UAM_USER C, {0}UAM_DEPARTMENT D 
                      WHERE A.USERID = C.USERID AND A.ROLEID = B.ROLEID AND C.DEPARTMENTID=D.DEPARTMENTID AND  
                       UPPER(A.LOGINID) = UPPER('{1}') AND UPPER(PASSWD) = '{2}'", sTableSpace, userID, PasswdSecurity(passwd));

            err = "";

            System.Data.DataSet ds = this.DBManager.ExecuteQuery(sqlstr, out err);

            if (err != "") return null;

            if (ds.Tables[0].Rows.Count == 0)
            {
                err = "用户名或密码错误！"; return null;
            }

            if ("1".Equals(ds.Tables[0].Rows[0]["lockstatus"].ToString()))
            {
                err = "该登录帐户已停用！"; return null;
            }

            System.Data.DataRow dr = ds.Tables[0].Rows[0];

            return dr;
        }
        private XmlDocument ReadXmlDoc(string fileName)
        {
            XmlDocument doc = new XmlDocument();

            try
            {
                doc.Load(@"CA\" + fileName);

                return doc;
            }

            catch
            {
                return null;
            }
        }

        private UserInfo SetUserInfo(DataRow dr)
        {
            UserInfo info;

            try
            {
                info = new UserInfo();
                info.LoginID = dr["LOGINID"].ToString();
                info.UserID = dr["USERID"].ToString();
                info.UserDepID = this.GetNoNullStr(dr["DEPARTMENTID"]);
                info.UserDepName = this.GetNoNullStr(dr["DEPARTMENTNAME"]);
                info.UserRoleID = this.GetNoNullStr(dr["ROLEID"]);
                info.UserRoleName = this.GetNoNullStr(dr["ROLENAME"]);
                if (dr["NAME"] == null || dr["NAME"] == DBNull.Value)
                    info.UserName = "";
                else
                    info.UserName = dr["NAME"].ToString();

                if (dr["BB"] == null || dr["BB"] == DBNull.Value)
                    info.UserBb = "300305";
                else
                    info.UserBb = dr["BB"].ToString();

                if (dr["BC"] == null || dr["BC"] == DBNull.Value)
                {
                    info.UserRz = "1";
                    info.UserBc = "300205";
                }
                else
                {
                    info.UserRz = dr["BC"].ToString();
                    info.UserBc = this.GetCurrBc(dr["BC"].ToString());
                }

                return info;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        private string GetNoNullStr(object obj)
        {
            if (obj == null || obj == DBNull.Value)
            {
                return "";
            }
            return obj.ToString();
        }


        #region "	登录退出记录	"
        private void RecodeLoginInfo(string vLoginID, string vUserName, string vUSERHOSTNAME,
          string vUSERIPADRESS, string vIsLogin)
        {
            OracleParameter[] param = new OracleParameter[5];
            object[] values = new object[5];
            ArrayList outvalues = new ArrayList();

            param[0] = new System.Data.OracleClient.OracleParameter();
            param[0].ParameterName = "vLoginID";
            param[0].DbType = System.Data.DbType.String;
            param[0].Size = 20;

            param[1] = new System.Data.OracleClient.OracleParameter();
            param[1].ParameterName = "vUserName";
            param[1].DbType = System.Data.DbType.String;
            param[1].Size = 20;

            param[2] = new System.Data.OracleClient.OracleParameter();
            param[2].ParameterName = "vUSERHOSTNAME";
            param[2].DbType = System.Data.DbType.String;
            param[2].Size = 100;

            param[3] = new System.Data.OracleClient.OracleParameter();
            param[3].ParameterName = "vUSERIPADRESS";
            param[3].DbType = System.Data.DbType.String;
            param[3].Size = 20;

            param[4] = new System.Data.OracleClient.OracleParameter();
            param[4].ParameterName = "vIsLogin";
            param[4].DbType = System.Data.DbType.String;
            param[4].Size = 20;

            values[0] = vLoginID;
            values[1] = vUserName;
            values[2] = vUSERHOSTNAME;
            values[3] = vUSERIPADRESS;
            values[4] = vIsLogin;

            string strOut = "";

            try
            {
                this.DBManager.ExecuteNonQuery("pub_useroperatemanager.pPub_Logininfo_Add", CommandType.StoredProcedure, param, values, ref outvalues, out strOut);

            }
            catch { }
        }


        public ReturnObject RecodeExitInfo(string vLoginID, string vUserName, string vUSERHOSTNAME,
          string vUSERIPADRESS)
        {
            RecodeLoginInfo(vLoginID, vUserName, vUSERHOSTNAME, vUSERIPADRESS, "退出");

            return new ReturnObject();
        }

        public ReturnObject RecodeOperateInfo(string vLoginID, string vUserName, string vUSERHOSTNAME,
          string vUSERIPADRESS, string vOPERATETYPE, string vOPERATEOBJECT, string vREMARK)
        {
            OracleParameter[] param = new OracleParameter[7];
            object[] values = new object[7];
            ArrayList outvalues = new ArrayList();

            param[0] = new System.Data.OracleClient.OracleParameter();
            param[0].ParameterName = "vLoginID";
            param[0].DbType = System.Data.DbType.String;
            param[0].Size = 20;

            param[1] = new System.Data.OracleClient.OracleParameter();
            param[1].ParameterName = "vUserName";
            param[1].DbType = System.Data.DbType.String;
            param[1].Size = 20;

            param[2] = new System.Data.OracleClient.OracleParameter();
            param[2].ParameterName = "vUSERHOSTNAME";
            param[2].DbType = System.Data.DbType.String;
            param[2].Size = 100;

            param[3] = new System.Data.OracleClient.OracleParameter();
            param[3].ParameterName = "vUSERIPADRESS";
            param[3].DbType = System.Data.DbType.String;
            param[3].Size = 20;

            param[4] = new System.Data.OracleClient.OracleParameter();
            param[4].ParameterName = "vOPERATETYPE";
            param[4].DbType = System.Data.DbType.String;
            param[4].Size = 50;

            param[5] = new System.Data.OracleClient.OracleParameter();
            param[5].ParameterName = "vOPERATEOBJECT";
            param[5].DbType = System.Data.DbType.String;
            param[5].Size = 100;

            param[6] = new System.Data.OracleClient.OracleParameter();
            param[6].ParameterName = "vREMARK";
            param[6].DbType = System.Data.DbType.String;
            param[6].Size = 200;

            values[0] = vLoginID;
            values[1] = vUserName;
            values[2] = vUSERHOSTNAME;
            values[3] = vUSERIPADRESS;
            values[4] = vOPERATETYPE;
            values[5] = vOPERATEOBJECT;
            values[6] = vREMARK;

            string strOut = "";

            try
            {
                this.DBManager.ExecuteNonQuery("pub_useroperatemanager.pPub_UserOperate_Add", CommandType.StoredProcedure, param, values, ref outvalues, out strOut);

            }
            catch { }

            return new ReturnObject();
        }

        #endregion

        #region "	班次、班别	"
        private string GetCurrBc(string bc)
        {
            System.DateTime now = System.DateTime.Now;
            switch (bc.Trim())
            {
                case "3":	//三班制
                    //早
                    if (now >= new DateTime(now.Year, now.Month, now.Day, 8, 0, 0) &&
                      now < new DateTime(now.Year, now.Month, now.Day, 16, 0, 0))
                        return "300201";
                    //中
                    if (now >= new DateTime(now.Year, now.Month, now.Day, 16, 0, 0) &&
                      now <= new DateTime(now.Year, now.Month, now.Day, 23, 59, 59))
                        return "300202";
                    //晚				
                    if (now >= new DateTime(now.Year, now.Month, now.Day, 0, 0, 0) &&
                      now < new DateTime(now.Year, now.Month, now.Day, 8, 0, 0))
                        return "300203";
                    break;
                case "2":	//两班制
                    //早
                    if (now >= new DateTime(now.Year, now.Month, now.Day, 8, 0, 0) &&
                      now < new DateTime(now.Year, now.Month, now.Day, 20, 0, 0))
                        return "300201";
                    else
                        return "300203";
            }
            return "300205";
        }
        public ReturnObject GetBz(string strWhere)
        {
            string sqlstr = string.Format("select ID_ BASECODE, NAME_ BASENAME from scm_base_info where SORT_CODE = '{0}' order by 1", strWhere);

            string strOut = "";

            try
            {
                DataSet ds = this.DBManager.ExecuteQuery(sqlstr, out strOut);

                return new ReturnObject(ds, strOut);
            }
            catch (Exception ex)
            {
                return new ReturnObject(new DataSet(), ex.Message + "\n" + strOut);
            }
        }

        public ReturnObject SetBz(string userID, string Bc, string Bb)
        {
            string sqlstr = string.Format(" update UAM_USER set BC = '{0}', BB = '{1}' where USERID = '{2}' ",
              Bc, Bb, userID);

            string strOut = "";

            try
            {
                int i = this.DBManager.ExecuteNonQuery(sqlstr, out strOut);

                return new ReturnObject(i, strOut);
            }
            catch (Exception ex)
            {
                return new ReturnObject(new DataSet(), ex.Message + "\n" + strOut);
            }
        }
        #endregion

        private string PasswdSecurity(string pwd)
        {
            return pwd.ToUpper();
        }
        public ReturnObject GetServerList()
        {
            if (!File.Exists("MesServer.xml"))
            {
                return new ReturnObject(null, "未找到服务配置文件！");
            }

            DataSet ds = new DataSet();
            ds.ReadXml("MesServer.xml");

            if (ds == null || ds.Tables.Count == 0)
                return new ReturnObject(null, "配置文件设置错误！");

            ds.AcceptChanges();

            lock (ServicesList)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    string asmFile = dr["AssemblyName"].ToString() + ".dll";
                    bool ExistServer = File.Exists(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), asmFile));
                    string sn = dr["ServerName"].ToString();
                    string url = dr["url"].ToString();
                    DataRow[] drs = ServicesList.Select(string.Format("ServerName = '{0}'", sn));
                    if (drs.GetLength(0) == 0 && ExistServer)
                    {
                        DataRow ndr = ServicesList.NewRow();
                        ndr["ServerName"] = sn;
                        ndr["URL"] = url;
                        if (HTServiceKeys.ContainsKey(sn))
                        {
                            ServiceObject so = (ServiceObject)HTServiceKeys[sn];
                            ndr["MD5_KEY"] = so.MD5_KEY;
                            ndr["SHA256_KEY"] = so.SHA256_KEY;
                            ServicesList.Rows.Add(ndr);
                        }
                    }
                    else if (drs.GetLength(0) > 0 && !ExistServer)
                    {
                        foreach (DataRow cdr in drs)
                        {
                            cdr.Delete();
                        }
                    }
                }
                ServicesList.TableName = "ServiceList";
                ServicesList.AcceptChanges();
            }

            DataTable dt_config = new DataTable("CONFIG");
            dt_config.Columns.Add("NAME", typeof(string));
            dt_config.Columns.Add("VALUE", typeof(object));
            dt_config.Rows.Add("PriorityFactor", ServerConfig.PriorityFactor);

            ds = new DataSet();
            ds.Tables.Add(ServicesList.Copy());
            ds.Tables.Add(dt_config);
            ds.AcceptChanges();

            return new ReturnObject(ds);
        }

        public ReturnObject CheckAlive(DateTime _dt)
        {
            return new ReturnObject((object)(new ArrayList() { ServerConfig.MAGIC_ID, _dt, ServerConfig.MasterServer }), 1314, "I'AM ALIVE");
        }

        public ReturnObject ControlIt(string ControlService)
        {
            try
            {
                UriBuilder ub = new UriBuilder(ControlService);
                if (ub.Host == "127.0.0.1") return new ReturnObject(null, 0, "不接受本地主机IP");

                if (!string.IsNullOrEmpty(ServerConfig.MasterServer))
                {
                    if (ServerConfig.MasterServer != ControlService) return new ReturnObject(ServerConfig.MasterServer, 1314, "已受控!");

                    if (t_MasterConnector == null)
                    {
                        t_MasterConnector = new Thread(CheckMaster);
                        t_MasterConnector.Start();
                    }
                }
                else
                {
                    ServerConfig.MasterServer = ControlService;
                    if (t_MasterConnector != null)
                    {
                        t_MasterConnector.Abort();
                    }

                    t_MasterConnector = new Thread(CheckMaster);
                    t_MasterConnector.Start();
                }
                return new ReturnObject(ServerConfig.MasterServer, 1314, "控制成功！");
            }
            catch (Exception ex)
            {
                return new ReturnObject(ServerConfig.MasterServer, 1, ex.Message);
            }
        }

        ICommon MasterChecker = null;
        private void CheckMaster()
        {
            int LostCommander = 0;
            do
            {
                if (string.IsNullOrEmpty(ServerConfig.MasterServer)) Thread.CurrentThread.Abort();

                if (MasterChecker == null)
                {
                    MasterChecker = (ICommon)Activator.GetObject(typeof(ICommon), ServerConfig.MasterServer);
                }
                DateTime dt = DateTime.Now;

                CallingMessage par = new CallingMessage();
                par.ServerName = ServerConfig.MasterServer;
                par.ClassName = "Core.Mes.ServerCommon.UserInfoManager";
                par.MethodName = "CheckAlive";
                par.args = new object[] { dt };

                par.ServerType = MesServerType.IComponentContainServer;
                par.TransType = NetWorkTransType.Remoting;
                par.visitType = VisitType.Method;

                try
                {

                    ReturnObject rtn = MasterChecker.MethodHandler(par, new ValidateInfo());
                    if (rtn.ErrCode == 1314 && rtn.RealObject != null && (DateTime)(((ArrayList)rtn.RealObject)[1]) == dt
                        && (int)(((ArrayList)rtn.RealObject)[0]) != ServerConfig.MAGIC_ID)
                    {
                        LostCommander = 0;
                    }
                    else if (LostCommander >= 3)
                    {
                        ServerConfig.MasterServer = "";
                        Thread.CurrentThread.Abort();
                        break;
                    }
                    else
                    {
                        LostCommander += 1;
                    }
                }
                catch
                {
                    if (LostCommander >= 3)
                    {
                        ServerConfig.MasterServer = "";
                        break;
                    }
                    else
                    {
                        LostCommander += 1;
                    }
                }
                Thread.Sleep(LostCommander == 0 ? 5000 : 1000);
            } while (!string.IsNullOrEmpty(ServerConfig.MasterServer));
        }

        public ReturnObject GetServerConfig()
        {
            DataSet ds = new DataSet();
            DataTable dt = new DataTable();

            dt.Columns.AddRange(new DataColumn[] {  new DataColumn("KEY_NAME", typeof(string)), 
                                                    new DataColumn("KEY_VALUE", typeof(string)) });
            dt.TableName = "CONFIG";
            dt.PrimaryKey = new DataColumn[] { dt.Columns["KEY_NAME"] };
            dt.AcceptChanges();

            NameValueCollection appSettings = ConfigurationManager.AppSettings;
            IEnumerator appSettingsEnum = appSettings.Keys.GetEnumerator();

            int i = 0;
            while (appSettingsEnum.MoveNext())
            {
                string key = appSettings.Keys[i];
                string value = appSettings[key];

                dt.Rows.Add(new object[] { key, value });

                i += 1;
            }
            dt.AcceptChanges();
            if (dt.Rows.Count > 0)
            {
                ds.Tables.Add(dt);
            }

            return new ReturnObject((object)ds);
        }

        public ReturnObject ChangePasswd(string loginID, string passwd, string passwdNew)
        {
            string sqlstr = string.Format(" update UAM_AUTHORIZATION set passwd = '{2}' where loginid = '{0}' and passwd = '{1}' ",
              loginID, passwd, passwdNew);

            string strOut = "";

            try
            {
                int i = this.DBManager.ExecuteNonQuery(sqlstr, out strOut);

                return new ReturnObject(i, strOut);
            }
            catch (Exception ex)
            {
                return new ReturnObject(new DataSet(), ex.Message + "\n" + strOut);
            }
        }
        #endregion

        #region "	消息	"
        public ReturnObject HeartBeat()
        {
            return new ReturnObject();
        }

        public ReturnObject GetUserMessage()
        {
            string sqlstr = "select MESSAGE, PROMULGATOR,EDITTIME, PRI_ from PUB_USERMESSAGE where ISVALID = '0' and	 > sysdate order by edittime desc ";

            string strOut = "";

            try
            {
                DataSet ds = this.DBManager.ExecuteQuery(sqlstr, out strOut);

                return new ReturnObject(ds, strOut);
            }
            catch (Exception ex)
            {
                return new ReturnObject(new DataSet(), ex.Message + "\n" + strOut);
            }
        }
        public ReturnObject GetMessage(string strWhere)
        {
            string sqlstr = string.Format("select * from pub_message where GETFLAG <> '1' and SENDPERSONCODE = '{0}' ", strWhere);

            string strOut = "";

            try
            {
                DataSet ds = this.DBManager.ExecuteQuery(sqlstr, out strOut);

                return new ReturnObject(ds, strOut);
            }
            catch (Exception ex)
            {
                return new ReturnObject(new DataSet(), ex.Message + "\n" + strOut);
            }
        }

        public ReturnObject SendMessage(string vSendPerson, string vSendPersonCode, string vInfo, string vGetPerson)
        {
            string strOut = "";

            OracleParameter[] param = new OracleParameter[7];
            object[] values = new object[7];
            ArrayList outvalues = new ArrayList();
            strOut = "";

            param[0] = new OracleParameter();
            param[0].ParameterName = "vID";
            param[0].Direction = System.Data.ParameterDirection.Input;
            param[0].DbType = System.Data.DbType.String;
            param[0].Size = 20;

            param[1] = new OracleParameter();
            param[1].ParameterName = "vSendPerson";
            param[1].Direction = System.Data.ParameterDirection.Input;
            param[1].DbType = System.Data.DbType.String;
            param[1].Size = 20;

            param[2] = new OracleParameter();
            param[2].ParameterName = "vSendPersonCode";
            param[2].Direction = System.Data.ParameterDirection.Input;
            param[2].DbType = System.Data.DbType.String;
            param[2].Size = 20;

            param[3] = new OracleParameter();
            param[3].ParameterName = "vInfo";
            param[3].Direction = System.Data.ParameterDirection.Input;
            param[3].DbType = System.Data.DbType.String;
            param[3].Size = 200;

            param[4] = new OracleParameter();
            param[4].ParameterName = "vGetPerson";
            param[4].Direction = System.Data.ParameterDirection.Input;
            param[4].DbType = System.Data.DbType.String;
            param[4].Size = 20;

            param[5] = new System.Data.OracleClient.OracleParameter();
            param[5].ParameterName = "vRESULT";
            param[5].Direction = System.Data.ParameterDirection.Output;
            param[5].DbType = System.Data.DbType.Int16;

            param[6] = new System.Data.OracleClient.OracleParameter();
            param[6].ParameterName = "vMESSAGE";
            param[6].Direction = System.Data.ParameterDirection.Output;
            param[6].DbType = System.Data.DbType.String;
            param[6].Size = 200;

            values[0] = System.Guid.NewGuid().ToString();
            values[1] = vSendPerson;
            values[2] = vSendPersonCode;
            values[3] = vInfo;
            values[4] = vGetPerson;
            values[5] = 0;
            values[6] = "";

            try
            {
                this.DBManager.ExecuteNonQuery("pub_MessageManager.pPub_Message_Send", CommandType.StoredProcedure, param, values, ref outvalues, out strOut);

                return new ReturnObject(outvalues, strOut);
            }
            catch (Exception ex)
            {
                return new ReturnObject(-1, ex.Message + "\n" + strOut);
            }
        }
        public ReturnObject AffirmMessage(string vID)
        {
            string strOut = "";

            OracleParameter[] param = new OracleParameter[3];
            object[] values = new object[3];
            ArrayList outvalues = new ArrayList();
            strOut = "";

            param[0] = new OracleParameter();
            param[0].ParameterName = "vID";
            param[0].Direction = System.Data.ParameterDirection.Input;
            param[0].DbType = System.Data.DbType.String;
            param[0].Size = 20;

            param[1] = new System.Data.OracleClient.OracleParameter();
            param[1].ParameterName = "vRESULT";
            param[1].Direction = System.Data.ParameterDirection.Output;
            param[1].DbType = System.Data.DbType.Int16;

            param[2] = new System.Data.OracleClient.OracleParameter();
            param[2].ParameterName = "vMESSAGE";
            param[2].Direction = System.Data.ParameterDirection.Output;
            param[2].DbType = System.Data.DbType.String;
            param[2].Size = 200;

            values[0] = vID;
            values[1] = 0;
            values[2] = "";

            try
            {
                this.DBManager.ExecuteNonQuery("pub_MessageManager.pPub_Message_Affirm", CommandType.StoredProcedure, param, values, ref outvalues, out strOut);

                return new ReturnObject(outvalues, strOut);
            }
            catch (Exception ex)
            {
                return new ReturnObject(-1, ex.Message + "\n" + strOut);
            }
        }
        #endregion

        #region "	override	"
        public override int maxValue
        {
            get
            {
                return 30;
            }
        }
        public override int minValue
        {
            get
            {
                return 20;
            }
        }
        #endregion

        #region		权限设置
        public ReturnObject selectPT_MenuInfo()
        {
            string sqlstr = string.Format("SELECT ID_,CAPTION,PARENTID,XH FROM {0}PT_MENUINFO ORDER BY PARENTID,XH,REMARK", sTableSpace);
            string err = "";
            DataSet dset = DBManager.ExecuteQuery(sqlstr, out err);
            return new ReturnObject(dset, err);
        }
        public ReturnObject updatePT_MenuPos(DataTable dt)
        {
            try
            {
                string err = "";
                bool success = DBManager.UpdateTable(dt, string.Format("SELECT ID_,CAPTION,PARENTID,XH FROM {0}PT_MENUINFO WHERE XH IS NOT NULL", sTableSpace), out err);
                return new ReturnObject(null, err);
            }
            catch (Exception ee)
            {
                return new ReturnObject(null, ee.Message);
            }
        }

        public ReturnObject GetPt_menuinfo(string strWhere)
        {
            string sqlstr = string.Format("SELECT * FROM {0}PT_MENUINFO WHERE 1=1 {1} ORDER BY CATEGORY, CAPTION", sTableSpace, strWhere);

            string strOut = "";

            try
            {
                DataSet ds = this.DBManager.ExecuteQuery(sqlstr, out strOut);

                return new ReturnObject(ds, strOut);
            }
            catch (Exception ex)
            {
                return new ReturnObject(new DataSet(), ex.Message + "\n" + strOut);
            }
        }
        public ReturnObject InsertPt_menuinfo(string vkey, string vCategory, string vCaption, string vRemark, string vType)
        {
            string strOut = "";
            DataSet ds = null;
            string strID = "";
            object obj = null;
            int iCount = 0;

            string sqlstr = string.Format("SELECT COUNT(1) FROM {0}PT_MENUINFO WHERE KEY_ = '{1}'", sTableSpace, vkey);
            try
            {
                ds = this.DBManager.ExecuteQuery(sqlstr, out strOut);
            }
            catch (Exception ex)
            {
                return new ReturnObject(null, ex.Message + "\n" + strOut);
            }
            obj = ds.Tables[0].Rows[0][0];
            if (obj == null || obj == DBNull.Value)
            {
                iCount = 0;
            }
            else
            {
                iCount = Convert.ToInt32(Convert.ToInt32(obj));
            }
            if (iCount > 0)
            {
                return new ReturnObject(null, "键值重复！请重新输入！");
            }

            sqlstr = string.Format("SELECT MAX(TO_NUMBER(ID_)) FROM {0}PT_MENUINFO ", sTableSpace);


            try
            {
                ds = this.DBManager.ExecuteQuery(sqlstr, out strOut);
            }
            catch (Exception ex)
            {
                return new ReturnObject(null, ex.Message + "\n" + strOut);
            }
            obj = ds.Tables[0].Rows[0][0];
            if (obj == null || obj == DBNull.Value)
            {
                strID = "0";
            }
            else
            {
                strID = Convert.ToString(Convert.ToInt32(obj) + 1);
            }
            sqlstr = string.Format("INSERT INTO {0}PT_MENUINFO (ID_, KEY_, CATEGORY, CAPTION, REMARK, TYPE) "
                + " VALUES "
                + " ('{1}', '{2}', '{3}', '{4}', '{5}', '{6}') ", sTableSpace, strID, vkey, vCategory, vCaption, vRemark, vType);

            strOut = "";

            try
            {
                this.DBManager.ExecuteNonQuery(sqlstr, out strOut);

                return new ReturnObject(strID, strOut);
            }
            catch (Exception ex)
            {
                return new ReturnObject(null, ex.Message + "\n" + strOut);
            }
        }
        public ReturnObject UpdatePt_menuinfo(string vID, string vkey, string vCategory, string vCaption, string vRemark, string vType)
        {
            string sqlstr = string.Format("UPDATE {0}PT_MENUINFO SET KEY_ = '{1}', CATEGORY = '{2}', "
                  + " CAPTION = '{3}', REMARK = '{4}', TYPE='{5}' WHERE ID_ = '{6}'  ",
               sTableSpace, vkey, vCategory, vCaption, vRemark, vType, vID);

            string strOut = "";

            try
            {
                this.DBManager.ExecuteNonQuery(sqlstr, out strOut);

                return new ReturnObject(null, strOut);
            }
            catch (Exception ex)
            {
                return new ReturnObject(null, ex.Message + "\n" + strOut);
            }
        }
        public ReturnObject DeletePt_menuinfo(string vID)
        {
            string sqlstr = string.Format("SELECT COUNT(1) FROM {0}PT_USERMENUINFO WHERE MENUID = '{1}' ", sTableSpace, vID);
            string strOut = "";
            try
            {
                DataSet dset = DBManager.ExecuteQuery(sqlstr, out strOut);
                if (int.Parse(dset.Tables[0].Rows[0][0].ToString()) > 0)
                    return new ReturnObject(null, "该菜单已被配置到角色菜单中去，请先在角色菜单中删除！");
            }
            catch (Exception ex)
            {
                return new ReturnObject(null, ex.Message + "\n" + strOut);
            }

            sqlstr = string.Format("SELECT COUNT(1) FROM {0}PT_MENUINFO WHERE PARENTID = '{1}' ", sTableSpace, vID);
            strOut = "";
            try
            {
                DataSet dset = DBManager.ExecuteQuery(sqlstr, out strOut);
                if (int.Parse(dset.Tables[0].Rows[0][0].ToString()) > 0)
                    return new ReturnObject(null, "该菜单其下还有子菜单，不可直接删除！");
            }
            catch (Exception ex)
            {
                return new ReturnObject(null, ex.Message + "\n" + strOut);
            }

            sqlstr = string.Format("DELETE {0}PT_MENUINFO WHERE ID_ = '{1}' ", sTableSpace, vID);
            strOut = "";

            try
            {
                this.DBManager.ExecuteNonQuery(sqlstr, out strOut);
            }
            catch (Exception ex)
            {
                return new ReturnObject(null, ex.Message + "\n" + strOut);
            }
            sqlstr = string.Format("DELETE {0}PT_USERMENUINFO WHERE MENUID = '{1}' ", sTableSpace, vID);

            strOut = "";

            try
            {
                this.DBManager.ExecuteNonQuery(sqlstr, out strOut);
                return new ReturnObject(null, strOut);
            }
            catch (Exception ex)
            {
                return new ReturnObject(null, ex.Message + "\n" + strOut);
            }
        }
        public ReturnObject PlastPt_menuinfo(string oldRole, string newRole)
        {
            string sqlstr = string.Format("DELETE {0}PT_USERMENUINFO WHERE ROLEID = '{1}' ", sTableSpace, newRole);

            string strOut = "";

            try
            {
                this.DBManager.ExecuteNonQuery(sqlstr, out strOut);
            }
            catch (Exception ex)
            {
                return new ReturnObject(null, ex.Message + "\n" + strOut);
            }

            sqlstr = string.Format("SELECT MAX(TO_NUMBER(ID_)) FROM {0}PT_USERMENUINFO ", sTableSpace);
            int iCount = 0;
            DataSet ds = null;

            try
            {
                ds = this.DBManager.ExecuteQuery(sqlstr, out strOut);
            }
            catch (Exception ex)
            {
                return new ReturnObject(null, ex.Message + "\n" + strOut);
            }
            object obj = ds.Tables[0].Rows[0][0];
            if (obj == null || obj == DBNull.Value)
            {
                iCount = 0;
            }
            else
            {
                iCount = Convert.ToInt32(obj);
            }
            sqlstr = string.Format("SELECT * FROM {0}PT_USERMENUINFO WHERE ROLEID = '{1}'", sTableSpace, oldRole);
            try
            {
                ds = this.DBManager.ExecuteQuery(sqlstr, out strOut);
            }
            catch (Exception ex)
            {
                return new ReturnObject(null, ex.Message + "\n" + strOut);
            }
            for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
            {
                iCount = iCount + 1;
                sqlstr = string.Format("INSERT INTO {0}PT_USERMENUINFO (ID_, ROLEID, MENUID, SETINFO) "
                    + " VALUES "
                    + " ('{1}', '{2}', '{3}', '{4}' ) ", sTableSpace, Convert.ToString(iCount),
                    newRole, ds.Tables[0].Rows[i]["MENUID"].ToString(),
                    ds.Tables[0].Rows[i]["SETINFO"].ToString());

                strOut = "";

                try
                {
                    this.DBManager.ExecuteNonQuery(sqlstr, out strOut);
                }
                catch (Exception ex)
                {
                    return new ReturnObject(null, ex.Message + "\n" + strOut);
                }
            }
            return new ReturnObject(null);
        }
        public ReturnObject SavePt_usermenuinfo(string vRole, ArrayList arMenu, ArrayList arSet)
        {
            string sqlstr = string.Format("DELETE {0}PT_USERMENUINFO WHERE ROLEID = '{1}' ", sTableSpace, vRole);

            string strOut = "";

            try
            {
                this.DBManager.ExecuteNonQuery(sqlstr, out strOut);
            }
            catch (Exception ex)
            {
                return new ReturnObject(null, ex.Message + "\n" + strOut);
            }

            sqlstr = string.Format("SELECT MAX(TO_NUMBER(ID_)) FROM {0}PT_USERMENUINFO ", sTableSpace);
            int iCount = 0;
            DataSet ds = null;

            try
            {
                ds = this.DBManager.ExecuteQuery(sqlstr, out strOut);
            }
            catch (Exception ex)
            {
                return new ReturnObject(null, ex.Message + "\n" + strOut);
            }
            object obj = ds.Tables[0].Rows[0][0];
            if (obj == null || obj == DBNull.Value)
            {
                iCount = 0;
            }
            else
            {
                iCount = Convert.ToInt32(obj);
            }

            for (int i = 0; i < arMenu.Count; i++)
            {
                iCount = iCount + 1;
                sqlstr = string.Format("INSERT INTO {0}PT_USERMENUINFO (ID_, ROLEID, MENUID, SETINFO) "
                    + " VALUES "
                    + " ('{1}', '{2}', '{3}', '{4}' ) ", sTableSpace, Convert.ToString(iCount),
                    vRole, arMenu[i].ToString(), arSet[i].ToString());

                strOut = "";

                try
                {
                    this.DBManager.ExecuteNonQuery(sqlstr, out strOut);
                }
                catch (Exception ex)
                {
                    return new ReturnObject(null, ex.Message + "\n" + strOut);
                }
            }
            return new ReturnObject(null, "");
        }

        public ReturnObject GetUserRolePairs()
        {
            try
            {
                string err = "";
                string sql = "SELECT U.LOGINID, U.ROLEID FROM UAM_AUTHORIZATION U ORDER BY U.LOGINID";
                DataSet ds = this.DBManager.ExecuteQuery(sql, out err);
                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {
                    return new ReturnObject(ds);
                }
                return new ReturnObject(null, err);
            }
            catch (System.Exception ex)
            {
                return new ReturnObject(null, ex.ToString());
            }
        }

        public ReturnObject GetRoleMenuPairs(string RoleID)
        {
            try
            {
                if (RoleID.Trim() == "") return new ReturnObject(null, "");

                string err = "";
                string sql = string.Format(@"SELECT T.ROLEID, T.MENUID, T.SETINFO, M.KEY_, M.CATEGORY, M.CAPTION, M.REMARK
                                 FROM   {0}PT_USERMENUINFO T
                                 LEFT   JOIN {0}PT_MENUINFO M
                                   ON   T.MENUID = M.ID_
                                 Where T.ROLEID = '{1}'", sTableSpace, RoleID.Trim());

                DataSet ds = this.DBManager.ExecuteQuery(sql, out err);
                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {
                    return new ReturnObject(ds);
                }
                return new ReturnObject(null, err);
            }
            catch (System.Exception ex)
            {
                return new ReturnObject(null, ex.ToString());
            }
        }

        public ReturnObject GetUser_Uam_Role(string DptID)
        {
            try
            {
                string err = "";
                string sql = string.Format("SELECT ROLEID, ROLENAME FROM {0}UAM_ROLE WHERE DEPARTMENTID IN({1}) ORDER BY ROLENAME ", sTableSpace, DptID);
                DataSet ds = this.DBManager.ExecuteQuery(sql, out err);
                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {
                    return new ReturnObject(ds);
                }
                return new ReturnObject(null, err);
            }
            catch (System.Exception ex)
            {
                return new ReturnObject(null, ex.ToString());
            }
        }

        public ReturnObject GetUam_role()
        {
            string sqlstr = "SELECT ROLEID, ROLENAME FROM UAM_ROLE ORDER BY ROLENAME ";

            string strOut = "";

            try
            {
                DataSet ds = this.DBManager.ExecuteQuery(sqlstr, out strOut);
                if (ds != null && ds.Tables[0].Rows.Count > 0)
                {
                    return new ReturnObject(ds, strOut);
                }
                else
                {
                    return new ReturnObject(null, strOut);
                }
            }
            catch (Exception ex)
            {
                return new ReturnObject(null, ex.Message + "\n" + strOut);
            }
        }

        public ReturnObject GetPurviewTree(string strWhere)
        {
            string sqlstr = string.Format("SELECT ID_, MENUID, (SELECT CAPTION FROM {0}PT_MENUINFO WHERE ID_ = MENUID) MENUNAME, "
                  + " SETINFO FROM {0}PT_USERMENUINFO WHERE 1=1 {1} ORDER BY SETINFO ", sTableSpace, strWhere);

            string strOut = "";

            try
            {
                DataSet ds = this.DBManager.ExecuteQuery(sqlstr, out strOut);

                return new ReturnObject(ds, strOut);
            }
            catch (Exception ex)
            {
                return new ReturnObject(new DataSet(), ex.Message + "\n" + strOut);
            }
        }

        public ReturnObject GetBuildMenuInfo(string strWhere)
        {
            string sqlstr = string.Format("SELECT C.KEY_, C.CATEGORY, C.CAPTION, C.TYPE,B.SETINFO "
                + " FROM {0}UAM_AUTHORIZATION A, {0}PT_USERMENUINFO B, {0}PT_MENUINFO C "
                + " WHERE LOGINID = '{1}' AND A.ROLEID = B.ROLEID AND B.MENUID = C.ID_ ORDER BY B.SETINFO ", sTableSpace, strWhere);

            string strOut = "";

            try
            {
                DataSet ds = this.DBManager.ExecuteQuery(sqlstr, out strOut);

                return new ReturnObject(ds, strOut);
            }
            catch (Exception ex)
            {
                return new ReturnObject(new DataSet(), ex.Message + "\n" + strOut);
            }
        }

        #endregion

        #region "系统监听"

        public ReturnObject MesSystemListener()
        {
            string sqlstr = "select sysdate from dual";

            string strOut = "";

            try
            {
                this.DBManager.ExecuteNonQuery(sqlstr, out strOut);

                return new ReturnObject(null, strOut);
            }
            catch (Exception ex)
            {
                return new ReturnObject(null, ex.Message + "\n" + strOut);
            }
        }


        public ReturnObject RecordUserEvent(string vLoginID, string vUserName, string vUSERHOSTNAME,
            string vUSERIPADRESS, string vOPerateType, string vControlTYPE, string vOPERATEOBJECT, string vFormName, string vClassName, string vREMARK)
        {
            try
            {
                DateTime dt = System.DateTime.Now;
                CoreWriteLogFile.WriteLog(dt, vLoginID, vUserName, vUSERHOSTNAME, vUSERIPADRESS, vOPerateType, vControlTYPE, vOPERATEOBJECT, vFormName, vClassName, vREMARK);

                Insert_UserEventsRec(dt, vLoginID, vUserName, vUSERHOSTNAME, vUSERIPADRESS, vOPerateType, vControlTYPE, vOPERATEOBJECT, vFormName, vClassName, vREMARK);
            }
            catch { }

            return new ReturnObject();
        }

        public ReturnObject Insert_UserEventsRec(DateTime dt, string vLoginID, string vUserName, string vUSERHOSTNAME, string vUSERIPADRESS, string vOPerateType,
            string vControlTYPE, string vOPERATEOBJECT, string vFormName, string vClassName, string vREMARK)
        {
            string sqlstr = string.Format("INSERT INTO {0}PUB_USEREVENTS (LOGINID, USERNAME, USERHOSTNAME, USERIPADRESS, OPERATETIME, OPERATETYPE, CONTROLTYPE, OPERATEOBJECT, FORMNAME, CLASSNAME, REMARK) "
                 + " VALUES   ('{1}', '{2}', '{3}', '{4}', TO_TIMESTAMP('{5}', 'yyyy-mm-dd hh24:mi:ss.ff'), '{6}', '{7}', '{8}', '{9}', '{10}', '{11}') ",
                 sTableSpace, vLoginID, vUserName, vUSERHOSTNAME, vUSERIPADRESS, dt.ToString("yyyy-MM-dd HH:mm:ss.fff"),
                 vOPerateType, vControlTYPE, vOPERATEOBJECT, vFormName, vClassName, vREMARK);

            string strOut = "";

            try
            {
                this.DBManager.ExecuteNonQuery(sqlstr, out strOut);

                return new ReturnObject(null, 0, strOut);
            }
            catch (Exception ex)
            {
                return new ReturnObject(null, -1, ex.Message + "\n" + strOut);
            }
        }
        #endregion

        public ReturnObject getDBSrvTime()
        {
            string strOut = "";
            try
            {
                DataSet ds = this.DBManager.ExecuteQuery("SELECT SYSDATE FROM DUAL", out strOut);

                return new ReturnObject(ds.Tables[0].Rows[0][0], strOut);
            }
            catch (Exception ex)
            {
                return new ReturnObject(null, ex.Message + "\n" + strOut);
            }
        }
    }
}
