using System;
using System.Collections.Generic;
using System.Linq;
using Whir.Domain;
using Whir.ezEIP.Web;
using Whir.Framework;
using Whir.Service;
using Whir.Config;
using Whir.Language;
using System.Text;
using Whir.Security.Service;
using Whir.Security.Domain;


public partial class Whir_System_Handler_Security_Security : SysHandlerPageBase
{
    protected void Page_Load(object sender, EventArgs e)
    {
        var action = RequestUtil.Instance.GetString("_action");
        Exec(this, action);
    }

    /// <summary>
    /// 保存数据
    /// </summary>
    /// <returns></returns>
    public HandlerResult Save()
    {
        int userId = RequestUtil.Instance.GetFormString("UserId").ToInt(0);

        //反射获取表单字段数据
        var type = typeof(Users);
        var user = ServiceFactory.UploadService.SingleOrDefault<Users>(userId) ?? ModelFactory<Users>.Insten();
        var password = user.Password;
        user = GetPostObject(type, user) as Users;
        if (userId <= 0)
        {
            try
            {
                if (user != null && Whir.Security.ServiceFactory.UsersService.IsUserExists(user.LoginName))
                {
                    return new HandlerResult { Status = false, Message = "该用户名已存在".ToLang() };
                }
                if (user != null)
                {
                    user.LastLoginTime = DateTimeExt.MinDateTime;
                    user.Password = StrExt.GetSHA1Str(user.Password);
                    user.SystemLanguage = 1;
                    user.SystemSkin = "Res/Images/Bg/bg6.jpg";

                    Whir.Security.ServiceFactory.UsersService.Save(user);

                    Whir.Service.ServiceFactory.OperateLogService.Save(string.Format("添加管理员【{0}】", user.LoginName));
                }
            }
            catch (Exception)
            {
                return new HandlerResult { Status = false, Message = "添加失败".ToLang() };
            }
        }
        else
        {
            try
            {
                if (user != null)
                {
                    user.Password = user.Password != "" ? StrExt.GetSHA1Str(user.Password) : password;

                    Whir.Security.ServiceFactory.UsersService.Update(user);
                    Whir.Service.ServiceFactory.OperateLogService.Save(string.Format("修改管理员【{0}】信息", user.LoginName));
                }
                else
                {
                    return new HandlerResult { Status = false, Message = "找不到记录" };
                }
            }
            catch (Exception)
            {
                return new HandlerResult { Status = false, Message = "修改失败" };
            }
        }

        return new HandlerResult { Status = true, Message = "保存成功" };

    }

    /// <summary>
    /// 禁用
    /// </summary>
    /// <returns></returns>
    public HandlerResult Disabled()
    {
        int userId = RequestUtil.Instance.GetFormString("userid").ToInt(0);
        if (userId.Equals(1))
        {
            return new HandlerResult { Status = false, Message = "该账号不能被禁用".ToLang() };
        }
        var result = Whir.Security.ServiceFactory.UsersService.SetUserState(userId, 1);
        if (result == -1)
        {
            return new HandlerResult { Status = false, Message = "禁用失败,至少需要保留一个非禁用状态的超级管理员账号".ToLang() };
        }
        return new HandlerResult { Status = true, Message = "操作成功" };
    }

    /// <summary>
    /// 启用
    /// </summary>
    /// <returns></returns>
    public HandlerResult Enabled()
    {
        int userId = RequestUtil.Instance.GetFormString("userid").ToInt(0);
        Whir.Security.ServiceFactory.UsersService.SetUserState(userId, 0);
        return new HandlerResult { Status = true, Message = "操作成功" };
    }

    /// <summary>
    /// 删除
    /// </summary>
    /// <returns></returns>
    public HandlerResult Delete()
    {
        int userId = RequestUtil.Instance.GetFormString("userid").ToInt(0);
        int result = Whir.Security.ServiceFactory.UsersService.DeleteUser(userId);
        if (result == -1)
        {
            return new HandlerResult { Status = false, Message = "删除失败,至少需要保留一个非禁用状态的超级管理员账号".ToLang() };
        }
        if (result == 0)
        {
            return new HandlerResult { Status = false, Message = "删除失败".ToLang() };
        }
        return new HandlerResult { Status = true, Message = "" };
    }

    /// <summary>
    /// 个人资料
    /// </summary>
    /// <returns></returns>
    public HandlerResult UpdateUserInfo()
    {
        int userId = RequestUtil.Instance.GetFormString("UserId").ToInt(0);

        //反射获取表单字段数据
        var type = typeof(Users);
        var user = ServiceFactory.UploadService.SingleOrDefault<Users>(userId) ?? ModelFactory<Users>.Insten();
        user = GetPostObject(type, user) as Users;
        if (userId <= 0)
        {
            return new HandlerResult { Status = false, Message = "当前用户不存在".ToLang() };
        }
        else
        {
            Whir.Security.ServiceFactory.UsersService.Update(user);
            Whir.Service.ServiceFactory.OperateLogService.Save(string.Format("修改管理员【{0}】个人信息", user.LoginName));
        }

        return new HandlerResult { Status = true, Message = "保存成功".ToLang() };
    }

    /// <summary>
    /// 密码设置
    /// </summary>
    /// <returns></returns>
    public HandlerResult ChangePwd()
    {
        int userId = RequestUtil.Instance.GetFormString("UserId").ToInt(0);
        string oldPassword = RequestUtil.Instance.GetFormString("txtOldPassword");
        string newPassword = RequestUtil.Instance.GetFormString("txtNewPassWord");

        if (userId > 0)
        {
            if (newPassword != "")
            {
                oldPassword = StrExt.GetSHA1Str(oldPassword);
                newPassword = StrExt.GetSHA1Str(newPassword);
                Users model = Whir.Repository.DbHelper.CurrentDb.SingleOrDefault<Users>(userId);
                if (model != null && model.Password == oldPassword)
                {
                    model.Password = newPassword;
                    Whir.Repository.DbHelper.CurrentDb.Update(model);
                    //重新登录一次
                    //LoginService ls = new LoginService();
                    //ls.Login(Model.LoginName, txtNewPassWord.Text.Trim(), "");

                    Whir.Service.ServiceFactory.OperateLogService.Save(string.Format("【{0}】管理员修改登录密码成功", model.LoginName));

                    return new HandlerResult { Status = true, Message = "修改密码成功".ToLang() };
                }
                return new HandlerResult { Status = false, Message = "旧密码输入错误".ToLang() };
            }
            return new HandlerResult { Status = false, Message = "请输入新密码".ToLang() };
        }
        return new HandlerResult { Status = false, Message = "找不到记录".ToLang() };
    }



    public void GetList()
    {
        int pageSize = Whir.ezEIP.BasePage.RequestInt32("limit", 10);
        int pageIndex = Whir.ezEIP.BasePage.RequestInt32("offset", 10) / pageSize + 1;
        int currentRolesId = Whir.ezEIP.BasePage.RequestInt32("rolesid", 0);
        string RolesIds = string.Empty;

        #region 取得当前角色所有下级角色Id串
        if (currentRolesId != 0)
        {
            RolesIds = "," + currentRolesId;
        }
        else if (!SysManagePageBase.IsDevUser)
        {
            var roles = Whir.Security.ServiceFactory.RolesService.GetList(SysManagePageBase.CurrentUserRolesId);
            foreach (Roles role in roles)
            {
                RolesIds += role.RoleId + ",";
            }
            //如果当前角色有下级角色，则显示当前角色下的管理员
            if (RolesIds != "")
            {
                RolesIds = "," + SysManagePageBase.CurrentUserRolesId + "," + RolesIds.TrimEnd(',');
            }
            else
            {
                RolesIds = "," + SysManagePageBase.CurrentUserRolesId.ToStr();//如果当前角色无下级角色，则显示当前角色管理员
            }
        }
        else
        {
            //开发者账户按角色查看管理员
            var roleId = RequestUtil.Instance.GetQueryString("rolesid").ToInt();
            RolesIds = roleId > 0 ? roleId.ToStr() : string.Empty;
        }

        #endregion

        string sql = @"SELECT SU.*,SR.RoleName RolesName
                            FROM   Whir_Sec_Users SU
                                   INNER JOIN Whir_Sec_Roles SR ON  SU.RolesId = SR.RoleId
                            WHERE  SU.IsDel = 0 ";
        if (!SysManagePageBase.IsDevUser)
        {
            if (!string.IsNullOrEmpty(RolesIds))
            {
                sql += " AND SU.RolesId IN (@0)";
            }
        }
        else
        {
            if (!string.IsNullOrEmpty(RolesIds))
            {
                sql += " AND SU.RolesId =@0";
            }
        }
        sql += " ORDER BY SU.Sort desc, SU.CreateDate DESC ";
        var list = Whir.Security.ServiceFactory.UsersService.Page(pageIndex, pageSize, sql, RolesIds.ToInts(','));

        long total = list.TotalItems;

        string data = list.Items.ToJson();
        string json = string.Format("{{\"total\":{0},\"rows\":{1}}}", total, data);
        Response.Clear();
        Response.Write(json);
    }
}