using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Authorization;
using Api.SignToken;
using MadRunFabric.Common;
using System.Threading;
using System.Security.Claims;
using ConfigurationApi.IRepositories;
using MongoDB.Driver;
using MadRunFabric.Model;
using ConfigurationApi.Model.Input;

// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace ConfigurationApi.Controllers
{
    [Authorize]
    [Route("api/[controller]")]
    public class RoleInfoController : BaseController
    {

        private readonly ILogger<RoleInfoController> _logger;
        private readonly ISys_Role_InfoRepository _sys_role_infoRepository;
        private readonly ISys_User_AccountRepository _sys_user_accountRepository;

        public RoleInfoController(
            ISys_Role_InfoRepository sys_role_infoRepository,
            ISys_User_AccountRepository sys_user_accountRepository,
            ILogger<RoleInfoController> logger)
        {
            _sys_role_infoRepository = sys_role_infoRepository;
            _sys_user_accountRepository = sys_user_accountRepository;
            _logger = logger;
        }

        /// <summary>
        /// 获取角色下拉列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("getlistdrop")]
        public async Task<IActionResult> GetListDropAsync()
        {
            var list = (await _sys_role_infoRepository.Get(x => x.state_flag == 1)).OrderBy(x => x.sort);
            return Success("获取全部数据成功", list);
        }

        /// <summary>
        /// 获取角色分页
        /// </summary>
        /// <param name="keyword"></param>
        /// <param name="pageindex"></param>
        /// <param name="pagesize"></param>
        /// <returns></returns>
        [HttpGet("getlistbypage")]
        public async Task<IActionResult> GetListsByPageAsync(string keyword,string stime,string etime, int pageindex = 1, int pagesize = 10)
        {
            #region 条件信息
            ////排序字段
            var sort = Builders<Sys_Role_Info>.Sort.Descending("sort").Descending("create_time");
            var list = await _sys_role_infoRepository.GetByPage(null, pageindex, pagesize, sort);
            var redCount = await _sys_role_infoRepository.CountAsync(null); //获取总数
            //根据条件查询集合
            var listApp = new List<FilterDefinition<Sys_Role_Info>>();
            listApp.Add(Builders<Sys_Role_Info>.Filter.Eq("state_flag", 1));
           
            //模糊查询
            if (!string.IsNullOrEmpty(keyword))
                listApp.Add(Builders<Sys_Role_Info>.Filter.Where(s => s.role_code.Contains(keyword) || s.role_name.Contains(keyword)));
            if (!string.IsNullOrWhiteSpace(stime))
            {
                listApp.Add(Builders<Sys_Role_Info>.Filter.Where(s => s.create_time.CompareTo(DateTime.Parse(stime + " 00:00:00")) >= 0 ));
            }
            if (!string.IsNullOrWhiteSpace(etime))
            {
                listApp.Add(Builders<Sys_Role_Info>.Filter.Where(s => s.create_time.CompareTo(DateTime.Parse(etime + " 23:59:59")) <= 0 ));
            }
            #endregion
            int recordCount = 0;
            if (listApp.Count > 0)
            {
                var filter = Builders<Sys_Role_Info>.Filter.And(listApp);
                list = await _sys_role_infoRepository.GetByPage(filter, pageindex, pagesize, sort);
                redCount = await _sys_role_infoRepository.CountAsync(filter);   //获取总数
            }
            recordCount = int.Parse(redCount.ToString());

            var obj = new
            {
                state = "success",
                message = "成功",
                rows = list,
                total = recordCount,
            };
            return Content(obj.ToJson());
        }

        /// <summary>
        /// 获取角色
        /// </summary>
        /// <param name="id">角色id</param>
        /// <returns></returns>
        [HttpGet("getdetailes")]
        public async Task<IActionResult> GetDetailsAsync(string id)
        {
            if (string.IsNullOrEmpty(id))
                return Error("参数错误");

            var model = await _sys_role_infoRepository.GetSingle(id);
            if (model == null)
            {
                return Error("获取失败");
            }
            return Success("获取成功！", model);
        }

        /// <summary>
        /// 添加角色
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost("add")]
        public async Task<IActionResult> AddAsync(RoleInfoInput input)
        {
            if (string.IsNullOrEmpty(input.role_name))
                return Error("请输入角色名称");
            if (string.IsNullOrEmpty(input.role_Code))
                return Error("请输入角色代码");

            var model = new Sys_Role_Info();
            model.role_name = input.role_name;
            model.role_remark = input.role_remark;
            model.role_code = input.role_Code;
            model.project_num = input.project_num;
            model.sort = input.sort;
            model.create_uid= User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            if (await _sys_role_infoRepository.Count(x => x.role_code == input.role_Code&&x.state_flag !=2) > 0)//2019-5-27添加删除判断
            {
                return Error("添加失败，存在相同的角色代码");
            }
            if (await _sys_role_infoRepository.Count(x => x.role_name == input.role_name) >0)//2019-5-27添加删除判断
            {
                return Error("添加失败，存在相同的角色名称");
            }

            if (await _sys_role_infoRepository.Add(model))
            {
               return Success("添加成功");
            }
            else
            {
               return Error("添加失败");
            }
        }

        /// <summary>
        /// 修改角色信息
        /// </summary>
        [HttpPost("update")]
        public async Task<IActionResult> UpdateAsync(RoleInfoInput input)
        {
            if (string.IsNullOrEmpty(input.role_name))
                return Error("请输入角色名称");
            if (string.IsNullOrEmpty(input.role_Code))
                return Error("请输入角色代码");

            var model = await _sys_role_infoRepository.GetSingle(input.role_id);
         
            if (model == null)
                return Error("操作失败");

            if (await _sys_role_infoRepository.Count(x => x.role_name == input.role_name && x.id != input.role_id) > 0)
            {
                return Error("修改失败，存在相同的角色名称");
            }


            model.role_name = input.role_name;
            model.role_code = input.role_Code;
            model.role_remark = input.role_remark;
            model.project_num = input.project_num;
            model.sort = input.sort;
            model.lastmodify_time = DateTime.Now.ToLocalTime();
            model.lastmodify_uid = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            bool b = await _sys_role_infoRepository.Update(model);
            if (b)
                return Success("修改成功");
            return Error("修改失败");
        }

        /// <summary>
        /// 删除角色信息 by ids
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpPost("delete")]
        public async Task<IActionResult> Remove(string[] ids)
        {
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                foreach (var item in ids)
                {
                    var ml = await _sys_role_infoRepository.GetSingle(item);
                    ml.state_flag = 2;
                    ml.delete_time = DateTime.Now.ToLocalTime();
                    ml.delete_uid = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
                    if (_sys_role_infoRepository.Update(ml).Result)
                        res += 1;
                }
                if (res == ids.Length)
                    return Success("删除成功");
                else if (res > 0 && res < ids.Length)
                    return Error("部分删除失败，请查看后重新操作");
                else
                    return Error("删除失败，请查看后重新操作");
            }
            else
                return Error("请选择要删除的记录");
        }

        #region 获取角色和人员 - 二级
        /// <summary>
        /// 获取角色和人员列表 - 二级
        /// </summary>
        [HttpGet("getroleuserlist")]
        public async Task<IActionResult> GetTreeListAsync()
        {
            var listRole = (await _sys_role_infoRepository.Get(p => p.state_flag == 1)).ToList();
            var listUser = (await _sys_user_accountRepository.Get(p => p.delete_flag == false)).ToList();
            var list1 = listRole.Select(p => new
            {
                id = p.id,
                type = "role",
                code = p.role_code,
                name = p.role_name
            });
            var list2 = listUser.Select(p => new
            {
                id = p.id,
                type = "user",
                code = p.usercode,
                name = p.username
            });

            var list = list1.Union(list2);
            return Success("获取成功", list);
        }
        #endregion


    }
}
