using System;
using System.Collections.Generic;
using System.Text;
using JuSNS.Factory;
using System.Data.SqlClient;
using JuSNS.Model;
using System.Reflection;
using JuSNS.Profile;
using System.Data;
using JuSNS.Config;
using JuSNS.Factory.ApiInterface;
using JuSNS.Model.ApiInterface;

namespace JuSNS.SQLServer.ApiInterface
{
    public class ApiUser : DbBase, IApiUser
    {
        #region 接口实现
        /// <summary>
        /// 取得字段属性
        /// </summary>
        /// <param name="Field">字段名称</param>
        /// <param name="UserID">用户ID</param>
        /// <returns></returns>
        public string GetProperty(int UserID, string Field)
        {
            SqlParameter param = new SqlParameter("@UserID", UserID);
            Type type;
            string tabName = GetTableName(Field,out type);
            string sql = "select " + Field + " from " + tabName + " where UserID=@UserID";
            object tobj = DbHelper.ExecuteScalar(CommandType.Text, sql, param);
            if (tobj == DBNull.Value || tobj == null)
            {
                return "";
            }
            else
            {
                return Convert.ToString(tobj);
            }
        }
        /// <summary>
        /// 取得所有的字段属性
        /// </summary>
        /// <param name="Fields">字段名称</param>
        /// <param name="UserID">用户ID</param>
        /// <returns></returns>
        public Dictionary<string, string> GetAllProperty(int UserID, string[] Fields)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            foreach (string Field in Fields)
            {
                string value = GetProperty(UserID, Field);
                dic.Add(Field, value);
            }
            return dic;
        }
        /// <summary>
        /// 是否有这个字段
        /// </summary>
        /// <param name="Field">字段名称</param>
        /// <returns></returns>
        public bool HasField(string Field)
        {
            string[] Fields = GetFields();
            foreach (string field in Fields)
            {
                if (field.ToLower() == Field.ToLower())
                    return true;
            }
            return false;
        }
        /// <summary>
        /// 取得所有字段名称
        /// </summary>
        /// <returns></returns>
        public string[] GetFields()
        {
            string str=UserApiConfig.SysConfig["AllFields"];
            string[] arr = str.Split(',');
            return arr;
        }
        /// <summary>
        /// 设置某个字段的值
        /// </summary>
        /// <param name="UserID">用户ID</param>
        /// <param name="Field"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public int SetField(int UserID, string Field, object value)
        {
            if (!CanWrite(Field))
            {
                //如果不可写
                return 0;
            }
            Type type;
            string tabName = GetTableName(Field,out type);
            SqlParameter[] param ={
                    new SqlParameter("@UserID", UserID),
                    new SqlParameter("@Value",ConvertType(type))
                };
            param[1].Value = value;
            string sql = "update "+tabName+" set "+Field+"=@Value where UserID=@UserID ";
            return DbHelper.ExecuteNonQuery(CommandType.Text, sql, param);
        }
        /// <summary>
        /// 某个字段是否可写
        /// </summary>
        /// <param name="Field">字段名称</param>
        /// <returns></returns>
        public bool CanWrite(string Field)
        {
            string WFields=UserApiConfig.SysConfig["WriteFields"];
            string[] fields = WFields.Split(',');
            foreach (string field in fields)
            {
                if (field == Field)
                    return true;
            }
            return false;
        }
        /// <summary>
        /// 是否添加某个应用
        /// </summary>
        /// <param name="UserID"></param>
        /// <param name="AppID"></param>
        /// <returns></returns>
        public bool IsAppAdded(int UserID, int AppID)
        {
            SqlParameter[] param =
                {
                    new SqlParameter("@UserID",UserID),
                    new SqlParameter("@AppID",AppID)
                };
            string sql = "Select Count(*) from App_UserApp where UserID=@UserID and AppID=@AppID";
            int n = Convert.ToInt32(DbHelper.ExecuteScalar(CommandType.Text, sql, param));
            if (n > 0)
                return true;
            return false;
        }
        /// <summary>
        /// 取得头像
        /// </summary>
        /// <param name="UserID">用户ID</param>
        /// <returns></returns>
        public string GetHeadImg(int UserID)
        {
            SqlParameter param = new SqlParameter("@UserID", UserID);
            string sql = "select Portrait from NT_User where UserID=@UserID";
            int id = Convert.ToInt32(DbHelper.ExecuteScalar(CommandType.Text, sql, param));
            sql = "select FilePath from Nt_Photo where UploadUser=@UserID and PhotoType=0";
            string filepath = Convert.ToString(DbHelper.ExecuteScalar(CommandType.Text, sql, param));
            return filepath;
        }
        /// <summary>
        /// 用户ID是否存在
        /// </summary>
        /// <param name="UserID">用户ID</param>
        /// <returns></returns>
        public bool ExistUserID(int UserID)
        {
            SqlParameter param = new SqlParameter("@UserID", UserID);
            string sql = "select Count(*) from Nt_User where UserID=@UserID";
            int n = Convert.ToInt32(DbHelper.ExecuteScalar(CommandType.Text, sql, param));
            if (n > 0)
            {
                return true;
            }
            return false;
        }
        /// <summary>
        /// 存在Email
        /// </summary>
        /// <param name="email"></param>
        /// <returns></returns>
        public bool ExistEmail(string email)
        {
            SqlParameter param = new SqlParameter("@Email", email);
            string sql = "select Count(*) from Nt_User where Email=@Email";
            int n = Convert.ToInt32(DbHelper.ExecuteScalar(CommandType.Text, sql, param));
            if (n > 0)
            {
                return true;
            }
            return false;
        }
        #endregion

        /// <summary>
        /// 根据字段名取得表名
        /// </summary>
        /// <param name="fieldName">字段名称</param>
        /// <returns></returns>
        private static string GetTableName(string fieldName,out Type type)
        {            
            UserInfo ui = new UserInfo();
            PropertyInfo Fi = ui.GetType().GetProperty(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase);
            if (Fi != null)
            {
                type = Fi.GetType();
                return "NT_User";
            }

            UserBasicInfo bs = new UserBasicInfo();
            Fi = bs.GetType().GetProperty(fieldName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase);
            if (Fi != null)
            {
                type = Fi.GetType();
                return "NT_UserInfo";
            }

            type = typeof(string);
            return string.Empty;
        }
       
        /// <summary>
        /// 转换Type为SqlDbType
        /// </summary>
        /// <param name="t"></param>
        /// <returns></returns>
        private static SqlDbType ConvertType(Type t)
        {
            switch (Type.GetTypeCode(t))
            {
                case TypeCode.Boolean:
                    return SqlDbType.Bit;
                case TypeCode.Byte:
                    return SqlDbType.TinyInt;
                case TypeCode.DateTime:
                    return SqlDbType.DateTime;
                case TypeCode.Decimal:
                    return SqlDbType.Decimal;
                case TypeCode.Double:
                    return SqlDbType.Float;
                case TypeCode.Int16:
                    return SqlDbType.SmallInt;
                case TypeCode.Int32:
                    return SqlDbType.Int;
                case TypeCode.Int64:
                    return SqlDbType.BigInt;
                case TypeCode.SByte:
                    return SqlDbType.TinyInt;
                case TypeCode.Single:
                    return SqlDbType.Real;
                case TypeCode.String:
                    return SqlDbType.NVarChar;
                case TypeCode.UInt16:
                    return SqlDbType.SmallInt;
                case TypeCode.UInt32:
                    return SqlDbType.Int;
                case TypeCode.UInt64:
                    return SqlDbType.BigInt;
                default:
                    return SqlDbType.Variant;
            }
        }
    }
}
