using Hotline.Share.Dtos;
using Hotline.Share.Dtos.Article;
using Hotline.Snapshot.Interfaces;
using Microsoft.AspNetCore.Mvc;
using Hotline.Repository.SqlSugar.Extensions;
using Mapster;
using Hotline.Application.Snapshot;
using XF.Domain.Exceptions;
using Hotline.Share.Enums.Article;
using XF.Domain.Authentications;
using Hotline.Caching.Interfaces;
using Hotline.Settings;
using Hotline.Article;
using Hotline.Snapshot;
using Hotline.Share.Dtos.Snapshot;
using Hotline.Share.Tools;
using XF.Utility.EnumExtensions;

namespace Hotline.Api.Controllers.Snapshot;

public class SnapshotBulletinController : BaseController
{
    private readonly ISnapshotBulletinRepository _bulletinRepository;
    private readonly ISnapshotBulletinApplication _bulletinApplication;
    private readonly ISessionContext _sessionContext;
    private readonly ISystemDicDataCacheManager _systemDicDataCacheManager;
    private readonly ISystemOrganizeRepository _organizeRepository;

    public SnapshotBulletinController(ISnapshotBulletinRepository bulletinRepository, ISessionContext sessionContext, ISystemDicDataCacheManager systemDicDataCacheManager, ISystemOrganizeRepository organizeRepository, ISnapshotBulletinApplication bulletinApplication)
    {
        _bulletinRepository = bulletinRepository;
        _sessionContext = sessionContext;
        _systemDicDataCacheManager = systemDicDataCacheManager;
        _organizeRepository = organizeRepository;
        _bulletinApplication = bulletinApplication;
    }

    #region 公告

    /// <summary>
    /// 查询公告列表
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    [HttpGet("bulletin/query")]
    public async Task<PagedDto<SnapshotBulletinItemsOutDto>> QueryBulletinItems([FromQuery] SnapshotBulletinItemsInDto dto)
        => (await _bulletinApplication.QueryBulletinItems(dto).ToPagedListAsync(dto)).ToPaged();

    /// <summary>
    /// 公告详情（内部）
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("bulletin/entity/{id}")]
    public async Task<SnapshotBulletinDetailOutDto> BulletinEntity(string id)
    {
        var model = await _bulletinRepository.Queryable()
            .Includes(x => x.ExaminMan)
            .FirstAsync(x => x.Id == id, HttpContext.RequestAborted);

        if (model != null && !string.IsNullOrEmpty(model.Content))
            model.Content = _bulletinApplication.GetSiteUrls(model.Content);

        return model.Adapt<SnapshotBulletinDetailOutDto>();
    }

    /// <summary>
    /// 公告上架或者下架
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    [HttpPost("bulletin-arrive")]
    public async Task BulletinArrive([FromBody] BulletinArriveDto dto)
    {
        var bulletin = await _bulletinRepository.GetAsync(dto.Id, HttpContext.RequestAborted);
        if (bulletin == null)
            throw UserFriendlyException.SameMessage("无效数据");

        if (bulletin.BulletinState != EBulletinState.ReviewPass)
            throw UserFriendlyException.SameMessage("当前状态不能操作上架或下架");

        bulletin.IsArrive = dto.IsArrive;
        if (bulletin.IsArrive == false)
        {
            bulletin.ExaminTime = null;
            bulletin.ExaminManId = null;
            bulletin.ExaminOpinion = null;
            bulletin.CommitTime = null;
            bulletin.BulletinState = EBulletinState.Draft;
        }
        await _bulletinRepository.UpdateAsync(bulletin, HttpContext.RequestAborted);
    }


    /// <summary>
    /// 公告审核
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    [HttpPost("bulletin/examine")]
    public async Task ExamineBulletin([FromBody] ExamineBulletinDto dto)
    {
        var bulletin = await _bulletinRepository.GetAsync(dto.Id, HttpContext.RequestAborted);
        if (bulletin == null)
            throw UserFriendlyException.SameMessage("无效数据");

        if (bulletin.BulletinState != EBulletinState.InReview)
            throw UserFriendlyException.SameMessage("当前状态不能审核");

        if (dto.IsPass)
        {
            bulletin.BulletinState = Share.Enums.Article.EBulletinState.ReviewPass;
            bulletin.BulletinTime = DateTime.Now;
            bulletin.ExaminOpinion = dto.Reason;
            bulletin.ExaminTime = DateTime.Now;
            bulletin.ExaminManId = _sessionContext.RequiredUserId;
            await _bulletinRepository.UpdateAsync(bulletin, HttpContext.RequestAborted);
            var publishBulletin = bulletin.Adapt<PublishBulletinDto>();

            //await _capPublisher.PublishAsync(Hotline.Share.Mq.EventNames.HotlinePushBulletin, publishBulletin, cancellationToken: HttpContext.RequestAborted);

            //todo await _bulletinService.PushBulletin(publishBulletin, HttpContext.RequestAborted);
        }
        else
        {
            bulletin.ExaminOpinion = dto.Reason;
            bulletin.ExaminTime = DateTime.Now;
            bulletin.ExaminManId = _sessionContext.RequiredUserId;
            bulletin.BulletinState = Share.Enums.Article.EBulletinState.ReviewNoPass;
            await _bulletinRepository.UpdateAsync(bulletin, HttpContext.RequestAborted);
        }
    }

    /// <summary>
    /// 提交公告
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("bulletin/commit")]
    public async Task CommitBulletin(string id)
    {
        var bulletin = await _bulletinRepository.GetAsync(id, HttpContext.RequestAborted);
        if (bulletin == null)
            throw UserFriendlyException.SameMessage("无效数据");

        if (bulletin.BulletinState != EBulletinState.Draft && bulletin.BulletinState != EBulletinState.ReviewNoPass)
            throw UserFriendlyException.SameMessage("当前状态不能提交");

        bulletin.BulletinState = EBulletinState.InReview;
        bulletin.CommitTime = DateTime.Now;
        await _bulletinRepository.UpdateAsync(bulletin, HttpContext.RequestAborted);
    }

    /// <summary>
    /// 修改公告
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    [HttpPost("bulletin/update")]
    public async Task UpdateBulletin([FromBody] UpdateSnapshotBulletinInDto dto)
    {
        var bulletin = await _bulletinRepository.GetAsync(dto.Id, HttpContext.RequestAborted);
        if (bulletin == null)
            throw UserFriendlyException.SameMessage("无效数据");

        if (bulletin.BulletinState != EBulletinState.Draft && bulletin.BulletinState != EBulletinState.ReviewNoPass)
            throw UserFriendlyException.SameMessage("当前状态不能修改");

        dto.Adapt(bulletin);
        await _bulletinRepository.UpdateAsync(bulletin, HttpContext.RequestAborted);
    }

    /// <summary>
    /// 删除公告
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("bulletin/del/{id}")]
    public async Task DelBulletin(string id)
    {
        var bulletin = await _bulletinRepository.GetAsync(id, HttpContext.RequestAborted);
        if (bulletin == null)
            throw UserFriendlyException.SameMessage("无效数据");

        if (bulletin.BulletinState != EBulletinState.Draft)
            throw UserFriendlyException.SameMessage("当前状态不能删除");

        await _bulletinRepository.RemoveAsync(x => x.Id == id, false, HttpContext.RequestAborted);
    }

    /// <summary>
    /// 新增公告
    /// </summary>
    /// <param name="dto"></param>
    /// <returns></returns>
    [HttpPost("bulletin/add")]
    public async Task AddBulletin([FromBody] AddSnapshotBulletinInDto dto)
    {
        var model = dto.Adapt<SnapshotBulletin>();
        model.BulletinState = Share.Enums.Article.EBulletinState.Draft;
        model.ReadedNum = 0;
        if (model.BulletinTime.HasValue == false) model.BulletinTime = DateTime.Now;
        await _bulletinRepository.AddAsync(model, HttpContext.RequestAborted);
    }

    /// <summary>
    /// 列表页面基础数据
    /// </summary>
    /// <returns></returns>
    [HttpGet("bulletin/listbasedata")]
    public async Task<object> BulletinListBaseData()
    {
        var rsp = new
        {
            BulletinType = _systemDicDataCacheManager.SnapshotBulletinType,
            BulletinSource = _systemDicDataCacheManager.SnapshotBulletinSource,
            BulletinState = EnumExts.GetDescriptions<EBulletinState>()
        };
        return rsp;
    }

    /// <summary>
    /// 新增页面基础数据
    /// </summary>
    /// <returns></returns>
    [HttpGet("bulletin/addbasedata")]
    public async Task<object> BulletinAddBaseData()
    {
        var rsp = new
        {
            BulletinType = _systemDicDataCacheManager.SnapshotBulletinType,
            BulletinSource = _systemDicDataCacheManager.SnapshotBulletinSource,
            OrgsOptions = await _organizeRepository.GetOrgJson(),
        };
        return rsp;
    }
    #endregion
}
