/*
 * 后台管理员
 */

using System;
using System.Web;
using System.Collections.Generic;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using MySystem.Models.Bs;
using Library;
using LitJson;
using Microsoft.AspNetCore.Authorization;
using MySystem.Service.Bs;
using System.Linq;

namespace MySystem.Areas.Api.Controllers.v1
{
    [Area("Api")]
    [Route("Api/v1/[controller]/[action]")]
    public class SysAdminController : BaseController
    {
        public SysAdminController(IHttpContextAccessor accessor) : base(accessor)
        {
        }

        #region 登录
        public JsonResult Login(string value)
        {
            value = PublicFunction.DesDecrypt(value);
            JsonData jsonObj = JsonMapper.ToObject(value);
            string userName = jsonObj["userName"].ToString(); //账号
            string pwd = jsonObj["pwd"].ToString(); //密码
            SysAdmin sys = SysAdminService.Query(userName, function.MD5_32(pwd));
            if (sys.Id == 0)
            {
                return Json(new AppResultJson() { Status = "-1", Info = "账号或密码不正确" });
            }
            int RoleId = int.Parse(function.CheckInt(sys.Role));
            SysAdminRole Role = SysAdminRoleService.Query(RoleId);
            string RightInfo = function.CheckNull(Role.RightInfo);
            Dictionary<string, object> obj = new Dictionary<string, object>(); //返回字段
            obj.Add("rightList", new AdminRightList().GetRight(sys.Role, RightInfo)); //权限列表
            obj.Add("apiToken", PublicFunction.AppToken(sys.AdminName)); //后台所有接口API所需的token
            obj.Add("apiTokenExpiredDate", DateTime.Now.AddDays(10).ToString("yyyy-MM-dd HH:mm:ss"));
            string token = dbconn.Encrypt3DES(sys.Id.ToString() + "-" + function.ConvertDateTimeInt(DateTime.Now));
            RefreshTokens check = RefreshTokensService.Query(sys.Id);
            if (check.UserId == 0)
            {
                Dictionary<string, object> Fields = new Dictionary<string, object>();
                Fields.Add("UserId", sys.Id);
                Fields.Add("ExpiredDate", DateTime.Now.AddDays(10));
                Fields.Add("RefreshToken", token);
                RefreshTokensService.Add(Fields);
            }
            else
            {
                Dictionary<string, object> Fields = new Dictionary<string, object>();
                Fields.Add("ExpiredDate", DateTime.Now.AddDays(10));
                Fields.Add("RefreshToken", token);
                RefreshTokensService.Edit(Fields, sys.Id);
            }
            List<string> roles = new List<string>();
            roles.Add(sys.Role);
            obj.Add("roles", roles);
            obj.Add("realName", sys.RealName);
            obj.Add("refreshToken", token); //主token,用于刷新apiToken
            obj.Add("SysAdminId", sys.Id); //当前登录系统用户Id
            AppConfig.LoginSession.sysId = sys.Id;
            AppConfig.LoginSession.sysAdminName = sys.AdminName;
            AppConfig.LoginSession.sysRealName = sys.RealName;
            return Json(new AppResultJson() { Status = "1", Info = "", Data = obj });
        }

        #endregion

        #region 刷新token

        public JsonResult RefreshToken(string value)
        {
            value = PublicFunction.DesDecrypt(value);
            JsonData jsonObj = JsonMapper.ToObject(value);
            string refreshToken = jsonObj["refreshToken"].ToString(); //账号        
            Dictionary<string, object> obj = new Dictionary<string, object>(); //返回字段
            string[] data = dbconn.Decrypt3DES(refreshToken).Split('-');
            int Id = int.Parse(data[0]);
            SysAdmin sys = SysAdminService.Query(Id);
            if (sys.Id == 0)
            {
                return Json(new AppResultJson() { Status = "-1", Info = "刷新失败" });
            }
            obj.Add("apiToken", PublicFunction.AppToken(sys.AdminName)); //后台所有接口API所需的token
            obj.Add("apiTokenExpiredDate", DateTime.Now.AddDays(10));
            string token = dbconn.Encrypt3DES(sys.Id.ToString() + "-" + function.ConvertDateTimeInt(DateTime.Now));
            RefreshTokens check = RefreshTokensService.Query(sys.Id);
            if (check.UserId == 0)
            {
                Dictionary<string, object> Fields = new Dictionary<string, object>();
                Fields.Add("UserId", sys.Id);
                Fields.Add("ExpiredDate", DateTime.Now.AddDays(10));
                Fields.Add("RefreshToken", token);
                RefreshTokensService.Add(Fields);
            }
            else
            {
                Dictionary<string, object> Fields = new Dictionary<string, object>();
                Fields.Add("ExpiredDate", DateTime.Now.AddDays(10));
                Fields.Add("RefreshToken", token);
                RefreshTokensService.Edit(Fields, sys.Id);
            }
            obj.Add("refreshToken", token); //主token,用于刷新apiToken
            return Json(new AppResultJson() { Status = "1", Info = "", Data = obj });
        }

        #endregion


        #region 修改当前操作人密码
        [Authorize]
        [Route("/v1/qrcodeplatemain/sysadmin/changeloginpassword")]
        public JsonResult ChangeLoginPassword(string value)
        {
            value = PublicFunction.DesDecrypt(value);
            JsonData jsonObj = JsonMapper.ToObject(value);
            int SysAdminId = int.Parse(jsonObj["SysAdminId"].ToString()); //系统用户Id
            string OldPassword = jsonObj["OldPassword"].ToString(); //旧密码
            string NewPassword = jsonObj["NewPassword"].ToString(); //新密码
            string NewPassword2 = jsonObj["NewPassword2"].ToString(); //确认新密码
            if (string.IsNullOrEmpty(OldPassword))
            {
                return Json(new AppResultJson() { Status = "-1", Info = "旧密码不能为空" });
            }
            if (string.IsNullOrEmpty(NewPassword))
            {
                return Json(new AppResultJson() { Status = "-1", Info = "新密码不能为空" });
            }
            if (string.IsNullOrEmpty(NewPassword2))
            {
                return Json(new AppResultJson() { Status = "-1", Info = "确认新密码不能为空" });
            }
            if (NewPassword != NewPassword2)
            {
                return Json(new AppResultJson() { Status = "-1", Info = "新密码和确认新密码不一致" });
            }
            var sysAdmin = bsdb.SysAdmin.FirstOrDefault(m => m.Id == SysAdminId && m.Password == function.MD5_32(OldPassword)) ?? new SysAdmin();
            if (sysAdmin.Id > 0)
            {
                if (NewPassword == NewPassword2)
                {
                    sysAdmin.Password = function.MD5_32(NewPassword);
                }
            }
            else
            {
                return Json(new AppResultJson() { Status = "-1", Info = "未找到该用户信息，请检查用户Id和旧密码是否一致" });
            }
            bsdb.SaveChanges();
            return Json(new AppResultJson() { Status = "1", Info = "成功" });
        }
        #endregion


        #region 权限树
        public JsonResult AuthsTree(string value)
        {
            value = PublicFunction.DesDecrypt(value);
            JsonData jsonObj = JsonMapper.ToObject(value);
            Dictionary<string, object> obj = new Dictionary<string, object>(); //返回字段
            var anths = BaseClass.GetRightJson();
            obj.Add("AuthsTree", anths); //主token,用于刷新apiToken
            return Json(new AppResultJson() { Status = "1", Info = "", Data = obj });
        }

        #endregion


        #region 系统管理-系统用户管理-系统用户信息列表
        [Authorize]
        [Route("/v1/qrcodeplatemain/sysadmin/sysadminlist")]
        public JsonResult SysAdminList(string value)
        {
            value = PublicFunction.DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            Dictionary<string, object> Other = new Dictionary<string, object>();
            List<Dictionary<string, object>> dataList = SysAdminListDo(value, out Other);
            return Json(new AppResultJson() { Status = "1", Info = "", Data = dataList, Other = Other });
        }
        private List<Dictionary<string, object>> SysAdminListDo(string value, out Dictionary<string, object> Other)
        {
            JsonData data = JsonMapper.ToObject(value);
            string AdminName = data["AdminName"].ToString(); //角色名称
            string RealName = data["RealName"].ToString(); //名称
            string RoleId = data["RoleId"].ToString(); //角色Id
            string LastLoginDate = data["LastLoginDate"].ToString(); //最后登录时间
            int pageSize = int.Parse(function.CheckInt(data["page_size"].ToString()));
            int pageNum = int.Parse(function.CheckInt(data["page_num"].ToString()));
            List<RelationData> relationData = new List<RelationData>();
            List<Dictionary<string, object>> dataList = new List<Dictionary<string, object>>();
            string condition = "";
            if (!string.IsNullOrEmpty(data["AdminName"].ToString()))
            {
                condition += " and AdminName like '%" + AdminName + "%'";
            }
            if (!string.IsNullOrEmpty(data["RealName"].ToString()))
            {
                condition += " and RealName like '%" + RealName + "%'";
            }
            if (!string.IsNullOrEmpty(data["RoleId"].ToString()))
            {
                condition += " and Role='" + RoleId + "'";
            }
            if (!string.IsNullOrEmpty(data["LastLoginDate"].ToString()))
            {
                string[] datelist = LastLoginDate.Split(new string[] { " - " }, StringSplitOptions.None);
                string start = datelist[0];
                string end = datelist[1];
                condition += " and LastLoginDate>='" + start + " 00:00:00' and LastLoginDate<='" + end + " 23:59:59'";
            }
            Other = new Dictionary<string, object>();
            int count = 0;
            List<Dictionary<string, object>> source = SysAdminService.List(relationData, condition, out count, pageNum, pageSize);
            foreach (Dictionary<string, object> subdata in source)
            {
                Dictionary<string, object> curData = new Dictionary<string, object>();
                curData.Add("Id", int.Parse(subdata["Id"].ToString())); //Id
                curData.Add("AdminName", subdata["AdminName"].ToString()); //用户名
                curData.Add("RealName", subdata["RealName"].ToString()); //名称
                curData.Add("RoleId", int.Parse(subdata["Role"].ToString())); //角色
                curData.Add("LastLoginDate", subdata["LastLoginDate"].ToString() == "" ? "" : DateTime.Parse(subdata["LastLoginDate"].ToString()).ToString("yyyy-MM-dd HH:mm:ss")); //最后登录时间
                dataList.Add(curData);
            }
            Other.Add("Count", count); //总数
            return dataList;
        }
        #endregion


        #region 系统管理-系统用户管理-添加系统用户信息
        [Authorize]
        [Route("/v1/qrcodeplatemain/sysadmin/addsysadminuserinfo")]
        public JsonResult AddSysAdminUserInfo(string value)
        {
            value = PublicFunction.DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = AddSysAdminUserInfoDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        private AppResultJson AddSysAdminUserInfoDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            string AdminName = data["AdminName"].ToString(); //用户名
            string RealName = data["RealName"].ToString(); //名称
            string PassWord = data["PassWord"].ToString(); //密码
            string RoleId = data["RoleId"].ToString(); //角色
            Dictionary<string, object> fields = new Dictionary<string, object>();
            fields.Add("AdminName", AdminName); //用户名
            fields.Add("RealName", RealName); //名称
            fields.Add("Password", function.MD5_32(PassWord)); //密码
            fields.Add("Role", RoleId); //角色
            var Id = int.Parse(SysAdminService.Add(fields).Data.ToString());
            if (Id > 0)
            {
                return new AppResultJson() { Status = "1", Info = "成功", Data = Id };
            }
            else
            {
                return new AppResultJson() { Status = "-1", Info = "失败", Data = Id };
            }
        }
        #endregion


        #region 系统管理-系统用户管理-编辑系统用户信息
        [Authorize]
        [Route("/v1/qrcodeplatemain/sysadmin/editsysadminuserinfo")]
        public JsonResult EditSysAdminUserInfo(string value)
        {
            value = PublicFunction.DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = EditSysAdminUserInfoDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        private AppResultJson EditSysAdminUserInfoDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            int SysAdminId = int.Parse(data["SysAdminId"].ToString()); //系统用户Id
            string AdminName = data["AdminName"].ToString(); //用户名
            string RealName = data["RealName"].ToString(); //名称
            string PassWord = data["PassWord"].ToString(); //密码
            string RoleId = data["RoleId"].ToString(); //角色
            var sysAdmin = bsdb.SysAdmin.FirstOrDefault(m => m.Id == SysAdminId) ?? new SysAdmin();
            if (sysAdmin.Id > 0)
            {
                if (!string.IsNullOrEmpty(AdminName))
                {
                    sysAdmin.AdminName = AdminName;
                }
                if (!string.IsNullOrEmpty(RealName))
                {
                    sysAdmin.RealName = RealName;
                }
                if (!string.IsNullOrEmpty(PassWord))
                {
                    sysAdmin.Password = function.MD5_32(PassWord);
                }
                if (!string.IsNullOrEmpty(data["RoleId"].ToString()) && RoleId != sysAdmin.Role)
                {
                    sysAdmin.Role = RoleId;
                }
            }
            bsdb.SaveChanges();
            return new AppResultJson() { Status = "1", Info = "成功" };
        }
        #endregion


        #region 系统管理-系统用户管理-删除系统用户信息
        [Authorize]
        [Route("/v1/qrcodeplatemain/sysadmin/deletesysadminuserinfo")]
        public JsonResult DeleteSysAdminUserInfo(string value)
        {
            value = PublicFunction.DesDecrypt(value);
            JsonData data = JsonMapper.ToObject(value);
            AppResultJson result = DeleteSysAdminUserInfoDo(value);
            return Json(new AppResultJson() { Status = result.Status, Info = result.Info, Data = result.Data });
        }
        private AppResultJson DeleteSysAdminUserInfoDo(string value)
        {
            JsonData data = JsonMapper.ToObject(value);
            int SysAdminId = int.Parse(data["SysAdminId"].ToString()); //系统用户Id
            SysAdminService.Delete(SysAdminId);
            return new AppResultJson() { Status = "1", Info = "成功" };
        }
        #endregion

    }
}