using DataSharing.LuZhou.Encrypt;
using DataSharing.LuZhou.LuZhou110;
using DataSharing.LuZhou.LZ110;
using DataSharing.RawData;
using DataSharing.Share.Dtos.LuZhou;
using Hotline.Share.Dtos.Order;
using Hotline.Share.Enums.Order;
using MapsterMapper;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using XF.Domain.Repository;

namespace DataSharing.Police110.HaiNengDa110
{
    public class HndService : IPoliceService
    {
        private readonly IMapper _mapper;
        private readonly ILogger<HndService> _logger;
        private readonly IRepository<DsPoliceSendChainAlarmHnd> _policeSendChainAlarmHndRepository;
        private readonly IRepository<DsPoliceSendChainDealHnd> _policeSendChainDealHndRepository;
        private readonly IRepository<DsOrder> _dsOrderRepository;
        private readonly ISharingConfigurationManager _sharingConfigurationManager;
        private readonly IRepository<WaitSendTaskLuzhou110> _waitSendTaskLuZhou110Repository;
        private readonly IRepository<SendTaskLuzhou110> _sendTaskLuZhou110Repository;

        /// <summary>
        /// 
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="logger"></param>
        /// <param name="policeSendChainAlarmHndRepository"></param>
        /// <param name="policeSendChainDealHndRepository"></param>
        /// <param name="sharingConfigurationManager"></param>
        /// <param name="waitSendTaskLuZhou110Repository"></param>
        /// <param name="sendTaskLuZhou110Repository"></param>
        public HndService(IMapper mapper, ILogger<HndService> logger,
            IRepository<DsPoliceSendChainAlarmHnd> policeSendChainAlarmHndRepository,
            IRepository<DsPoliceSendChainDealHnd> policeSendChainDealHndRepository,
            IRepository<DsOrder> dsOrderRepository,
            ISharingConfigurationManager sharingConfigurationManager,
            IRepository<WaitSendTaskLuzhou110> waitSendTaskLuZhou110Repository,
            IRepository<SendTaskLuzhou110> sendTaskLuZhou110Repository)
        {
            _mapper = mapper;
            _logger = logger;
            _policeSendChainAlarmHndRepository = policeSendChainAlarmHndRepository;
            _policeSendChainDealHndRepository = policeSendChainDealHndRepository;
            _dsOrderRepository = dsOrderRepository;
            _sharingConfigurationManager = sharingConfigurationManager;
            _waitSendTaskLuZhou110Repository = waitSendTaskLuZhou110Repository;
            _sendTaskLuZhou110Repository = sendTaskLuZhou110Repository;
        }

        /// <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.GetLuZhouConfig().PoliceHND;
            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 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;

            var Title = orderDto.Title.Length > 60 ? orderDto.Title.Substring(0, 60) : orderDto.Title;

            DsPoliceSendChainAlarmHnd 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 = "510500000000",
                AlarmReceivingUnitName = "四川省泸州市市公安局",
                CallPoliceTime = Convert.ToDateTime(orderDto.CreationTime),
                PushTime = DateTime.Now,
                AlarmReceptionType = "0",
                AreaCode = orderDto.AreaCode.Substring(0, 6),
                CallPoliceAddress = orderDto.FullAddress,
                OrderId = orderDto.Id,
                No = orderDto.No,
                IsSecret = orderDto.IsSecret == true ? "1" : "0",
                Title = Title,
            };

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

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

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

        /// <summary>
        /// 110的非警情工单获取办理信息
        /// </summary>
        /// <param name="dto"></param>
        /// <returns></returns>
        public async Task InitPoliceSendChainDealAsync(OrderFlowDto dto, CancellationToken cancellationToken)
        {
            var order = dto.Order;
            var checkData = await _policeSendChainDealHndRepository.AnyAsync(p => p.AlarmReceiptNumber == order.ExternalId && p.DisposalType == "2", cancellationToken);

            var data = await _policeSendChainDealHndRepository.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 - 6);
            }
            //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 = "12345",
                    FeedbackUnitName = "12345政务服务热线",
                    WarehousingTime = DateTime.Now,
                    DisposalType = "1",
                    OrderId = dto.Order.Id,
                    No = dto.Order.No
                };
                await _policeSendChainDealHndRepository.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 = "12345";
                data.FeedbackUnitName = "12345政务服务热线";
                data.WarehousingTime = DateTime.Now;
                await _policeSendChainDealHndRepository.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 _policeSendChainDealHndRepository.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 DsPoliceSendChainDealHnd()
                {
                    OrderId = orderDto.Id,
                    AlarmReceiptNumber = orderDto.ExternalId,
                    ReturnName = orderDto.ActualHandlerName,
                    ReturnUnit = "12345政务服务热线",
                    ReturnOpinion = actualOpinion,
                    ReturnTime = orderDto.ActualHandleTime,
                    WarehousingTime = DateTime.Now,
                    DisposalType = "2",
                    No = orderDto.No
                };
                await _policeSendChainDealHndRepository.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 _policeSendChainAlarmHndRepository.GetAsync(p => p.OrderId == dto.Order.Id && p.AlarmReceptionType == "0", cancellationToken);
                if (checkDataAlarm != null)
                {
                    alarmReceiptNumber = checkDataAlarm.AlarmReceiptNumber;
                }
            }

            var checkData = await _policeSendChainDealHndRepository.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,
                    No = dto.No
                };
                await _policeSendChainDealHndRepository.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 _policeSendChainDealHndRepository.UpdateAsync(checkData, cancellationToken);
            }
        }

        /// <summary>
        /// 泸州110回访（交互-取消）
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task InitVisitData(PublishVisitAllDto dto, CancellationToken cancellationToken)
        {
            var order = dto.Order;
            if (order != null && order.Source == ESource.Police110 && !string.IsNullOrEmpty(order.ExternalId))
            {
                #region 接受数据汇聚 工单回访信息
                if (dto.VisitState == EVisitState.Visited)
                {
                    if (dto.OrderVisitDetails != null && dto.OrderVisitDetails.Count > 0)
                    {
                        var visitMethod = "3";
                        if (dto.VisitType == EVisitType.CallVisit)
                            visitMethod = "1";
                        else if (dto.VisitType == EVisitType.SmsVisit)
                            visitMethod = "2";

                        #region 坐席
                        //坐席
                        var seat = dto.OrderVisitDetails.Where(p => p.VisitTarget == EVisitTarget.Seat).FirstOrDefault();
                        var seatsContent = "";
                        var seatsResult = "";
                        if (seat != null)
                        {
                            seatsContent = seat.VisitContent;
                            seatsResult = seat.SeatEvaluate switch
                            {
                                ESeatEvaluate.VerySatisfied => "1",
                                ESeatEvaluate.Satisfied => "2",
                                ESeatEvaluate.Normal => "3",
                                ESeatEvaluate.NoSatisfied => "4",
                                ESeatEvaluate.VeryNoSatisfied => "5",
                                _ => "2",
                            };
                        }
                        #endregion

                        #region 部门
                        //部门
                        var bm = dto.OrderVisitDetails.Where(p => p.VisitTarget == EVisitTarget.Org).FirstOrDefault();
                        var bmContent = "";
                        var bmResult = "";
                        if (bm != null)
                        {
                            bmContent = bm.VisitContent;
                            bmResult = bm.OrgProcessingResults.Key switch
                            {
                                "5" => "1",
                                "4" => "2",
                                "3" => "3",
                                "2" => "4",
                                "1" => "5",
                                _ => "2",
                            };
                        }
                        #endregion

                        LZ110ZCallBackDto callBackDto = new LZ110ZCallBackDto()
                        {
                            VisitTime = dto.VisitTime.Value.ToString("yyyy/MM/dd HH:mm:ss"),
                            FlowID = order.Id,
                            SeatsContent = seatsContent,
                            SeatsResult = seatsResult,
                            Code = order.No,
                            UserName = string.IsNullOrEmpty(dto.VisitName) == true ? "系统管理员" : dto.VisitName,
                            VisitID = dto.Id,
                            BMContent = bmContent,
                            BMResult = bmResult,
                            VisitMethod = visitMethod,
                            PoliceCode = order.ExternalId
                        };
                        var GDYQSQInfoObject = EncryptHandler.AES(callBackDto);
                        await InitSendData(order.Id, order.No, "1", LZ110Defaults.InteractiveCallBack, 
                            JsonConvert.SerializeObject(callBackDto), JsonConvert.SerializeObject(GDYQSQInfoObject), cancellationToken);
                    }
                }

                #endregion
            }
        }

        /// <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 _policeSendChainDealHndRepository.AnyAsync(p => p.AlarmReceiptNumber == orderDto.ExternalId && p.DisposalType == "4", cancellationToken);
            if (!checkData)
            {
                var feedbackPersonNumber = "10001";
                if (!string.IsNullOrEmpty(orderDto.AcceptorStaffNo))
                    feedbackPersonNumber = orderDto.AcceptorStaffNo;
                else
                {
                    if (!string.IsNullOrEmpty(orderDto.AcceptorId))
                        feedbackPersonNumber = orderDto.AcceptorId.Substring(orderDto.AcceptorId.Length - 6);
                }

                //泸州110签收 跨网交互平台
                var dataPolice = new DsPoliceSendChainDealHnd()
                {
                    OrderId = orderDto.Id,
                    AlarmReceiptNumber = orderDto.ExternalId,
                    DisposalSituation = "已签收",
                    ResultDescription = "已签收",
                    FeedbackUnitCode = "12345",
                    FeedbackUnitName = "12345政务服务热线",
                    FeedbackPersonNumber = feedbackPersonNumber,
                    FeedbackPersonName = orderDto.ActualHandlerName,
                    DisposalType = "4",
                    WarehousingTime = DateTime.Now,
                    No = orderDto.No
                };
                await _policeSendChainDealHndRepository.AddAsync(dataPolice, cancellationToken);
            }
        }

        /// <summary>
        /// 结果签收
        /// </summary>
        /// <param name="orderDto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public Task FileEndPoliceAsync(Hotline.Share.Dtos.Order.OrderDto orderDto, CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }

        /// <summary>
        /// 给110推送行政审批工单（自贡独有）
        /// </summary>
        /// <param name="orderDto"></param>
        /// <returns></returns>
        public Task InitPoliceAdministrativeApproval(Hotline.Share.Dtos.Order.OrderDto orderDto, CancellationToken cancellationToken)
        {
            return Task.CompletedTask;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="OrderId">工单Id</param>
        /// <param name="No">工单编号</param>
        /// <param name="TaskType">任务类型  0：12345工单推送（汇聚），1：110工单推送</param>
        /// <param name="Path">请求地址</param>
        /// <param name="RequestData">组装参数</param>
        /// <param name="Request">请求参数</param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        private async Task<string> InitSendData(string OrderId, string No, string TaskType, string Path, string RequestData, string Request, CancellationToken cancellationToken)
        {
            WaitSendTaskLuzhou110 waitTask = new WaitSendTaskLuzhou110()
            {
                OrderId = OrderId,
                No = No,
                SendTimes = 0,
                TaskType = TaskType,
                HttpMethod = "Post",
                Path = Path,
                RequestData = RequestData,
                Request = Request,
            };
            waitTask.Id = await _waitSendTaskLuZhou110Repository.AddAsync(waitTask, cancellationToken);

            var sendTask = _mapper.Map<SendTaskLuzhou110>(waitTask);
            sendTask.Id = waitTask.Id;
            //写入推送主表
            return await _sendTaskLuZhou110Repository.AddAsync(sendTask, cancellationToken);

        }

    }
}
