using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using JLHHJSvr.Com.Model;
using JLHHJSvr.DBA.DBModle;
using LJLib.DAL.SQL;
using LJLib.Tools.DEncrypt;
using JLHHJSvr.LJException;
using System.Linq;

namespace JLHHJSvr.BLL
{
    internal sealed class UserHelper
    {
        private static Dictionary<string, TokenData> _tokens = new Dictionary<string, TokenData>();

        ///// <summary>
        ///// TODO: 保存Token信息, 登录成功后绑定token与tokendata
        ///// </summary>
        ///// <param name="token"></param>
        ///// <param name="tokendata"></param>
        //public static void SetToken(string token, TokenData tokendata)
        //{
        //    _tokens[token] = tokendata;
        //}

        ///// <summary>
        ///// TODO: 带token请求是通过本方法获取tokendata
        ///// </summary>
        ///// <param name="token"></param>
        ///// <returns>tokendata</returns>
        //public static TokenData GetToken(string token)
        //{
        //    if (_tokens.ContainsKey(token))
        //    {
        //        return _tokens[token];
        //    }
        //    else
        //    {
        //        return null;
        //    }
        //}

        ///// <summary>
        ///// TODO: 获取ID
        ///// </summary>
        ///// <param name="cmd">数据库连接,事务</param>
        ///// <param name="key">关联字</param>
        ///// <param name="step">增幅,默认1</param>
        ///// <returns>新ID上限</returns>
        //public static int GetID(SqlCommand cmd, string key, int step = 1)
        //{
        //    int rslt = 0;
        //    cmd.CommandText = "UPDATE cd_idfactory SET idvalue = idvalue + @step, @curid = idvalue + @step WHERE idkey = @idkey";
        //    cmd.Parameters.Clear();
        //    cmd.Parameters.Add("@idkey", SqlDbType.VarChar).Value = key;
        //    cmd.Parameters.Add("@step", SqlDbType.Int).Value = step;
        //    cmd.Parameters.Add("@curid", SqlDbType.Int).Direction = ParameterDirection.Output;
        //    int nrows = cmd.ExecuteNonQuery();
        //    if (nrows == 0)
        //    {
        //        rslt = 10 + step;
        //        cmd.CommandText = "INSERT INTO cd_idfactory(idkey, idvalue) VALUES(@idkey, @curid)";
        //        cmd.Parameters.Clear();
        //        cmd.Parameters.Add("@idkey", SqlDbType.VarChar).Value = key;
        //        cmd.Parameters.Add("@curid", SqlDbType.Int).Value = rslt;
        //        cmd.ExecuteNonQuery();
        //    }
        //    else
        //    {
        //        rslt = Convert.ToInt32(cmd.Parameters["@curid"].Value);
        //    }
        //    return rslt;
        //}

        ///// <summary>
        ///// 初始化超级用户
        ///// </summary>
        ///// <param name="constr">数居库连接字符串</param>
        //public static void InitUser(string constr)
        //{
        //    using (var con = new SqlConnection(constr))
        //    using (var cmd = con.CreateCommand())
        //    {
        //        con.Open();
        //        using (cmd.Transaction = con.BeginTransaction())
        //        {
        //            try
        //            {
        //                var user = new st_user {userid = 11};
        //                if (DbSqlHelper.SelectOne(cmd, user, "usercode") != 1)
        //                {
        //                    var id = GetID(cmd, "st_user");
        //                    user.userid = id;
        //                    user.usercode = "super";
        //                    user.username = "超级用户";
        //                    user.psw = DESEncrypt.Encrypt("super", "BC493812B6664BECBF44C21C3BB043C4");
        //                    user.sex = "男";
        //                    user.tel = string.Empty;
        //                    user.dscrp = string.Empty;
        //                    user.opemp = "初始化生成";
        //                    user.opdate = DateTime.Now;
        //                    user.modemp = "初始化生成";
        //                    user.moddate = DateTime.Now;
        //                    DbSqlHelper.InsertOrUpdate(cmd, user, "userid,usercode,username,psw,sex,tel,dscrp,opemp,opdate,modemp,moddate");
        //                    var powers = new Power().GetAllPowers();
        //                    var userPower = new st_user_power { userid = user.userid };
        //                    foreach (var power in powers)
        //                    {
        //                        userPower.funid = power.funid;
        //                        DbSqlHelper.Insert(cmd, userPower, "userid, funid");
        //                    }
        //                }
        //                cmd.Transaction.Commit();
        //            }
        //            catch (Exception e)
        //            {
        //                cmd.Transaction.Rollback();
        //                Trace.Write("初始化super用户数据失败："+e.ToString());
        //            }
        //        }
        //    }
        //}

        public static bool CheckFuncPower(SqlCommand cmd, int empid, int funcid)
        {
            if (empid == 0)
            {
                return true;
            }
            var user = new u_user_jlhprice() { empid = empid };
            if (DbSqlHelper.SelectOne(cmd, user, "empid,rightstring") != 1)
            {
                throw new Exception(string.Format("查询用户信息失败,empid:{0}", empid));
            }
            return HasPower(funcid, user.rightstring);
        }
        private static bool HasPower(int funcid, string sys_pwrstr)
        {
            bool hasPower;
            hasPower = funcid > 0 && sys_pwrstr.Length >= funcid &&
                       sys_pwrstr.Substring(funcid - 1, 1) == "1";
            return hasPower;
        }
        private static Dictionary<int, sys_func_pwr> _funcCache = new Dictionary<int, sys_func_pwr>();
        class sys_func_pwr
        {
            public int funcid { get; set; }
            public byte functype { get; set; }
            public int parentid { get; set; }
        }
        private static void LoadFuncCache(SqlCommand cmd)
        {
            if (_funcCache.Count == 0)
            {
                lock (_funcCache)
                {
                    if (_funcCache.Count == 0)
                    {
                        cmd.CommandText = "SELECT funcid,functype,parentid FROM sys_func_pwr";
                        cmd.Parameters.Clear();
                        using (var reader = cmd.ExecuteReader())
                        {
                            while (reader.Read())
                            {
                                var func = new sys_func_pwr
                                {
                                    funcid = Convert.ToInt32(reader["funcid"]),
                                    functype = Convert.ToByte(reader["functype"]),
                                    parentid = Convert.ToInt32(reader["parentid"]),
                                };
                                _funcCache[func.funcid] = func;
                            }
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 过滤出当前用户有的权限列表
        /// </summary>
        /// <param name="empid">当前用户empid</param>
        /// <returns></returns>
        public static List<int> FilterMyFunids(SqlCommand cmd, int empid)
        {
            LoadFuncCache(cmd);
            var rslt = new HashSet<int>();

            var user = new u_user_jlhprice() { empid = empid};
            if (DbSqlHelper.SelectOne(cmd, user, "empid,rightstring") != 1)
            {
                throw  new Exception(string.Format("查询用户信息失败,empid:{0}", empid));
            }

            foreach (var funcItem in _funcCache)
            {
                var hasPower = empid == 0 || HasPower(funcItem.Value.funcid, user.rightstring);

                if (hasPower && !rslt.Contains(funcItem.Value.funcid))
                {
                    rslt.Add(funcItem.Value.funcid);
                }
            }

            return rslt.ToList();
        }
    }
}