using Hotline.Share.Dtos;
using Hotline.Share.Dtos.Article;
using Microsoft.AspNetCore.Mvc;
using Hotline.Repository.SqlSugar.Extensions;
using Mapster;
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;
using Hotline.Snapshot.IRepository;
using Hotline.Application.Snapshot.Contracts;
using Hotline.Share.Dtos.Settings;

namespace Hotline.Api.Controllers.Snapshot;

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

    public SnapshotBulletinController(ISnapshotBulletinRepository bulletinRepository, ISystemDicDataCacheManager systemDicDataCacheManager, ISystemOrganizeRepository organizeRepository, ISnapshotBulletinApplication bulletinApplication, ISafetyTypeRepository safetyTypeRepository)
    {
        _bulletinRepository = bulletinRepository;
        _systemDicDataCacheManager = systemDicDataCacheManager;
        _organizeRepository = organizeRepository;
        _bulletinApplication = bulletinApplication;
        _safetyTypeRepository = safetyTypeRepository;
    }

    #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)
            ?? throw UserFriendlyException.SameMessage("公告不存在");

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

        var outDto = model.Adapt<SnapshotBulletinDetailOutDto>();
        if (outDto.SafetyTypeId.NotNullOrEmpty())
        {
            outDto.SafetyTypeNames = await _safetyTypeRepository.Queryable()
                .Where(m => outDto.SafetyTypeId.Contains(m.Id))
                .Select(m => m.Name)
                .ToListAsync();
        }
        return outDto;
    }

    /// <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)
        => await _bulletinApplication.ExamineBulletinAsync(dto, HttpContext.RequestAborted);

    /// <summary>
    /// 提交公告
    /// </summary>
    /// <param name="id"></param>
    /// <returns></returns>
    [HttpGet("bulletin/commit")]
    public async Task CommitBulletin(string id)
        => await _bulletinApplication.CommitBulletinAsync(id, 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)
        => await _bulletinApplication.AddBulletinAsync(dto, 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 safetyTypes = await _safetyTypeRepository.Queryable()
            .Select(m => new SystemDicDataOutDto { Id = m.Id, DicDataName = m.Name, DicDataValue = m.Id })
            .ToListAsync(HttpContext.RequestAborted);
        var rsp = new
        {
            BulletinType = _systemDicDataCacheManager.SnapshotBulletinType,
            BulletinSource = _systemDicDataCacheManager.SnapshotBulletinSource,
            OrgsOptions = await _organizeRepository.GetOrgJson(),
            SafetyTypes = safetyTypes
        };
        return rsp;
    }
    #endregion
}
