using Microsoft.AspNetCore.Mvc;
using System;
using System.Linq;
using System.Threading.Tasks;
using Yitter.IdGenerator;
using Znyc.Recruitment.Admin.AspNetCore.Controllers;
using Znyc.Recruitment.Admin.AspNetCore.Entitys;
using Znyc.Recruitment.Admin.AspNetCore.Mvc;
using Znyc.Recruitment.Admin.AspNetCore.ViewModel;
using Znyc.Recruitment.Admin.Commons.Cache;
using Znyc.Recruitment.Admin.Commons.Entitys;
using Znyc.Recruitment.Admin.Commons.Extensions;
using Znyc.Recruitment.Admin.Commons.Log;
using Znyc.Recruitment.Admin.Commons.Mapping;
using Znyc.Recruitment.Admin.Security.Dtos;
using Znyc.Recruitment.Admin.Security.Entitys;
using Znyc.Recruitment.Admin.Security.IServices;

namespace Znyc.Recruitment.Admin.WebApi.Controllers
{
    /// <summary>
    ///     数据字典接口
    /// </summary>
    [ApiController]
    [Route("api/Security/[controller]")]
    public class DictionaryController : AreaApiController<DictionaryEntity, DictionaryOutputDto, DictionaryInputDto,
        IDictionaryService, long>
    {
        //private readonly IDictionaryService _service;

        /// <summary>
        ///     构造函数
        /// </summary>
        /// <param name="service"></param>
        public DictionaryController(IDictionaryService service) :
            base(service)
        {
            _service = service;
        }

        /// <summary>
        ///     新增前处理数据
        /// </summary>
        /// <param name="info"></param>
        protected override void OnBeforeInsert(DictionaryEntity info)
        {
            info.Id = 0;
            info.CreatedTime = DateTime.Now;
            info.CreatedUserId = CurrentUser.UserId;
            info.IsDeleted = false;
        }

        /// <summary>
        ///     在更新数据前对数据的修改操作
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        protected override void OnBeforeUpdate(DictionaryEntity info)
        {
            info.ModifiedUserId = CurrentUser.UserId;
            info.ModifiedTime = DateTime.Now;
        }

        /// <summary>
        ///     在软删除数据前对数据的修改操作
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        protected override void OnBeforeSoftDelete(DictionaryEntity info)
        {
            info.IsDeleted = true;
        }

        /// <summary>
        ///     异步新增数据
        /// </summary>
        /// <param name="tinfo"></param>
        /// <returns></returns>
        [HttpPost("Insert")]
        [FunctionAuthorize("Add")]
        public async Task<IActionResult> InsertAsync(DictionaryInputDto tinfo)
        {
            CommonResult result = new CommonResult();
            CacheHelper cacheHelper = new CacheHelper();
            DictionaryEntity isExsit = await _service.GetByEnCodAsynce(tinfo.Code);
            if (isExsit != null && tinfo.ParentId == 0)
            {
                result.ErrMsg = "字典分类编码不能重复";
                return ToJsonContent(result);
            }

            DictionaryEntity info = tinfo.MapTo<DictionaryEntity>();
            OnBeforeInsert(info);
            info.Id = YitIdHelper.NextId();
            int ln = await _service.InsertAsync(info).ConfigureAwait(false);
            if (ln > 0)
            {
                cacheHelper.Remove("dictionary:list");
                result.ErrCode = ErrCode.successCode;
                result.ErrMsg = ErrCode.err0;
            }
            else
            {
                result.ErrMsg = ErrCode.err43001;
                result.ErrCode = "43001";
            }

            return ToJsonContent(result);
        }

        /// <summary>
        ///     异步更新数据
        /// </summary>
        /// <param name="tinfo"></param>
        /// <returns></returns>
        [HttpPost("Update")]
        [FunctionAuthorize("Edit")]
        public async Task<IActionResult> UpdateAsync(DictionaryInputDto tinfo)
        {
            CommonResult result = new CommonResult();
            CacheHelper cacheHelper = new CacheHelper();
            DictionaryEntity isExsit = await _service.GetByEnCodAsynce(tinfo.Code, tinfo.Id);
            if (isExsit != null && tinfo.ParentId == 0)
            {
                result.ErrMsg = "字典分类编码不能重复";
                return ToJsonContent(result);
            }

            DictionaryEntity info = _service.Get(tinfo.Id);
            info.ParentId = tinfo.ParentId;
            info.Value = tinfo.Value;
            info.Description = tinfo.Description;
            info.Name = tinfo.Name;
            info.IsEnabled = tinfo.IsEnabled;
            info.Sort = tinfo.Sort;
            info.Description = tinfo.Description;
            OnBeforeUpdate(info);
            bool bl = await _service.UpdateAsync(info, tinfo.Id).ConfigureAwait(false);
            if (bl)
            {
                cacheHelper.Remove("dictionary:list");
                result.ErrCode = ErrCode.successCode;
                result.ErrMsg = ErrCode.err0;
            }
            else
            {
                result.ErrMsg = ErrCode.err43002;
                result.ErrCode = "43002";
            }

            return ToJsonContent(result);
        }

        /// <summary>
        /// 获取功能菜单适用于Vue 树形列表
        /// </summary>
        /// <returns></returns>
        [HttpGet("GetAllDictionaryTreeTable")]
        [FunctionAuthorize("List")]
        public async Task<IActionResult> GetAllDictionaryTreeTable()
        {
            CommonResult result = new CommonResult();
            try
            {
                System.Collections.Generic.List<DictionaryOutputDto> list = await _service.GetAllDictionaryTreeTable();
                result.Success = true;
                result.ErrCode = ErrCode.successCode;
                result.ResData = list;
            }
            catch (Exception ex)
            {
                Log4NetHelper.Error("获取菜单异常", ex);
                result.ErrMsg = ErrCode.err40110;
                result.ErrCode = "40110";
            }

            return ToJsonContent(result);
        }

        /// <summary>
        ///     查询单条数据字典
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("GetDictionaryById")]
        [FunctionAuthorize("")]
        public async Task<IActionResult> GetDictionaryById(long id)
        {
            CommonResult result = new CommonResult
            {
                ResData = await _service.GetDictionaryById(id),
                ErrCode = ErrCode.successCode,
                ErrMsg = ErrCode.err0
            };
            return ToJsonContent(result);
        }

        /// <summary>
        ///     异步批量禁用数据
        /// </summary>
        /// <param name="info"></param>
        [HttpPost("SetEnabledMarktBatchAsync")]
        [FunctionAuthorize("")]
        public async Task<IActionResult> SetEnabledMarktBatchAsync(UpdateEnableViewModel info)
        {
            CommonResult result = new CommonResult();
            CacheHelper cacheHelper = new CacheHelper();
            string where = string.Empty;
            if (typeof(int) == typeof(string))
            {
                @where = "id in ('" + info.Ids.Join(",").Trim(',').Replace(",", "','") + "')";
            }
            else if (typeof(int) == typeof(int))
            {
                @where = "id in (" + info.Ids.Join(",") + ")";
            }

            if (!string.IsNullOrEmpty(where))
            {
                bool bl = false;
                if (info.Flag == "1")
                {
                    bl = true;
                }

                bool blResult = await _service.SetEnabledMarkByWhereAsync(bl, where, CurrentUser.UserId);
                if (blResult)
                {
                    cacheHelper.Remove("dictionary:list");
                    result.ErrCode = ErrCode.successCode;
                    result.ErrMsg = ErrCode.err0;
                }
                else
                {
                    result.ErrMsg = ErrCode.err43002;
                    result.ErrCode = "43002";
                }
            }

            return ToJsonContent(result);
        }

        /// <summary>
        ///     异步软删除信息
        /// </summary>
        /// <param name="id">主键Id</param>
        /// <param name="bltag">删除标识,默认为1:即设为删除,0:未删除</param>
        [HttpDelete("DeleteSoftAsync")]
        [FunctionAuthorize("DeleteSoft")]
        public async Task<IActionResult> DeleteSoftAsync(long id, string bltag = "1")
        {
            CommonResult result = new CommonResult();
            System.Collections.Generic.IEnumerable<DictionaryEntity> dictionaryList = await _service.GetListWhereAsync($" ParentId={id} and IsDeleted=0 and IsEnabled=1");
            if (dictionaryList != null && dictionaryList.Count() > 0)
            {
                result.ErrMsg = "字典存在启用下级,不能删除";
                return ToJsonContent(result);
            }

            CacheHelper cacheHelper = new CacheHelper();
            bool bl = false;
            if (bltag == "0")
            {
                bl = true;
            }

            bool blResult = await _service.DeleteSoftAsync(bl, id, CurrentUser.UserId);
            if (blResult)
            {
                cacheHelper.Remove("dictionary:list");
                result.ErrCode = ErrCode.successCode;
                result.ErrMsg = ErrCode.err0;
            }
            else
            {
                result.ErrMsg = ErrCode.err43002;
                result.ErrCode = "43002";
            }
            return ToJsonContent(result);
        }

        /// <summary>
        ///     异步批量软删除信息
        /// </summary>
        /// <param name="info"></param>
        /// <returns></returns>
        [HttpDelete("DeleteSoftBatchAsync")]
        [FunctionAuthorize("DeleteSoft")]
        public async Task<IActionResult> DeleteSoftBatchAsync(UpdateEnableViewModel info)
        {
            CommonResult result = new CommonResult();
            CacheHelper cacheHelper = new CacheHelper();
            string where = string.Empty;
            string key = string.Empty;
            if (typeof(int) == typeof(string))
            {
                @where = "id in ('" + info.Ids.Join(",").Trim(',').Replace(",", "','") + "')";
                @key = " ParentId in ('" + info.Ids.Join(",").Trim(',').Replace(",", "','") + "') and IsDeleted=0 and IsEnabled=1";
            }
            else if (typeof(int) == typeof(int))
            {
                @where = "id in (" + info.Ids.Join(",") + ")";
                @key = " ParentId in (" + info.Ids.Join(",") + ") and IsDeleted=0 and IsEnabled=1";
            }
            if (!string.IsNullOrEmpty(key))
            {
                System.Collections.Generic.IEnumerable<DictionaryEntity> dictionaryList = await _service.GetListWhereAsync(key);
                if (dictionaryList != null && dictionaryList.Count() > 0)
                {
                    result.ErrMsg = "字典存在启用下级,不能删除";
                    return ToJsonContent(result);
                }
            }
            if (!string.IsNullOrEmpty(where))
            {
                bool bl = false;
                if (info.Flag == "0")
                {
                    bl = true;
                }

                bool blResult = await _service.DeleteSoftBatchAsync(bl, where, CurrentUser.UserId);
                if (blResult)
                {
                    cacheHelper.Remove("dictionary:list");
                    result.ErrCode = ErrCode.successCode;
                    result.ErrMsg = ErrCode.err0;
                }
                else
                {
                    result.ErrMsg = ErrCode.err43002;
                    result.ErrCode = "43002";
                }
            }
            return ToJsonContent(result);
        }

        /// <summary>
        ///    根据ParentId查询数据字典列表
        /// </summary>
        /// <param name="pid"></param>
        /// <returns></returns>
        [HttpGet("GetListByPidAsync")]
        [FunctionAuthorize("")]
        public async Task<IActionResult> GetListByPidAsync(long pid)
        {
            var result = new CommonResult
            {
                ResData = await _service.GetListByPidAsync(pid),
                ErrCode = ErrCode.successCode,
                ErrMsg = ErrCode.err0
            };
            return ToJsonContent(result);
        }
    }
}