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

namespace DataSharing.Police110.DCJT110
{
    public class DcjtService : IPoliceService
    {
        private readonly IMapper _mapper;
        private readonly ILogger<DcjtService> _logger;
        private readonly IRepository<DsPoliceSendChainAlarmDcjt> _policeSendChainAlarmDcjtRepository;
        private readonly IRepository<DsPoliceSendChainDealDcjt> _policeSendChainDealDcjtRepository;
        private readonly IRepository<DsOrder> _dsOrderRepository;
        private readonly ISharingConfigurationManager _sharingConfigurationManager;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="logger"></param>
        /// <param name="policeSendChainAlarmDcjtRepository"></param>
        /// <param name="policeSendChainDealDcjtRepository"></param>
        /// <param name="dsOrderRepository"></param>
        /// <param name="sharingConfigurationManager"></param>
        public DcjtService(IMapper mapper, ILogger<DcjtService> logger,
            IRepository<DsPoliceSendChainAlarmDcjt> policeSendChainAlarmDcjtRepository,
            IRepository<DsPoliceSendChainDealDcjt> policeSendChainDealDcjtRepository,
             IRepository<DsOrder> dsOrderRepository,
             ISharingConfigurationManager sharingConfigurationManager)
        {
            _mapper = mapper;
            _logger = logger;
            _policeSendChainAlarmDcjtRepository = policeSendChainAlarmDcjtRepository;
            _policeSendChainDealDcjtRepository = policeSendChainDealDcjtRepository;
            _dsOrderRepository = dsOrderRepository;
            _sharingConfigurationManager = sharingConfigurationManager;
        }

        /// <summary>
        /// 组装110数据，12345警情工单推送到110
        /// </summary>
        /// <param name="orderDto"></param>
        /// <returns></returns>
        public async Task InitPoliceSendChainAlarmAsync(Hotline.Share.Dtos.Order.OrderDto orderDto, CancellationToken cancellationToken)
        {
            var areaCodeDefu = _sharingConfigurationManager.GetCityCode();
            var config = _sharingConfigurationManager.GetZiGongConfig().PoliceDCJT;
            var registerNo = "10001";
            if (!string.IsNullOrEmpty(orderDto.AcceptorStaffNo))
                registerNo = orderDto.AcceptorStaffNo;
            else
            {
                if (!string.IsNullOrEmpty(orderDto.AcceptorId))
                    registerNo = orderDto.AcceptorId.Substring(orderDto.AcceptorId.Length - 12);
            }
            //  var registerNo = string.IsNullOrEmpty(orderDto.AcceptorId) == true ? "1001" : orderDto.AcceptorId.Substring(orderDto.AcceptorId.Length - 12);
            var Content = orderDto.Content.Length > 1900 ? orderDto.Content.Substring(0, 1900) : orderDto.Content;
            var policeTypeCode = "01";
            if (!string.IsNullOrEmpty(orderDto.HotspotId))
                policeTypeCode = orderDto.HotspotId.Length > 8 ? orderDto.HotspotId.Substring(0, 7) : orderDto.HotspotId;

            DsPoliceSendChainAlarmDcjt policeSend = new()
            {
                SerialNumber = orderDto.ExternalId,
                AlarmReceiptNumber = orderDto.ExternalId,
                RegisterNo = registerNo,
                RegisterName = orderDto.AcceptorName,
                CallPoliceNumber = string.IsNullOrEmpty(orderDto.FromPhone) == true ? orderDto.Contact : orderDto.FromPhone,
                CallPoliceName = orderDto.FromName,
                PhoneNumber = orderDto.Contact,
                CallPoliceContent = Content,
                PoliceTypeCode = policeTypeCode,
                PoliceTypeName = orderDto.HotspotSpliceName,
                JurisdictionalUnitCode = config.GXDWDM,
                JurisdictionalUnitName = config.GXDWMC,
                JurisdictionalUnitNumber = config.GXDWDH,
                AlarmReceivingUnitCode = "510300010000",
                AlarmReceivingUnitName = "四川省自贡市公安局指挥中心",
                CallPoliceTime = Convert.ToDateTime(orderDto.CreationTime),
                PushTime = DateTime.Now,
                AlarmReceptionType = "0",
                AreaCode = orderDto.AreaCode.Substring(0, 6),
                CallPoliceAddress = orderDto.FullAddress,
                OrderId = orderDto.Id
            };

            policeSend.FromGender = orderDto.FromGender switch
            {
                Hotline.Share.Enums.Order.EGender.Female => "0",
                Hotline.Share.Enums.Order.EGender.Male => "1",
                Hotline.Share.Enums.Order.EGender.Unknown => "2",
                _ => "2",
            };

            if (string.IsNullOrEmpty(policeSend.AlarmReceiptNumber))
            {
                policeSend.AlarmReceiptNumber = areaCodeDefu + "1234512345" + orderDto.No;
                policeSend.SerialNumber = areaCodeDefu + "1234512345" + 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 _policeSendChainAlarmDcjtRepository.GetAsync(p => p.OrderId == orderDto.Id && p.AlarmReceptionType == "1", cancellationToken);
            if (data == null)
                await _policeSendChainAlarmDcjtRepository.AddAsync(policeSend, cancellationToken);
        }

        /// <summary>
        /// 110的非警情工单获取办理信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task InitPoliceSendChainDealAsync(OrderFlowDto dto, CancellationToken cancellationToken)
        {
            var data = await _policeSendChainDealDcjtRepository.GetAsync(p => p.OrderId == dto.Order.Id && p.DisposalType == "1", cancellationToken);
            var actualOpinion = dto.Order.ActualOpinion.Length > 1500 ? dto.Order.ActualOpinion.Substring(0, 1500) : 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 _policeSendChainDealDcjtRepository.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 _policeSendChainDealDcjtRepository.UpdateAsync(data, cancellationToken);
            }
        }

        /// <summary>
        /// 110警情工单退回
        /// </summary>
        /// <param name="orderDto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task ReturnPoliceAsync(Hotline.Share.Dtos.Order.OrderDto orderDto, CancellationToken cancellationToken)
        {
            var checkData = await _policeSendChainDealDcjtRepository.AnyAsync(p => p.AlarmReceiptNumber == orderDto.ExternalId && p.DisposalType == "2", cancellationToken);
            if (!checkData)
            {
                var actualOpinion = orderDto.ActualOpinion.Length > 100 ? orderDto.ActualOpinion.Substring(0, 80) : orderDto.ActualOpinion;
                var dataPolice = new DsPoliceSendChainDealDcjt()
                {
                    OrderId = orderDto.Id,
                    AlarmReceiptNumber = orderDto.ExternalId,
                    ReturnName = orderDto.ActualHandlerName,
                    ReturnUnit = orderDto.ActualHandleOrgName,
                    ReturnOpinion = actualOpinion,
                    ReturnTime = orderDto.ActualHandleTime,
                    WarehousingTime = DateTime.Now,
                    DisposalType = "2"
                };
                await _policeSendChainDealDcjtRepository.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",
            };
            //如果来源是110，直接取工单里面的编号
            var alarmReceiptNumber = dto.Order.ExternalId;
            if (string.IsNullOrEmpty(alarmReceiptNumber))
            {
                var checkDataAlarm = await _policeSendChainAlarmDcjtRepository.GetAsync(p => p.OrderId == dto.Order.Id && p.AlarmReceptionType == "0", cancellationToken);
                if (checkDataAlarm != null)
                {
                    alarmReceiptNumber = checkDataAlarm.AlarmReceiptNumber;
                }
            }

            var checkData = await _policeSendChainDealDcjtRepository.GetAsync(p => p.AlarmReceiptNumber == alarmReceiptNumber && p.DisposalType == "3", cancellationToken);
            string visitRemark = "默认评价";
            if (!string.IsNullOrEmpty(dto.VisitRemark))
            {
                visitRemark = visitRemark.Length > 140 ? dto.VisitRemark.Substring(0, 140) : dto.VisitRemark;
            }
            if (checkData == null)
            {
                checkData = new()
                {
                    OrderId = dto.Order.Id,
                    AlarmReceiptNumber = alarmReceiptNumber,
                    RevisitTime = dto.VisitTime,
                    CheckingContent = visitRemark,
                    VisitContent = visitRemark,
                    VisitResult = VisitResult,
                    DisposalType = "3",
                    CreatorName = dto.VisitName,
                    WarehousingTime = DateTime.Now,
                };
                await _policeSendChainDealDcjtRepository.AddAsync(checkData, cancellationToken);
            }
            else
            {
                checkData.AlarmReceiptNumber = alarmReceiptNumber;
                checkData.RevisitTime = dto.VisitTime;
                checkData.CheckingContent = visitRemark;
                checkData.VisitContent = visitRemark;
                checkData.VisitResult = VisitResult;
                checkData.CreatorName = dto.VisitName;
                checkData.WarehousingTime = DateTime.Now;
                await _policeSendChainDealDcjtRepository.UpdateAsync(checkData, cancellationToken);
            }
        }

        /// <summary>
        /// 签收状态
        /// </summary>
        /// <param name="orderDto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task SingForPoliceAsync(Hotline.Share.Dtos.Order.OrderDto orderDto, CancellationToken cancellationToken)
        {
            var checkData = await _policeSendChainDealDcjtRepository.AnyAsync(p => p.AlarmReceiptNumber == orderDto.ExternalId && p.DisposalType == "4", cancellationToken);
            if (!checkData)
            {
                var dataPolice = new DsPoliceSendChainDealDcjt()
                {
                    OrderId = orderDto.Id,
                    AlarmReceiptNumber = orderDto.ExternalId,
                    DisposalType = "4",
                    WarehousingTime = DateTime.Now,
                };
                await _policeSendChainDealDcjtRepository.AddAsync(dataPolice, cancellationToken);
            }
        }

        /// <summary>
        /// 结果签收
        /// </summary>
        /// <param name="orderDto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task FileEndPoliceAsync(Hotline.Share.Dtos.Order.OrderDto orderDto, CancellationToken cancellationToken)
        {
            var checkData = await _policeSendChainAlarmDcjtRepository.GetAsync(p => p.OrderId == orderDto.Id && p.AlarmReceptionType == "0", cancellationToken);
            if (checkData != null)
            {
                var checkDataDeal = await _policeSendChainDealDcjtRepository.AnyAsync(p => p.AlarmReceiptNumber == checkData.AlarmReceiptNumber && p.DisposalType == "5", cancellationToken);
                if (!checkDataDeal)
                {
                    var dataPolice = new DsPoliceSendChainDealDcjt()
                    {
                        OrderId = orderDto.Id,
                        AlarmReceiptNumber = checkData.AlarmReceiptNumber,
                        DisposalType = "5",
                        WarehousingTime = DateTime.Now,
                    };
                    await _policeSendChainDealDcjtRepository.AddAsync(dataPolice, cancellationToken);
                }
            }
        }

        /// <summary>
        /// 给110推送行政审批工单（自贡独有）
        /// </summary>
        /// <param name="orderDto"></param>
        /// <returns></returns>
        public async Task InitPoliceAdministrativeApproval(Hotline.Share.Dtos.Order.OrderDto orderDto, CancellationToken cancellationToken)
        {
            try
            {
                var areaCodeDefu = _sharingConfigurationManager.GetCityCode();
                var config = _sharingConfigurationManager.GetZiGongConfig().PoliceDCJT;
                var registerNo = "10001";
                if (!string.IsNullOrEmpty(orderDto.AcceptorStaffNo))
                    registerNo = orderDto.AcceptorStaffNo;
                else
                {
                    if (!string.IsNullOrEmpty(orderDto.AcceptorId))
                        registerNo = orderDto.AcceptorId.Substring(orderDto.AcceptorId.Length - 12);
                }
                var Content = orderDto.Content.Length > 1900 ? orderDto.Content.Substring(0, 1900) : orderDto.Content;
                var policeTypeCode = "01";
                if (!string.IsNullOrEmpty(orderDto.HotspotId))
                    policeTypeCode = orderDto.HotspotId.Length > 8 ? orderDto.HotspotId.Substring(0, 7) : orderDto.HotspotId;
                DsPoliceSendChainAlarmDcjt policeSend = new()
                {
                    SerialNumber = orderDto.ExternalId,
                    AlarmReceiptNumber = orderDto.ExternalId,
                    RegisterNo = registerNo,
                    RegisterName = orderDto.AcceptorName,
                    CallPoliceNumber = string.IsNullOrEmpty(orderDto.FromPhone) == true ? orderDto.Contact : orderDto.FromPhone,
                    CallPoliceName = orderDto.FromName,
                    PhoneNumber = orderDto.Contact,
                    CallPoliceContent = Content,
                    PoliceTypeCode = policeTypeCode,
                    PoliceTypeName = orderDto.HotspotSpliceName,
                    JurisdictionalUnitCode = config.GXDWDM,
                    JurisdictionalUnitName = config.GXDWMC,
                    JurisdictionalUnitNumber = config.GXDWDH,
                    AlarmReceivingUnitCode = "510300010000",
                    AlarmReceivingUnitName = "四川省自贡市公安局指挥中心",
                    CallPoliceTime = Convert.ToDateTime(orderDto.CreationTime),
                    PushTime = DateTime.Now,
                    AlarmReceptionType = "3",
                    AreaCode = orderDto.AreaCode.Substring(0, 6),
                    CallPoliceAddress = orderDto.FullAddress,
                    OrderId = orderDto.Id
                };

                policeSend.FromGender = orderDto.FromGender switch
                {
                    Hotline.Share.Enums.Order.EGender.Female => "0",
                    Hotline.Share.Enums.Order.EGender.Male => "1",
                    Hotline.Share.Enums.Order.EGender.Unknown => "2",
                    _ => "2",
                };

                policeSend.AlarmReceiptNumber = areaCodeDefu + "1234512345" + orderDto.No;
                policeSend.SerialNumber = areaCodeDefu + "1234512345" + orderDto.No;

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

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

        }
    }
}
