using System;
using System.Collections;
using System.Xml;
using System.Data;
using System.IO;
using System.Data.OracleClient;
using Core.Mes.IBaseInterface;
using Core.Mes.ServerFrameWork;

namespace Core.Mes.PurviewManager
{
  /// <summary>
  /// 权限管理服务端，用于在客户端输入用户名密码后
  /// 由服务端来获取对应权限文件，然后根据权限文件
  /// 将相应的窗体信息从数据库中读出，再将信息合并
  /// 到权限文件中，然后将权限文件返回给客户端生成
  /// 菜单文件
  /// 
  /// fanxb 20050705
  /// </summary>
  public class PurviewManager : IComponent
  {

    #region "	variable	"

    private UAM_DEPARTMENT _departmentClass;
    private UAM_ROLE _roleClass;
    private UAM_FUNCTION _functionClass;
    private UAM_USER _userClass;
    private UAM_AUTHORIZATION _authorClass;
    //private TestUser _testuserClass;

    #endregion

    #region "	Construct	"

    public PurviewManager() { }

    #endregion

    #region "	获取权限信息	"
    /// <summary>
    /// 获取权限信息
    /// </summary>
    /// <param name="userID">用户名ID</param>
    /// <param name="passwd">密码</param>
    /// <returns>权限xml文件的字符串</returns>
    public ReturnObject GetPurviewInfo(string userID, string passwd)
    {
      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, "用户名或密码错误！");

        string fileName = dr["MEMO"].ToString().Trim();

        if (File.Exists(@"CA\" + fileName))
        {
          XmlDocument doc = ReadXmlDoc(fileName);
          if (doc != null)
          {
            UserInfo useInfo;
            try
            {
              useInfo = SetUserInfo(dr);
              SetValidateInfo(useInfo);
              //useInfo.MenuConfigInfo = doc.InnerXml;
            }
            catch (Exception ex)
            {
              return new ReturnObject(null, ex.Message);
            }

            return new ReturnObject(useInfo);
          }
          else
            return new ReturnObject(null, 10010, "权限文件内容错误！！");
        }
        else
        {
          return new ReturnObject(null, 10006, "未找到指定的文件！");
        }
      }
    }


    private DataRow GetPurviewRow(string userID, string passwd, out string err)
    {
      string sqlstr = "SELECT * FROM UAMV_AUTHORROLE WHERE LOGINID = '" + userID + "' AND PASSWORD = '" + PasswdSecurity(passwd) + "'";
      err = "";

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

      if (err.Equals("") && ds != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
      {
        System.Data.DataRow dr = ds.Tables[0].Rows[0];

        return dr;
      }
      return null;
    }

    /// <summary>
    /// 根据权限配置文件，在数据库中找出对应的表信息
    /// </summary>
    /// <param name="fileName">权限配置文件名</param>
    private XmlDocument ReadXmlDoc(string fileName)
    {
      XmlDocument doc = new XmlDocument();

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

        XmlNodeList xnl = doc.ChildNodes[1].ChildNodes;

        DataTable dt = GetFormInfoFromDB();
        recursionGetNodes(xnl, doc, dt);

        return doc;
      }

      catch (Exception ex)
      {
        Console.WriteLine(ex.Message);
        return null;
      }
    }

    /// <summary>
    /// 获取"Default"情况的窗体信息
    /// </summary>
    /// <param name="xnl">子节点</param>
    private void GetDefaultFormInfo(XmlNodeList xnl, XmlDocument doc, DataTable dt)
    {
      foreach (XmlNode xn in xnl)
      {
        try
        {
          string strFormID = xn.Attributes[0].Value.ToString();
          DataRow dr = (dt.Select("FunctionID = '" + strFormID + "'"))[0];

          AddFormInfoIntoXmlNode(xn, dr, doc);
        }
        catch (Exception ex)
        {
          Console.WriteLine(ex.Message);
        }
      }
    }

    /// <summary>
    /// 获取"Tree"情况的窗体信息
    /// 采用递归调用的方式
    /// </summary>
    /// <param name="xnl">子节点</param>
    /// <param name="doc">xml文档</param>
    private void recursionGetNodes(XmlNodeList xnl, XmlDocument doc, DataTable dt)
    {
      foreach (XmlNode xn in xnl)
      {
        string strFormID = "";
        try
        {
          strFormID = xn.Attributes[0].Value.ToString();
          DataRow dr = (dt.Select("FunctionID = '" + strFormID + "'"))[0];

          AddFormInfoIntoXmlNode(xn, dr, doc);
        }
        catch
        {
          XmlAttribute newAttr = doc.CreateAttribute("FunctionName");
          newAttr.Value = strFormID;
          xn.Attributes.InsertAfter(newAttr, xn.Attributes[0]);
        }

        if (xn.ChildNodes.Count > 0)
        {
          recursionGetNodes(xn.ChildNodes, doc, dt);
        }
      }
    }

    /// <summary>
    /// 从数据库中获取表信息
    /// </summary>
    /// <param name="formID">要获取窗体的id号</param>
    /// <returns>存有该窗体所有信息的数据行</returns>
    private DataTable GetFormInfoFromDB()
    {
      string sqlstr = "SELECT * FROM UAM_FUNCTION";

      System.Data.DataSet ds = DBManager.ExecuteQuery(sqlstr);

      if (ds != null && ds.Tables.Count > 0)
      {
        System.Data.DataTable dt = ds.Tables[0];

        return dt;
      }
      else
        return null;

    }

    /// <summary>
    /// 将取道的窗体信息存入xml节点
    /// </summary>
    /// <param name="xn">要存入的xml节点</param>
    /// <param name="dr">获取到的窗体信息</param>
    /// <param name="doc">xml文档，用于生成新的属性</param>
    private void AddFormInfoIntoXmlNode(XmlNode xn, DataRow dr, XmlDocument doc)
    {
      if (dr != null)
      {
        XmlAttribute newAttr = doc.CreateAttribute("AssemblyName");
        newAttr.Value = dr["AssemblyName"].ToString().Trim();

        xn.Attributes.InsertAfter(newAttr, xn.Attributes[0]);

        newAttr = doc.CreateAttribute("ClassName");
        newAttr.Value = dr["ClassName"].ToString().Trim();

        xn.Attributes.InsertAfter(newAttr, xn.Attributes[1]);

        newAttr = doc.CreateAttribute("FunctionName");
        newAttr.Value = dr["FunctionName"].ToString().Trim();

        xn.Attributes.InsertAfter(newAttr, xn.Attributes[2]);
      }
    }

    private string PasswdSecurity(string pwd)
    {
      return pwd;
    }
    private void SetValidateInfo(UserInfo userInfo)
    {
      if (UserValidate._htUserInfo == null)
        UserValidate._htUserInfo = new Hashtable();

      string loginID = userInfo.LoginID;
      if (UserValidate._htUserInfo.Contains(loginID))
      {
        UserValidate._htUserInfo[loginID] = userInfo;
      }
      else
      {
        UserValidate._htUserInfo.Add(loginID, userInfo);
      }
    }

    private UserInfo SetUserInfo(DataRow dr)
    {
      UserInfo info;

      try
      {
        info = new UserInfo();
        info.LoginID = dr["LOGINID"].ToString();
        info.UserID = dr["USERID"].ToString();
        info.UserName = dr["NAME"].ToString();
        info.ValidateGuid = Guid.NewGuid().ToString();

        UpdateValidateGuid(info);

        return info;
      }
      catch (Exception ex)
      {
        throw ex;
      }
    }
    private void UpdateValidateGuid(UserInfo info)
    {
      string sqlstr = "UPDATE CXUSER.UAM_AUTHORIZATION SET VALIDATECODE = '"
        + info.ValidateGuid + "' WHERE LOGINID = '"
        + info.LoginID + "' AND USERID = '"
        + info.UserID + "'";
      string ErrorInfo = "";

      int i = DBManager.ExecuteNonQuery(sqlstr, out ErrorInfo);

      if (i == 0)
      {
        throw new Exception(ErrorInfo);
      }

    }

    public ReturnObject ChangePasswd(string userID, string passwd, string passwdNew)
    {
      string sqlstr = "SELECT * FROM UAMV_AUTHORROLE WHERE LOGINID = '" + userID + "' AND PASSWORD = '" + PasswdSecurity(passwd) + "'";
      string err = "";

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

      if (err != "" || ds == null || ds.Tables.Count == 0)
      {
        return new ReturnObject(null, "数据库连接错误！");
      }
      if (ds.Tables[0].Rows.Count == 0)
      {
        return new ReturnObject(null, "用户名或密码错误!");
      }
      else
      {
        sqlstr = "update UAMV_AUTHORROLE set PASSWORD = '" + passwdNew + "' where LOGINID = '" + userID + "'";
        err = "";

        object obj = DBManager.ExecuteNonQuery(sqlstr, out err);

        if (err != "")
        {
          return new ReturnObject(null, "数据库连接错误！");
        }
        try
        {
          if (Convert.ToInt32(obj) > 0)
          {
            return new ReturnObject(1);
          }
          else
          {
            return new ReturnObject(null, "密码修改失败!");
          }
        }
        catch
        {
          return new ReturnObject(null, "密码修改失败!");
        }
      }
    }
    #endregion

    #region "	Get Files	"
    public ReturnObject GetFiles()
    {
      try
      {
        string[] fileNames = Directory.GetFiles(@"CA\", "*.xml");

        return new ReturnObject(fileNames);
      }
      catch (Exception ex)
      {
        return new ReturnObject(null, ex.Message);
      }
    }
    #endregion

    #region "	User Manager	"

    #region "	Department Manager	"
    public ReturnObject SelectUAM_DEPARTMENT(string strWhere)
    {
      CheckPartClass();
      return _departmentClass.SelectUAM_DEPARTMENT(strWhere);
    }
    public ReturnObject InsertUAM_DEPARTMENT(ArrayList ar)
    {
      CheckPartClass();
      return _departmentClass.InsertUAM_DEPARTMENT(ar);
    }
    public ReturnObject DeleteUAM_DEPARTMENT(string strWhere)
    {
      CheckPartClass();
      return _departmentClass.DeleteUAM_DEPARTMENT(strWhere);
    }
    public ReturnObject UpdateUAM_DEPARTMENT(ArrayList ar)
    {
      CheckPartClass();
      return _departmentClass.UpdateUAM_DEPARTMENT(ar);
    }
    public ReturnObject UpdateDsPart(DataSet ds, string sqlstr)
    {
      CheckPartClass();
      return _departmentClass.UpdateDataSet(ds, sqlstr);
    }

    private void CheckPartClass()
    {
      if (_departmentClass == null)
      {
        _departmentClass = new UAM_DEPARTMENT();
        _departmentClass.DBManager = this.DBManager;
      }
    }
    #endregion

    #region "	Role Manager	"
    public ReturnObject SelectUAM_ROLE(string strWhere)
    {
      CheckRoleClass();
      return _roleClass.SelectUAM_ROLE(strWhere);
    }
    public ReturnObject InsertUAM_ROLE(ArrayList ar)
    {
      CheckRoleClass();
      return _roleClass.InsertUAM_ROLE(ar);
    }
    public ReturnObject UpdateUAM_ROLE(ArrayList ar)
    {
      CheckRoleClass();
      return _roleClass.UpdateUAM_ROLE(ar);
    }
    public ReturnObject UpdateDsRole(DataSet ds, string sqlstr)
    {
      CheckRoleClass();
      return _roleClass.UpdateDataSet(ds, sqlstr);
    }
    public ReturnObject DeleteUAM_ROLE(string strWhere)
    {
      CheckRoleClass();
      return _roleClass.DeleteUAM_ROLE(strWhere);
    }

    private void CheckRoleClass()
    {
      if (_roleClass == null)
      {
        _roleClass = new UAM_ROLE();
        _roleClass.DBManager = this.DBManager;
      }
    }
    #endregion

    #region "	Function Manager	"
    public ReturnObject SelectUAM_FUNCTION(string strWhere)
    {
      CheckFuncClass();
      return _functionClass.SelectUAM_FUNCTION(strWhere);
    }
    public ReturnObject UpdateDsFunc(DataSet ds, string sqlstr)
    {
      CheckFuncClass();
      return _functionClass.UpdateDataSet(ds, sqlstr);
    }
    public ReturnObject DeleteUAM_FUNCTION(string strWhere)
    {
      CheckFuncClass();
      return _functionClass.DeleteUAM_FUNCTION(strWhere);
    }
    public ReturnObject InsertUAM_FUNCTION(ArrayList ar)
    {
      CheckFuncClass();
      return _functionClass.InsertUAM_FUNCTION(ar);
    }
    public ReturnObject UpdateUAM_FUNCTION(ArrayList ar)
    {
      CheckFuncClass();
      return _functionClass.UpdateUAM_FUNCTION(ar);
    }

    private void CheckFuncClass()
    {
      if (_functionClass == null)
      {
        _functionClass = new UAM_FUNCTION();
        _functionClass.DBManager = this.DBManager;
      }
    }
    #endregion

    #region "	User Manager	"
    public ReturnObject SelectUAM_USER(string strWhere)
    {
      CheckUserClass();
      return _userClass.SelectUAM_USER(strWhere);
    }
    public ReturnObject InsertUAM_USER(ArrayList ar)
    {
      CheckUserClass();
      return _userClass.InsertUAM_USER(ar);
    }
    public ReturnObject UpdateUAM_USER(ArrayList ar)
    {
      CheckUserClass();
      return _userClass.UpdateUAM_USER(ar);
    }
    public ReturnObject DeleteUAM_USER(string strWhere)
    {
      CheckUserClass();
      return _userClass.DeleteUAM_USER(strWhere);
    }
    public ReturnObject UpdateDsUser(DataSet ds, string sqlstr)
    {
      CheckUserClass();
      return _userClass.UpdateDataSet(ds, sqlstr);
    }
    public ReturnObject GetUAM_USER(string where)
    {
      CheckUserClass();
      return _userClass.GetUAM_USER(where);
    }
    private void CheckUserClass()
    {
      if (_userClass == null)
      {
        _userClass = new UAM_USER();
        _userClass.DBManager = this.DBManager;
      }
    }
    #endregion

    #region "	Author Manager	"
    public ReturnObject SelectUAM_AUTHORIZATION(string strWhere)
    {
      CheckAuthorClass();
      return _authorClass.SelectUAM_AUTHORIZATION(strWhere);
    }
    public ReturnObject GetUAM_AUTHORIZATION(string where)
    {
      CheckAuthorClass();
      return _authorClass.GetUAM_AUTHORIZATION(where);
    }
    public ReturnObject InsertUAM_AUTHORIZATION(ArrayList ar)
    {
      CheckAuthorClass();
      return _authorClass.InsertUAM_AUTHORIZATION(ar);
    }
    public ReturnObject UpdateUAM_AUTHORIZATION(ArrayList ar)
    {
      CheckAuthorClass();
      return _authorClass.UpdateUAM_AUTHORIZATION(ar);
    }
    public ReturnObject DeleteUAM_AUTHORIZATION(string strWhere)
    {
      CheckAuthorClass();
      return _authorClass.DeleteUAM_AUTHORIZATION(strWhere);
    }
    public ReturnObject UpdateAuUser(DataSet ds, string sqlstr)
    {
      CheckAuthorClass();
      return _authorClass.UpdateDataSet(ds, sqlstr);
    }

    private void CheckAuthorClass()
    {
      if (_authorClass == null)
      {
        _authorClass = new UAM_AUTHORIZATION();
        _authorClass.DBManager = this.DBManager;
      }
    }
    #endregion

    #endregion

    //#region "SelectTestUser"
    //public ReturnObject SelectTestUser()
    //{
    //    CheckTestUserClass();
    //    return _testuserClass.SelectTestUser();
    //}
    //public ReturnObject Query(string str)
    //{
    //    CheckTestUserClass();
    //    return _testuserClass.Query(str);
    //}
    //public ReturnObject Add(string Id, string DptId, string Name, string Sex)
    //{
    //    CheckTestUserClass();
    //    return _testuserClass.Add(Id, DptId, Name, Sex);
    //}
    //public ReturnObject Modify(string Id, string DptId, string Name, string Sex)
    //{
    //    CheckTestUserClass();
    //    return _testuserClass.Modify(Id, DptId, Name, Sex);
    //}
    //private void CheckTestUserClass()
    //{
    //    if (_testuserClass == null)
    //    {
    //        _testuserClass = new TestUser();
    //        _testuserClass.DBManager = this.DBManager;
    //    }
    //}
    //#endregion

    #region "	Interface	"

    public void Dispose()
    {

    }

    //	public STMes.DBManager DBManager
    //	{
    //		set {DBManager = value;}
    //		get {return DBManager;}
    //	}

    public string Description
    {
      get
      {
        string _description = "权限管理服务端，用于在客户端输入用户名密码后";
        _description += "由服务端来获取对应权限文件，然后根据权限文件将相应";
        _description += "的窗体信息从数据库中读出，再将信息合并到权限";
        _description += "文件中，然后将权限文件返回给客户端生成菜单文件";

        return _description;
      }
    }

    #endregion

  }
}
