using Hotline.Application.ObservationPiece;
using Hotline.Orders;
using Hotline.Repository.SqlSugar.Extensions;
using Hotline.Share.Dtos;
using Hotline.Share.Dtos.ObservationPiece;
using Hotline.Share.Dtos.Order;
using Hotline.Tools;
using MapsterMapper;
using Microsoft.AspNetCore.Mvc;
using SqlSugar;
using XF.Domain.Authentications;
using XF.Domain.Exceptions;
using XF.Domain.Repository;

namespace Hotline.Api.Controllers
{
    public class ObservationPieceController : BaseController
    {
        private readonly ISessionContext _sessionContext;
        private readonly IMapper _mapper;
        private readonly IRepository<ObservationPiece> _observationPieceRepository;
        private readonly IObservationPieceApplication _observationPieceApplication;

        public ObservationPieceController(
            ISessionContext sessionContext,
            IMapper mapper,
            IRepository<ObservationPiece> observationPieceRepository,
             IObservationPieceApplication observationPieceApplication
            )
        {
            _sessionContext = sessionContext;
            _mapper = mapper;
            _observationPieceRepository = observationPieceRepository;
            _observationPieceApplication = observationPieceApplication;
        }

        /// <summary>
        /// 回复
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpPost("add-observation-piece-reply")]
        public async Task AddObservationPieceReply([FromBody] AddObservationPieceReply dto)
        {
            if (dto.ReplyContent == null)
                throw UserFriendlyException.SameMessage("回复内容不能为空！");

            if (dto.CompletionTime.HasValue == false)
                throw UserFriendlyException.SameMessage("完成时间不能为空！");
            var data = await _observationPieceRepository.GetAsync(p => p.Id == dto.Id, HttpContext.RequestAborted);
            if (data == null)
                throw UserFriendlyException.SameMessage("数据查询失败！");

            data.ReplyContent = dto.ReplyContent;
            data.CompletionTime = dto.CompletionTime;
            data.ReplyTime = DateTime.Now;
            data.IsReply = true;
            data.ReplyUserId = _sessionContext.UserId;
            data.ReplyUserName = _sessionContext.UserName;
            data.ReplyOrgId = _sessionContext.OrgId;
            data.ReplyOrgName = _sessionContext.OrgName;
            await _observationPieceRepository.UpdateAsync(data, HttpContext.RequestAborted);
        }

        /// <summary>
        /// 获取详情
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet("get-observation-piece-detail/{id}")]
        public async Task<ObservationPiece> GetObservationPieceDetail(string id)
        {
            var data = await _observationPieceRepository.GetAsync(p => p.Id == id, HttpContext.RequestAborted);

            return data;
        }


        /// <summary>
        /// 观察件回复
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("get-observation-piece-reply-list")]
        public async Task<PagedDto<ObservationPieceListDto>> GetObservationPieceReplyList([FromQuery] ObservationPieceRequestDto dto)
        {
            var (total, items) = await _observationPieceApplication.GetObservationPieceReplyList(dto)
                .ToPagedListAsync(dto.PageIndex, dto.PageSize, HttpContext.RequestAborted);
            return new PagedDto<ObservationPieceListDto>(total, _mapper.Map<IReadOnlyList<ObservationPieceListDto>>(items));
        }

        /// <summary>
        /// 观察件回复导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>

        [HttpPost("get-observation-piece-reply-list-export")]
        public async Task<FileStreamResult> GetObservationPieceReplyListExport([FromBody] ExportExcelDto<ObservationPieceRequestDto> dto)
        {
            var query = _observationPieceApplication.GetObservationPieceReplyList(dto.QueryDto);
            List<ObservationPieceListDto> data;
            if (dto.IsExportAll)
            {
                data = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                data = items;
            }

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<ObservationPieceListDto>(dto.ColumnInfos);

            var dtos = data
                .Select(stu => _mapper.Map(stu, typeof(ObservationPieceListDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "观察件回复");
        }

        /// <summary>
        /// 观察件列表
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        [HttpGet("get-observation-piece-list")]
        public async Task<PagedDto<ObservationPieceListDto>> GetObservationPieceList([FromQuery] ObservationPieceRequestDto dto)
        {
            var (total, items) = await _observationPieceApplication.GetObservationPieceList(dto)
                .ToPagedListAsync(dto.PageIndex, dto.PageSize, HttpContext.RequestAborted);
            return new PagedDto<ObservationPieceListDto>(total, _mapper.Map<IReadOnlyList<ObservationPieceListDto>>(items));
        }

        /// <summary>
        /// 观察件列表导出
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>

        [HttpPost("get-observation-piece-list-export")]
        public async Task<FileStreamResult> GetObservationPieceListExport([FromBody] ExportExcelDto<ObservationPieceRequestDto> dto)
        {
            var query = _observationPieceApplication.GetObservationPieceList(dto.QueryDto);
            List<ObservationPieceListDto> data;
            if (dto.IsExportAll)
            {
                data = await query.ToListAsync(HttpContext.RequestAborted);
            }
            else
            {
                var (_, items) = await query.ToPagedListAsync(dto.QueryDto, HttpContext.RequestAborted);
                data = items;
            }

            dynamic? dynamicClass = DynamicClassHelper.CreateDynamicClass<ObservationPieceListDto>(dto.ColumnInfos);

            var dtos = data
                .Select(stu => _mapper.Map(stu, typeof(ObservationPieceListDto), dynamicClass))
                .Cast<object>()
                .ToList();

            var stream = ExcelHelper.CreateStream(dtos);

            return ExcelStreamResult(stream, "观察件列表");
        }

    }
}
