using Hotline.KnowledgeBase;
using Hotline.Permissions;
using Hotline.Share.Dtos.Knowledge;
using MapsterMapper;
using Microsoft.AspNetCore.Mvc;
using XF.Domain.Authentications;
using XF.Domain.Exceptions;
using XF.Domain.Repository;

namespace Hotline.Api.Controllers
{
    /// <summary>
    /// 
    /// </summary>
    public class KnowledgeCommonController : BaseController
    {

        #region 注入
        private readonly IRepository<KnowledgeType> _knowledgeTypeRepository;
        private readonly IKnowledgeTypeDomainService _knowledgeTypeDomainService;
        private readonly IRepository<KnowledgeStandard> _knowledgeStandardRepository;
        private readonly IMapper _mapper;
        private readonly ISessionContext _sessionContext;

		/// <summary>
		/// 
		/// </summary>
		/// <param name="knowledgeTypeRepository"></param>
		/// <param name="knowledgeTypeDomainService"></param>
		/// <param name="knowledgeStandardRepository"></param>
		/// <param name="mapper"></param>
		public KnowledgeCommonController(IRepository<KnowledgeType> knowledgeTypeRepository, IKnowledgeTypeDomainService knowledgeTypeDomainService,
            IRepository<KnowledgeStandard> knowledgeStandardRepository, ISessionContext sessionContext,
			IMapper mapper)
        {
            _knowledgeTypeRepository = knowledgeTypeRepository;
            _knowledgeTypeDomainService = knowledgeTypeDomainService;
            _knowledgeStandardRepository = knowledgeStandardRepository;
            _mapper = mapper;
            _sessionContext = sessionContext;

		}
        #endregion

        #region 知识分类

        /// <summary>
        ///知识分类- 新增
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [Permission(EPermission.AddKnowledgeType)]
        [HttpPost("add")]
        public async Task<string> AddType([FromBody] AddKnowledgeTypeDto dto)
        {
            return await _knowledgeTypeDomainService.AddType(dto, HttpContext.RequestAborted);
        }

        /// <summary>
        ///知识分类- 编辑
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [Permission(EPermission.UpdateKnowledgeType)]
        [HttpPut("update")]
        public async Task UpdateType([FromBody] UpdateKnowledgeTypeDto dto)
        {
            await _knowledgeTypeDomainService.UpdateType(dto, HttpContext.RequestAborted);
        }

        /// <summary>
        /// 知识分类-新增、编辑初始化
        /// </summary>
        /// <param name="Id"></param>
        /// <param name="ParentId"></param>
        /// <returns></returns>
        [HttpGet("init")]
        public async Task<KnowledgeTypeDto> InitType(string Id, string ParentId)
        {
            return await _knowledgeTypeDomainService.InitType(Id, ParentId, HttpContext.RequestAborted);
        }

        /// <summary>
        /// 知识分类-查询详情
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpGet("info/{Id}")]
        public async Task<KnowledgeType> GetType(string Id)
        {
            var types = await _knowledgeTypeRepository.Queryable()
                .Includes(x=>x.KnowledgeTypeOrgs)
                .Where(x=>x.Id  == Id)
                .FirstAsync(HttpContext.RequestAborted);
            if (types is null)
                throw UserFriendlyException.SameMessage("查询失败！");
            return types;
        }

        /// <summary>
        /// 知识分类-删除
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
       [Permission(EPermission.RemoveKnowledgeType)]
        [HttpDelete("remove")]
        public async Task RemoveType(string Id)
        {
            await _knowledgeTypeDomainService.RemoveType(Id, HttpContext.RequestAborted);
        }

        /// <summary>
        /// 知识分类-启用、禁用切换
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpPut("changestate")]
        public async Task ChangeStateType(string Id)
        {
            await _knowledgeTypeDomainService.ChangeStateType(Id, HttpContext.RequestAborted);
        }

        /// <summary>
        /// 知识分类-禁用，并且下架知识
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        [HttpPut("changestateandoffshelf")]
        public async Task TypeChangeStateAndOffShelf(string Id)
        {
            await _knowledgeTypeDomainService.ChangeStateTypeAndOffShelf(Id, HttpContext.RequestAborted);
        }

        /// <summary>
        /// 知识分类- 获取层级分类
        /// </summary>
        /// <param name="IsEnable">不传查询所有</param>
        /// <returns></returns>
        [HttpGet("treelist")]
        public async Task<List<KnowledgeType>> GetTreeList(bool? IsEnable)
        {
            return await _knowledgeTypeRepository.Queryable().WhereIF(IsEnable.HasValue, p => p.IsEnable == IsEnable)
				 .Where(x => x.KnowledgeTypeOrgs.Any(to => to.OrgId == _sessionContext.RequiredOrgId) || x.KnowledgeTypeOrgs.Any() == false).OrderBy(p => p.Sort).ToTreeAsync(it => it.children, it => it.ParentId, null,it=> it.Id);
        }

        /// <summary>
        /// 知识分类- 只获取一级
        /// </summary>
        /// <param name="ParentId">不传默认查询第一级</param>
        /// <param name="IsEnable">不传查询所有，包含已经禁用的</param>
        /// <returns></returns>
        [HttpGet("typelist")]
        public async Task<List<KnowledgeType>> GetTypeList(string? ParentId, bool? IsEnable)
        {
            return await _knowledgeTypeRepository
                .Queryable()
                .Where(p => p.ParentId == ParentId)
                .WhereIF(IsEnable.HasValue, p => p.IsEnable == IsEnable)
                .OrderByDescending(p => p.Sort)
                .ToListAsync();
        }

        #endregion

        #region 编写规范

        /// <summary>
        /// 编写规范-查询详情
        /// </summary>
        /// <returns></returns>
        [Permission(EPermission.KnowledgeStandardInfo)]
        [HttpGet("info-standard")]
        public async Task<KnowledgeStandard> GetStandard()
        {
            var sandard = await _knowledgeStandardRepository.Queryable().FirstAsync();
            if (sandard == null)
            {
                KnowledgeStandard standard = new()
                {
                    Title = "",
                    Content = ""
                };
                var Id = await _knowledgeStandardRepository.AddAsync(standard, HttpContext.RequestAborted);
                return await _knowledgeStandardRepository.GetAsync(Id, HttpContext.RequestAborted);
            }
            return sandard;
        }

        /// <summary>
        /// 编写规范-修改
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [Permission(EPermission.KnowledgeStandardUpdate)]
        [HttpPut("update-standard")]
        public async Task UpdateStandard([FromBody] UpdateKnowledgeStandardDto dto)
        {
            var standard = await _knowledgeStandardRepository.GetAsync(dto.Id);
            _mapper.Map(dto, standard);
            await _knowledgeStandardRepository.UpdateAsync(standard, HttpContext.RequestAborted);
        }
        #endregion

    }
}
