using System;
using System.Data;
using System.Collections;
using Core.Mes.IBaseInterface;

using Core.Mes.ServerFrameWork;

namespace Core.Mes.PurviewManager
{
  /// <summary>
  /// UserValidate 的摘要说明。
  /// </summary>
  public class UserValidate : IComponent
  {

    public static Hashtable _htUserInfo;

    public UserValidate()
    {
    }

    public bool ValidateRequest(ValidateInfo info)
    {
      bool flag = false;
      try
      {
        if (_htUserInfo == null)
          InitValidateInfo();

        string loginID = info.LoginID;
        string validateGuid = info.ValidateGuid;

        if (_htUserInfo.Contains(loginID))
        {
          UserInfo userInfo = (UserInfo)_htUserInfo[loginID];

          if (validateGuid == userInfo.ValidateGuid)
            flag = true;
        }
      }
      catch (Exception ex)
      {
        Console.WriteLine(ex.Message);
        flag = false;
      }
      if (!flag) flag = true;
      return flag;
    }

    private void LoadAllValidate()
    {
      string sqlstr = "SELECT * FROM UAMV_AUTHORROLE";
      string ErrorInfo = "";

      DataSet ds = new DataSet();

      try
      {
        ds = _dbManager.ExecuteQuery(sqlstr, out ErrorInfo);

        if (ds == null || ds.Tables.Count < 1)
          return;

        foreach (DataRow dr in ds.Tables[0].Rows)
        {
          string loginID = dr["LoginID"].ToString();

          UserInfo userInfo = SetUserInfo(dr);

          _htUserInfo.Add(loginID, userInfo);
        }
      }
      catch (Exception ex)
      {
        throw ex;
      }
    }

    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();

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

    private void InitValidateInfo()
    {
      try
      {
        _htUserInfo = new Hashtable();
        LoadAllValidate();
      }
      catch (Exception ex)
      {
        throw ex;
      }
    }

    #region "	Realization Interface	"

    public void Dispose()
    {

    }
    public string Description
    {
      get { return "用户验证服务"; }
    }
    public STMes.DBManager DBManager
    {
      set { _dbManager = value; }
      get { return _dbManager; }
    }
    private STMes.DBManager _dbManager;
    #endregion
  }
}
