using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using RFrameGenerate.DAL;
using RFrameGenerate.DAL.Interface;
using RFrameGenerate.Model;
using System.Data;
using RFramework.SQLServer;
using RFramework.SQLQuery;
using RFrameGenerate.Common;

namespace RFrameGenerate.BLL.Organization
{
    public class UserManage
    {
        public List<UserRoleList> GetUserPageList(GridModel gridModel, string userName)
        {
            using (var query = Factory.CreateT_ST_UserAndRoleView())
            {
                var urlist = query.GetPageList(gridModel, a => a.MerchantGuid == CurrentManage.MerchantGuid && a.UserName.SqlLike(userName), true, b => b.UserGuid);
                List<UserRoleList> list = new List<UserRoleList>();
                foreach (var v in urlist)
                {
                    var item = list.Where(a => a.UserGuid == v.UserGuid).FirstOrDefault();
                    if (item != null)
                    {
                        item.RoleName += "," + v.RoleName;
                    }
                    else
                    {
                        list.Add(new UserRoleList()
                        {
                            UserGuid = v.UserGuid,
                            LoginName = v.LoginName,
                            UserName = v.UserName,
                            RoleName = v.RoleName,
                            Remark = v.Remark,
                        });
                    }
                }
                return list;
            }
        }

        public List<UserRoleModel> GetRoleList(Guid UserGuid)
        {
            SqlRTransaction tran = new SqlRTransaction();
            var queryRole = Factory.CreateT_ST_Role(tran);
            var roleList = queryRole.GetList(a => a.MerchantGuid == CurrentManage.MerchantGuid);

            var queryUR = Factory.CreateT_ST_User_Role(tran);
            var roleListOld = queryUR.GetList(a => a.UserGuid == UserGuid && a.MerchantGuid == CurrentManage.MerchantGuid);
            tran.Dispose();
            List<UserRoleModel> list = new List<UserRoleModel>();
            foreach (var role in roleList)
            {
                list.Add(new UserRoleModel() { RoleGuid = role.RoleGuid, RoleName = role.RoleName + "  " + role.RoleRemark });
            }
            foreach (var role in roleListOld)
            {
                var rolestate = list.Where(a => a.RoleGuid == role.RoleGuid).FirstOrDefault();
                rolestate.Check = true;
            }
            return list;
        }

        public Result UpdateUserRole(Guid UserGuid, Guid[] checkedRole)
        {
            try
            {
                using (SqlRTransaction tan = new SqlRTransaction())
                {
                    if (checkedRole == null)
                    {
                        var qeuryRP0 = Factory.CreateT_ST_User_Role(tan);
                        qeuryRP0.Delete(a => a.UserGuid == UserGuid && a.MerchantGuid == CurrentManage.MerchantGuid);
                        return new Result(true);
                    }

                    List<T_ST_User_Role> addList = new List<T_ST_User_Role>();
                    foreach (var v in checkedRole)
                    {
                        T_ST_User_Role rp = new T_ST_User_Role()
                        {
                            User_RoleGuid = Guid.NewGuid(),
                            UserGuid = UserGuid,
                            RoleGuid = v,
                            MerchantGuid = CurrentManage.MerchantGuid,
                        };
                        addList.Add(rp);
                    }
                    tan.BeginTransaction();
                    var qeuryRP = Factory.CreateT_ST_User_Role(tan);
                    qeuryRP.Delete(a => a.UserGuid == UserGuid && a.MerchantGuid == CurrentManage.MerchantGuid);
                    qeuryRP.AddList(addList);
                    tan.Commit();
                }

                return new Result(true);
            }
            catch (Exception e)
            {
                return new Result(false, e.Message);
            }
        }
        /// <summary>
        /// 登录验证
        /// </summary>
        /// <param name="UserID">用户id</param>
        /// <param name="password">密码</param>
        /// <returns></returns>
        public static Result IsValid(string loginName, string password, out T_ST_User user)
        {
            using (var query = Factory.CreateT_ST_User())
            {
                user = query.GetFirstData(a => a.LoginName == loginName);
                if (user == null)
                    return new Result(false, "不存在用户:" + loginName);
                if (user.Password == password)
                {
                    return new Result(true);
                }
                else
                    return new Result(false, "密码不正确");
            }
        }

        public static Result IsKeyValid(string loginName, string key, out T_ST_User user)
        {
            using (var query = Factory.CreateT_ST_User())
            {
                user = query.GetFirstData(a => a.LoginName == loginName && a.Password == key);
                if (user == null)
                    return new Result(false, "账号或密码错误");
                else
                    return new Result(true);
            }
        }

        public Result AddUser(T_ST_User user)
        {
            if (user.LoginName.Contains("@") == true)
            {
                return new Result(false, "用户登录名不能包含@");
            }
            else
            {
                user.LoginName = string.Format("{0}@{1}", CurrentManage.MerchantUserID, user.LoginName);
            }

            if (user.Password == null)
                user.Password = string.Empty;


            using (var query = Factory.CreateT_ST_User())
            {
                if (query.IsExist(a => a.LoginName == user.LoginName) != true)
                {
                    query.Add(new T_ST_User()
                    {
                        UserGuid = Guid.NewGuid(),
                        UserName = user.UserName,
                        LoginName = user.LoginName,
                        Remark = user.Remark,
                        Password = Utils.Md5(user.Password),
                        MerchantGuid = CurrentManage.MerchantGuid,
                    });
                    return new Result(true);
                }
                else
                {
                    return new Result(false, user.LoginName + "已存在,登录名必须唯一");
                }
            }
        }

        public Result SaveUser(T_ST_User user)
        {
            if (user.LoginName.Contains("@") == true)
            {
                return new Result(false, "用户登录名不能包含@");
            }
            else
            {
                user.LoginName = string.Format("{0}@{1}", CurrentManage.MerchantUserID, user.LoginName);
            }
            using (var query = Factory.CreateT_ST_User())
            {
                var dbuser = query.GetFirstData(a => a.UserGuid == user.UserGuid && a.MerchantGuid == CurrentManage.MerchantGuid);
                if (dbuser.LoginName != user.LoginName)
                {
                    if (query.IsExist(a => a.LoginName == user.LoginName && a.MerchantGuid == CurrentManage.MerchantGuid) == true)
                        return new Result(false, user.LoginName + "已存在,登录名必须唯一");
                }
                if (string.IsNullOrEmpty(user.Password) == true)
                {
                    query.Update(a => new object[]
                                        {
                                            a.UserName == user.UserName,
                                            a.Remark == user.Remark,
                                            a.LoginName==user.LoginName,
                                        }, b => b.UserGuid == user.UserGuid && b.MerchantGuid == CurrentManage.MerchantGuid);
                }
                else
                {
                    query.Update(a => new object[]
                                        {
                                            a.UserName == user.UserName,
                                            a.Remark == user.Remark, 
                                            a.LoginName==user.LoginName,
                                            a.Password == RFrameGenerate.Common.Utils.Md5(user.Password),
                                        }, b => b.UserGuid == user.UserGuid && b.MerchantGuid == CurrentManage.MerchantGuid);
                }

                return new Result(true);
            }
        }


    }
}