using DataSharing.LuZhou.Encrypt;
using DataSharing.LuZhou.LuZhou110;
using DataSharing.LuZhou.LZ110;
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 SqlSugar;
using XF.Domain.Repository;

namespace DataSharing.LuZhou
{
    public class LuZhou110Service : ILuZhou110Service
    {
        private readonly IMapper _mapper;
        private readonly ILogger<LuZhou110Service> _logger;
        private readonly IRepository<WaitSendTaskLuZhou110> _waitSendTaskLuZhou110Repository;
        private readonly IRepository<SendTaskLuZhou110> _sendTaskLuZhou110Repository;

        public LuZhou110Service(IMapper mapper, ILogger<LuZhou110Service> logger,
            IRepository<WaitSendTaskLuZhou110> waitSendTaskLuZhou110Repository,
            IRepository<SendTaskLuZhou110> sendTaskLuZhou110Repository
            )
        {
            _mapper = mapper;
            _logger = logger;
            _waitSendTaskLuZhou110Repository = waitSendTaskLuZhou110Repository;
            _sendTaskLuZhou110Repository = sendTaskLuZhou110Repository;
        }

        /// <summary>
        /// 组装基础参数
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task InitData(OrderFlowDto dto, CancellationToken cancellationToken)
        {
            var order = dto.Order;
            if (order.TransferPhone == "12345")
            {
                #region 接受数据汇聚 工单基础信息
                var gender = "";
                if (order.FromGender == EGender.Female)
                    gender = "女";
                if (order.FromGender == EGender.Male)
                    gender = "男";
                LZ110BasicInfoDto basicInfoDto = new LZ110BasicInfoDto()
                {
                    FlowID = order.Id,
                    Code = order.No,
                    PoliceCode = "",
                    AreaName = order.AreaCode.Substring(0, 6),
                    AddDate = order.CreationTime.ToString("yyyy/MM/dd HH:mm:ss"),
                    FromTel = order.FromPhone,
                    CallerName = order.FromName,
                    Gender = gender,
                    ContactTel = order.Contact,
                    IDCard = order.LicenceNo,
                    TelHome = "",
                    Address = order.Province + order.City + order.County + order.Street,
                    WorkUnit = "",
                    Title = order.Title,
                    PurTypeName = order.AcceptType,
                    FromName = order.SourceChannel,
                    ConTypeName = order.HotspotSpliceName,
                    Content = order.Content,
                    IsSecrecy = order.IsSecret == true ? "1" : "0"
                };
                var GDJCXXInfoObject = EncryptHandler.AES(basicInfoDto);

                await InitSendData(order.Id, order.No, "0", LZ110Defaults.SendBasicInfo, JsonConvert.SerializeObject(basicInfoDto), JsonConvert.SerializeObject(GDJCXXInfoObject), cancellationToken);
                #endregion

                #region 接受数据汇聚 工单流转信息
                var nodeName = "派单组";
                var nodeType = "2";
                if (!string.IsNullOrEmpty(order.ActualHandleOrgName) && order.ActualHandleOrgName != "001")
                {
                    if (order.ActualHandleOrgName.Length == 6)
                    {
                        nodeName = "一级部门受理";
                        nodeType = "4";
                    }
                    else if (order.ActualHandleOrgName.Length == 9)
                    {
                        nodeName = "二级部门办理";
                        nodeType = "4";
                    }
                    else if (order.ActualHandleOrgName.Length == 12)
                    {
                        nodeName = "三级部门办理";
                        nodeType = "4";
                    }
                }

                LZ110FlowedDto flowedDto = new LZ110FlowedDto()
                {
                    RunID = dto.WorkflowTrace.Id,
                    FlowID = order.Id,
                    Code = order.No,
                    NodeName = nodeName,
                    NodeType = nodeType,
                    HandleBMName = order.ActualHandleOrgName,
                    HandleUserName = order.ActualHandlerName,
                    HandleTime = order.ActualHandleTime.HasValue == true ? order.ActualHandleTime.Value.ToString("yyyy/MM/dd HH:mm:ss") : DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"),
                    HandleOpinion = order.ActualOpinion,
                    IsPolice = "0",
                    PoliceCode = string.Empty,
                    HandleState = string.Empty
                };

                var GdblztInfoObject = EncryptHandler.AES(flowedDto);
                await InitSendData(order.Id, order.No, "0", LZ110Defaults.SendFlowed, JsonConvert.SerializeObject(flowedDto), JsonConvert.SerializeObject(GdblztInfoObject), cancellationToken);
                #endregion

                #region 接受数据汇聚 工单办理结果

                LZ110HandResultDto handResultDto = new LZ110HandResultDto()
                {
                    Code = order.No,
                    HandleUserName = order.ActualHandlerName,
                    HandleBMName = order.ActualHandleOrgName,
                    HandleTime = order.FiledTime.HasValue == true ? order.FiledTime.Value.ToString("yyyy/MM/dd HH:mm:ss") : DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"),
                    HandleOpinion = order.FileOpinion,
                    HandleState = "办理完成",
                    PoliceCode = "",
                };
                var GDBLJGInfoObject = EncryptHandler.AES(handResultDto);
                await InitSendData(order.Id, order.No, "0", LZ110Defaults.SendHandResult, JsonConvert.SerializeObject(handResultDto), JsonConvert.SerializeObject(GDBLJGInfoObject), cancellationToken);

                #endregion

                #region 接受数据汇聚 工单办理状态
                LZ110UpdateStatusDto updateStatusDto = new LZ110UpdateStatusDto()
                {
                    Code = order.No,
                    FlowID = order.Id,
                    PoliceCode = "",
                    HandleState = "已归档",
                };
                var GDBLZTInfoObject = EncryptHandler.AES(updateStatusDto);
                await InitSendData(order.Id, order.No, "0", LZ110Defaults.SendUpdateStatus, JsonConvert.SerializeObject(updateStatusDto), JsonConvert.SerializeObject(GDBLZTInfoObject), cancellationToken);


                #endregion

                #region 接受数据汇聚 工单延期申请
                if (dto.OrderSearchDelay != null)
                {
                    var orderSearchDelay = dto.OrderSearchDelay;
                    LZ110ExtensionRequestDto extensionRequestDto = new LZ110ExtensionRequestDto()
                    {
                        FlowID = order.Id,
                        Code = order.No,
                        ApplyBMName = orderSearchDelay.ApplyOrgName,
                        ApplyUserName = orderSearchDelay.EmployeeName,
                        ApplyTime = orderSearchDelay.ApplyDelayTime.ToString("yyyy/MM/dd HH:mm:ss"),
                        ApplyTimeLimit = orderSearchDelay.DelayNum.ToString(),
                        ApplyContent = orderSearchDelay.DelayReason,
                        FPID = orderSearchDelay.Id,
                        RunID = orderSearchDelay.WorkflowId,
                    };
                    var GDYQSQInfoObject = EncryptHandler.AES(extensionRequestDto);
                    await InitSendData(order.Id, order.No, "0", LZ110Defaults.SendExtensionRequest, JsonConvert.SerializeObject(extensionRequestDto), JsonConvert.SerializeObject(GDYQSQInfoObject), cancellationToken);

                }

                #endregion

            }
        }

        /// <summary>
        /// 回访
        /// </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.TransferPhone == "12345")
            {
                #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

                        LZ110CallBackDto callBackDto = new LZ110CallBackDto()
                        {
                            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
                        };
                        var GDYQSQInfoObject = EncryptHandler.AES(callBackDto);
                        await InitSendData(order.Id, order.No, "0", LZ110Defaults.SendCallBack, JsonConvert.SerializeObject(callBackDto), JsonConvert.SerializeObject(GDYQSQInfoObject), cancellationToken);
                    }
                }

                #endregion
            }
        }

        /// <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>
        public 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);

        }
    }
}
