using DataSharing.RawData;
using Hotline.Share.Dtos.Order;
using Hotline.Share.Enums.DataSharing;
using MapsterMapper;
using Microsoft.Extensions.Logging;
using XF.Domain.Repository;

namespace DataSharing.Police110.DaoShu110
{
    /// <summary>
    /// 道枢110
    /// </summary>
    public class DaoShuService : IPoliceService
    {
        private readonly IMapper _mapper;
        private readonly ILogger<DaoShuService> _logger;
        private readonly IRepository<DsPoliceSendChainAlarmDs> _policeSendChainAlarmDsRepository;
        private readonly IRepository<DsPoliceSendChainDealDs> _policeSendChainDealDsRepository;
        private readonly IRepository<DsOrder> _dsOrderRepository;
        private readonly ISharingConfigurationManager _sharingConfigurationManager;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="logger"></param>
        /// <param name="policeSendChainAlarmDsRepository"></param>
        /// <param name="policeSendChainDealDsRepository"></param>
        /// <param name="dsOrderRepository"></param>
        /// <param name="sharingConfigurationManager"></param>
        public DaoShuService(IMapper mapper, ILogger<DaoShuService> logger,
             IRepository<DsPoliceSendChainAlarmDs> policeSendChainAlarmDsRepository,
             IRepository<DsPoliceSendChainDealDs> policeSendChainDealDsRepository,
             IRepository<DsOrder> dsOrderRepository,
             ISharingConfigurationManager sharingConfigurationManager)
        {
            _mapper = mapper;
            _logger = logger;
            _policeSendChainAlarmDsRepository = policeSendChainAlarmDsRepository;
            _policeSendChainDealDsRepository = policeSendChainDealDsRepository;
            _dsOrderRepository = dsOrderRepository;
            _sharingConfigurationManager = sharingConfigurationManager;
        }

        /// <summary>
        /// 组装110数据，12345警情工单推送到110
        /// </summary>
        /// <param name="orderDto"></param>
        /// <returns></returns>
        public async Task InitPoliceSendChainAlarmAsync(OrderDto orderDto, CancellationToken cancellationToken)
        {
            var areaCodeDefu = _sharingConfigurationManager.GetCityCode();
            ConfigurationPoliceDS config = new();
            if (_sharingConfigurationManager.IsCity(ConfigurationConsts.YiBin))
                config = _sharingConfigurationManager.GetYiBinConfig().PoliceDS;
            var registerNo = "10001";
            if (!string.IsNullOrEmpty(orderDto.AcceptorStaffNo))
                registerNo = orderDto.AcceptorStaffNo;
            else
            {
                if (!string.IsNullOrEmpty(orderDto.AcceptorId))
                    registerNo = orderDto.AcceptorId.Substring(orderDto.AcceptorId.Length - 6);
            }
            //  var registerNo = string.IsNullOrEmpty(orderDto.AcceptorId) == true ? "1001" : orderDto.AcceptorId.Substring(orderDto.AcceptorId.Length - 6);
            var Content = orderDto.Content.Length > 290 ? orderDto.Content.Substring(0, 290) : orderDto.Content;
            DsPoliceSendChainAlarmDs policeSend = new()
            {
                SerialNumber = orderDto.ExternalId,
                AlarmReceiptNumber = orderDto.ExternalId,
                RegisterNo = registerNo,
                CallPoliceNumber = string.IsNullOrEmpty(orderDto.FromPhone) == true ? orderDto.Contact : orderDto.FromPhone,
                CallPoliceName = orderDto.FromName,
                PhoneNumber = orderDto.Contact,
                CallPoliceContent = Content,
                PoliceTypeCode = "",
                PoliceTypeName = "",
                JurisdictionalUnitCode = config.GXDWDM,
                JurisdictionalUnitName = config.GXDWMC,
                JurisdictionalUnitNumber = config.GXDWDH,
                AlarmReceivingUnitCode = "12345",
                AlarmReceivingUnitName = "12345热线中心",
                CallPoliceTime = Convert.ToDateTime(orderDto.CreationTime),
                PushTime = DateTime.Now,
                AlarmReceptionType = "0",
                AreaCode = orderDto.AreaCode.Substring(0, 6),
                CallPoliceAddress = orderDto.FullAddress,
                OrderId = orderDto.Id
            };

            if (string.IsNullOrEmpty(policeSend.AlarmReceiptNumber))
            {
                policeSend.AlarmReceiptNumber = areaCodeDefu + "12345" + orderDto.No;
                policeSend.SerialNumber = areaCodeDefu + "12345" + orderDto.No;
            }

            //修改外部唯一ID
            var orderData = await _dsOrderRepository.GetAsync(p => p.OrderId == orderDto.Id, cancellationToken);
            if (orderData != null)
            {
                orderData.ExternalId = policeSend.AlarmReceiptNumber;
                await _dsOrderRepository.UpdateAsync(orderData, cancellationToken);
            }


            //查询是否有此工单，如果没有新增此工单
            var data = await _policeSendChainAlarmDsRepository.GetAsync(p => p.OrderId == orderDto.Id, cancellationToken);
            if (data == null)
                await _policeSendChainAlarmDsRepository.AddAsync(policeSend, cancellationToken);
        }

        /// <summary>
        /// 110的非警情工单获取办理信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task InitPoliceSendChainDealAsync(OrderFlowDto dto, CancellationToken cancellationToken)
        {
            var data = await _policeSendChainDealDsRepository.GetAsync(p => p.OrderId == dto.Order.Id && p.DisposalType == (int)EDsDisposalType.OrderFiled, cancellationToken);
            var actualOpinion = dto.Order.ActualOpinion.Length > 300 ? dto.Order.ActualOpinion.Substring(0, 280) : dto.Order.ActualOpinion;
            var feedbackPersonNumber = "10001";
            if (!string.IsNullOrEmpty(dto.Order.AcceptorStaffNo))
                feedbackPersonNumber = dto.Order.AcceptorStaffNo;
            else
            {
                if (!string.IsNullOrEmpty(dto.Order.AcceptorId))
                    feedbackPersonNumber = dto.Order.AcceptorId.Substring(dto.Order.AcceptorId.Length - 12);
            }
            //var feedbackPersonNumber = string.IsNullOrEmpty(dto.Order.AcceptorId) == true ? "1001" : dto.Order.AcceptorId.Substring(dto.Order.AcceptorId.Length - 12);
            var actualHandleOrgCode = "001";
            if (!string.IsNullOrEmpty(dto.Order.ActualHandleOrgCode))
                actualHandleOrgCode = dto.Order.ActualHandleOrgCode.Length > 12 ? dto.Order.ActualHandleOrgCode.Substring(0, 12) : dto.Order.ActualHandleOrgCode;
            if (data == null)
            {
                data = new()
                {
                    AlarmReceiptNumber = dto.Order.ExternalId,
                    FeedbackTime = dto.Order.ActualHandleTime,
                    DisposalSituation = actualOpinion,
                    ResultDescription = actualOpinion,
                    FeedbackPersonNumber = feedbackPersonNumber,
                    FeedbackPersonName = dto.Order.ActualHandlerName,
                    FeedbackUnitCode = actualHandleOrgCode,
                    FeedbackUnitName = dto.Order.ActualHandleOrgName,
                    WarehousingTime = DateTime.Now,
                    DisposalType = 1,
                    OrderId = dto.Order.Id
                };
                await _policeSendChainDealDsRepository.AddAsync(data, cancellationToken);
            }
            else
            {
                data.AlarmReceiptNumber = dto.Order.ExternalId;
                data.FeedbackTime = dto.Order.ActualHandleTime;
                data.DisposalSituation = actualOpinion;
                data.ResultDescription = actualOpinion;
                data.FeedbackPersonNumber = feedbackPersonNumber;
                data.FeedbackPersonName = dto.Order.ActualHandlerName;
                data.FeedbackUnitCode = actualHandleOrgCode;
                data.FeedbackUnitName = dto.Order.ActualHandleOrgName;
                data.WarehousingTime = DateTime.Now;
                await _policeSendChainDealDsRepository.UpdateAsync(data, cancellationToken);
            }
        }

        /// <summary>
        /// 110警情工单退回
        /// </summary>
        /// <param name="orderDto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task ReturnPoliceAsync(OrderDto orderDto, CancellationToken cancellationToken)
        {
            var checkData = await _policeSendChainDealDsRepository.AnyAsync(p => p.AlarmReceiptNumber == orderDto.ExternalId && p.DisposalType == (int)EDsDisposalType.Return, cancellationToken);
            if (!checkData)
            {
                var actualOpinion = orderDto.ActualOpinion.Length > 100 ? orderDto.ActualOpinion.Substring(0, 80) : orderDto.ActualOpinion;
                var dataPolice = new DsPoliceSendChainDealDs()
                {
                    OrderId = orderDto.Id,
                    AlarmReceiptNumber = orderDto.ExternalId,
                    ReturnName = orderDto.ActualHandlerName,
                    ReturnUnit = orderDto.ActualHandleOrgName,
                    ReturnOpinion = actualOpinion,
                    ReturnTime = orderDto.ActualHandleTime,
                    WarehousingTime = DateTime.Now,
                    DisposalType = 2
                };
                await _policeSendChainDealDsRepository.AddAsync(dataPolice, cancellationToken);
            }
        }

        /// <summary>
        /// 110回访数据
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task Visit(PublishVisitDto dto, CancellationToken cancellationToken)
        {
            var VisitResult = dto.SubjectResultSatifyCode switch
            {
                "2" => "3",
                "4" or "5" => "1",
                _ => "2",
            };
            var checkData = await _policeSendChainDealDsRepository.GetAsync(p => p.AlarmReceiptNumber == dto.Order.ExternalId && p.DisposalType == (int)EDsDisposalType.Visit, cancellationToken);
            string visitRemark = "默认评价";
            if (!string.IsNullOrEmpty(dto.VisitRemark))
            {
                visitRemark = visitRemark.Length > 140 ? dto.VisitRemark.Substring(0, 140) : dto.VisitRemark;
            }

            if (checkData == null)
            {
                checkData = new()
                {
                    AlarmReceiptNumber = dto?.Order?.ExternalId,
                    RevisitTime = dto.VisitTime,
                    CheckingContent = visitRemark,
                    VisitContent = visitRemark,
                    VisitResult = VisitResult,
                    DisposalType = 3
                };
                await _policeSendChainDealDsRepository.AddAsync(checkData, cancellationToken);
            }
            else
            {
                checkData.AlarmReceiptNumber = dto?.Order?.ExternalId;
                checkData.RevisitTime = dto.VisitTime;
                checkData.CheckingContent = visitRemark;
                checkData.VisitContent = visitRemark;
                checkData.VisitResult = VisitResult;
                await _policeSendChainDealDsRepository.UpdateAsync(checkData, cancellationToken);
            }
        }

        /// <summary>
        /// 签收状态
        /// </summary>
        /// <param name="orderDto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task FileEndPoliceAsync(OrderDto orderDto, CancellationToken cancellationToken)
        {

        }

        /// <summary>
        /// 结果签收
        /// </summary>
        /// <param name="orderDto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task SingForPoliceAsync(OrderDto orderDto, CancellationToken cancellationToken)
        {

        }

        /// <summary>
        /// 给110推送行政审批工单（自贡独有）
        /// </summary>
        /// <param name="orderDto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task InitPoliceAdministrativeApproval(OrderDto orderDto, CancellationToken cancellationToken)
        {

        }

        /// <summary>
        /// 泸州110回访
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task InitVisitData(PublishVisitAllDto dto, CancellationToken cancellationToken)
        {

        }
    }
}
