using System;
using System.Collections.Generic;
using System.IRepositories;
using System.Linq;
using System.Model;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Common;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using TVShoppingCallCenter_ZLJ.Models.Inputs;

namespace TVShoppingCallCenter_ZLJ.Controllers.System
{
    [Authorize]
    [Produces("application/json")]
    [Route("api/[controller]")]
    public class RoleInfoController : BaseController
    {
        private readonly ISys_RoleInfoRepository _sys_role_infoRepository;

        public RoleInfoController(ISys_RoleInfoRepository sys_role_infoRepository)
        {
            _sys_role_infoRepository = sys_role_infoRepository;
        }

        /// <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, int pageindex = 1, int pagesize = 20)
        {
            List<IConditionalModel> conModels = new List<IConditionalModel>();
            #region 条件筛选
            conModels.Add(new ConditionalModel() { FieldName = "F_State", ConditionalType = ConditionalType.Equal, FieldValue = ((int)EnumDelState.Enabled).ToString() });

            if (!string.IsNullOrEmpty(keyword))
            {
                conModels.Add(new ConditionalModel() { FieldName = "F_RoleCode", ConditionalType = ConditionalType.Like, FieldValue = keyword });
            }
            #endregion
            int recordCount = 0;
            var list = await _sys_role_infoRepository.GetListByPage(conModels, new MyPageModel() { PageIndex = pageindex, PageSize = pagesize, PageCount = recordCount }, "F_CreateOn desc");
            return Success("获取数据成功", list);
        }

        /// <summary>
        /// 获取角色下拉列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("getlistdrop")]
        public async Task<IActionResult> GetListDropAsync()
        {
            var list = await _sys_role_infoRepository.GetListALL(x => x.F_State == (int)EnumDelState.Enabled, o => o.F_CreateOn, OrderByType.Desc);
            var result = list.Select(x => new {
                x.F_RoleCode,
                x.F_RoleName,
                x.F_RoleId
            });
            return Success("获取全部数据成功", result);
        }

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

            var model = await _sys_role_infoRepository.GetSingle(x => x.F_RoleId == id && x.F_State == (int)EnumDelState.Enabled);
            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("请输入角色代码");

            if(input.role_name.Length>15)
                return Error("角色名称长度不能超过15");
            if (input.role_Code.Length > 15)
                return Error("角色代码长度不能超过15");
            var model = new T_Sys_RoleInfo();
            model.F_RoleName = input.role_name;
            model.F_Remark = input.role_remark;
            model.F_RoleCode = input.role_Code;
            model.F_State = input.state;
            model.F_CreateBy = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;
            model.F_CreateOn = DateTime.Now;
            
            if (await _sys_role_infoRepository.GetCount(x => x.F_RoleCode == input.role_Code && x.F_State != 2) > 0)
            {
                return Error("添加失败，存在相同的角色代码");
            }
            var res = await _sys_role_infoRepository.Add(model);
            if (res>0)
            {
                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(x => x.F_RoleId == input.role_id && x.F_State == (int)EnumDelState.Enabled);
            if (model == null)
                return Error("操作失败");
            model.F_RoleName = input.role_name;
            model.F_Remark = input.role_remark;
            model.F_RoleCode = input.role_Code;
            model.F_LastModifyOn = DateTime.Now.ToLocalTime();
            model.F_LastModifyBy = User.Claims.FirstOrDefault(c => c.Type == ClaimTypes.Sid).Value;

            if (await _sys_role_infoRepository.GetCount(x => x.F_RoleCode == input.role_Code && x.F_RoleId !=input.role_id && x.F_State != 2) > 0)
            {
                return Error("修改失败，存在相同的角色代码");
            }

            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(int[] ids)
        {
            var res = 0;
            if (ids != null && ids.Length > 0)
            {
                foreach (var item in ids)
                {
                    var ml = await _sys_role_infoRepository.GetSingle(x => x.F_RoleId == item);
                    ml.F_State = (int)EnumDelState.Delete;
                    ml.F_DeleteOn = DateTime.Now.ToLocalTime();
                    ml.F_DeleteBy = 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("请选择要删除的记录");
        }
    }
}