using DataSharing.RawData;
using DataSharing.SendTask;
using DataSharing.Share.Dtos.LuZhou;
using DataSharing.Share.Enums;
using Hotline.Share.Dtos.Order;
using System.Text.Json;
using XF.Domain.Exceptions;
using XF.Domain.Repository;

namespace DataSharing.LuZhou.LZCityPortal
{
    public class LZCityPortalSiteService : ILZCityPortalSiteService
    {
        private readonly IInitPushDataService _initPushDataService;
        private readonly IRepository<DsUserTokenInfo> _dsUserTokenInfoRepository;
        private readonly ISharingConfigurationManager _sharingConfigurationManager;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="initPushDataService"></param>
        /// <param name="dsUserTokenInfoRepository"></param>
        /// <param name="sharingConfigurationManager"></param>
        public LZCityPortalSiteService(
            IInitPushDataService initPushDataService,
            IRepository<DsUserTokenInfo> dsUserTokenInfoRepository,
            ISharingConfigurationManager sharingConfigurationManager)
        {
            _initPushDataService = initPushDataService;
            _dsUserTokenInfoRepository = dsUserTokenInfoRepository;
            _sharingConfigurationManager = sharingConfigurationManager;
        }

        /// <summary>
        /// 办理意见推送
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task SendOpinionAsync(OrderDto dto, CancellationToken cancellationToken)
        {
            var userInfo = await _dsUserTokenInfoRepository.GetAsync(p => p.PlatformSource == dto.Source.ToString() && p.State == "1", cancellationToken);
            if (userInfo is null)
                throw UserFriendlyException.SameMessage("未配置token信息!");

            ConfigurationCityPortalSite config = _sharingConfigurationManager.GetLuZhouConfig().CityPortalSite;

            if (config == null)
                throw UserFriendlyException.SameMessage("未配置结果接口!");

            CityPortalSiteDto addOpinionDto = new CityPortalSiteDto
            {
                AcceptCode = dto.No,
                AcceptPwd = dto.Password,
                ReplyContent = dto.ActualOpinion,
                ReplyUnit = dto.ActualHandleOrgName,
                FinishTime = dto.ActualHandleTime
            };

            var request = JsonSerializer.Serialize(addOpinionDto);
            await _initPushDataService.InitDsSendTaskOtherPlatforms(
                userInfo.PlatformSource,
                config.PushOpinion,
                dto.No,
                request,
                request,
                EPlatformSource.LZCityPortalSite,
                cancellationToken: cancellationToken);

        }
    }
}
