using System.Net.Http.Headers;
using AutoFixture;
using Fw.Utility.UnifyResponse;
using Hotline.Api.Controllers;
using Hotline.Api.Controllers.Snapshot;
using Hotline.Caching.Interfaces;
using Hotline.FlowEngine.Notifications;
using Hotline.Orders;
using Hotline.Share.Dtos;
using Hotline.Share.Dtos.File;
using Hotline.Share.Dtos.FlowEngine;
using Hotline.Share.Dtos.FlowEngine.Workflow;
using Hotline.Share.Dtos.Order;
using Hotline.Share.Dtos.Snapshot;
using Hotline.Share.Enums.FlowEngine;
using Hotline.Share.Enums.Snapshot;
using Hotline.Share.Tools;
using Hotline.Tests.Dto;
using Hotline.Tests.Mock.Interfaces;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using XF.Domain.Authentications;
using XF.Domain.Repository;
using System.Net.Http.Headers;
using Hotline.Share.Dtos;
using Hotline.FlowEngine.Notifications;
using Hotline.Api.Controllers.Bi;
using XF.Domain.Exceptions;
using System;
using DocumentFormat.OpenXml.Bibliography;
using Hotline.Snapshot;
using Hotline.Share.Enums.Settings;
using Npgsql;

namespace Hotline.Tests.Mock;
public class OrderServiceMock
{
    private readonly OrderController _orderController;
    public CreateOrderOutDto CreateOrderOutDto;
    private AddOrderDto AddOrderDto;
    private readonly IRepository<Order> _orderRepository;
    private readonly IOrderVisitRepository _orderVisitRepository;
    private readonly SnapshotController _snapshotController;
    private readonly ISystemSettingCacheManager _systemSettingCacheManager;
    public readonly IFixture _fixture;
    public readonly ISessionContext _sessionContext;
    public readonly IOrderServiceStartWorkflow _orderServiceStartWorkflow;
    public readonly RedPackController _redPackController;
    private readonly ISystemDicDataCacheManager _systemDicDataCacheManager;

    public OrderServiceMock(OrderController orderController, IRepository<Order> orderRepository, IOrderVisitRepository orderVisitRepository, SnapshotController snapshotController, ISessionContext sessionContext, IOrderServiceStartWorkflow orderServiceStartWorkflow, ISystemSettingCacheManager systemSettingCacheManager, RedPackController redPackController, ISystemDicDataCacheManager systemDicDataCacheManager)
    {
        _orderController = orderController;
        _orderController.ControllerContext = new ControllerContext
        {
            HttpContext = new DefaultHttpContext()
        };
        _orderRepository = orderRepository;
        _orderVisitRepository = orderVisitRepository;
        _snapshotController = snapshotController;
        _snapshotController.ControllerContext = new ControllerContext
        {
            HttpContext = new DefaultHttpContext()
        };
        _fixture = new Fixture();
        _sessionContext = sessionContext;
        _orderServiceStartWorkflow = orderServiceStartWorkflow;
        _systemSettingCacheManager = systemSettingCacheManager;
        _redPackController = redPackController;
        _redPackController.ControllerContext = new ControllerContext
        {
            HttpContext = new DefaultHttpContext(),
        };
        _systemDicDataCacheManager = systemDicDataCacheManager;
    }

    public IOrderServiceStartWorkflow CreateSnapshotOrder(Action action, string industryName = "电气焊作业申报")
    {
        action.Invoke();
        var homePage = _snapshotController.GetHomePageAsync().GetAwaiter().GetResult();
        var industry = homePage.Industrys
            .Where(m => m.Name == industryName)
            .OrderBy(m => m.DisplayOrder)
            .FirstOrDefault();
        var pageBase = _snapshotController.GetIndustryBaseAsync(industry.Id).GetAwaiter().GetResult();

        var inDto = _fixture.Create<AddSnapshotOrderInDto>();
        inDto.Street = "单元测试街道" + DateTime.Now.ToLongDateTimeString();
        inDto.IndustryId = industry.Id;
        inDto.Town = "仙市镇";
        inDto.AreaCode = "510302";
        inDto.County = "自流井区";
        inDto.Description = "单元测试添加的时间描述";
        inDto.IsSecret = false;
        inDto.PhoneNumber = _sessionContext.Phone;
        inDto.Latitude = 29.3661181959828;
        inDto.Longitude = 104.41928;
        //inDto.JobType = 
        var file = 0;
        foreach (var item in inDto.Files)
        {
            var i = UploadImage();
            if (i.Code == -1)
            {
                file = i.Code;
                break;
            }
            var result = i.Result;
            item.FileName = result.FileName;
            item.Path = result.Path;
            item.AdditionId = result.Id;
        }
        if (file == -1) inDto.Files = new List<SnapshotFileInDto>();
        CreateOrderOutDto = _snapshotController.AddOrderAsync(inDto).GetAwaiter().GetResult().ToJson().FromJson<CreateOrderOutDto>();
        _orderServiceStartWorkflow.orderServiceMock = this;
        return _orderServiceStartWorkflow;
    }

    public IOrderServiceStartWorkflow CreateOrder(string callId = "", string industryId = "", string industryName = "", List<string> tags = null)
    {
        var json = "{\"sourceChannel\":\"因特网\",\"sourceChannelCode\":\"YTW\",\"transferPhone\":null,\"fromPhone\":null,\"acceptorName\":\"单元测试\",\"acceptorStaffNo\":\"\",\"fromName\":\"1233333333\",\"fromGender\":1,\"identityType\":1,\"licenceType\":null,\"licenceTypeCode\":null,\"licenceNo\":null,\"ageRange\":null,\"ageRangeCode\":null,\"contact\":\"12333333333\",\"isSecret\":false,\"acceptSms\":false,\"no\":null,\"title\":\"\",\"hotspotId\":\"1912\",\"eventCategoryId\":null,\"incidentTime\":null,\"incidentPurpose\":null,\"areaCode\":\"519800\",\"city\":\"省内\",\"street\":null,\"isRepeat\":\"false\",\"pushType\":null,\"pushTypeCode\":null,\"content\":\"单元测试内容\",\"duplicateIds\":[],\"duplicateTitle\":null,\"callAddress\":null,\"repeatableEventDetails\":[],\"orderExtension\":null,\"transpond\":false,\"isEnforcementOrder\":false,\"focusOnEventsArr\":[],\"focusOnEvents\":null,\"isFormalistWorkOrder\":false,\"isSensitiveWorkOrders\":false,\"isUrgent\":false,\"isThreePartyConference\":false,\"is24HoursComplete\":false,\"company\":null,\"orderPushTypes\":[],\"acceptType\":\"咨询\",\"acceptTypeCode\":\"10\",\"files\":[],\"hotspotSpliceName\":\"互联互通-转接乐山市12345\",\"hotspotName\":\"转接乐山市12345\",\"hotspotCode\":\"1912\",\"hotspotExternal\":\"19\",\"county\":\"\",\"town\":\"\"}";
        AddOrderDto = json.FromJson<AddOrderDto>();
        if (callId.NotNullOrEmpty())
        {
            AddOrderDto.CallId = callId;
            AddOrderDto.SourceChannel = "电话";
            AddOrderDto.SourceChannelCode = AppDefaults.SourceChannel.DianHua;
        }
        AddOrderDto.IndustryId = industryId;
        AddOrderDto.IndustryName = industryName;
        AddOrderDto.Title = "单元测试" + DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
        if (tags.NotNullOrEmpty())
            AddOrderDto.Tags = tags;
        RetryHelper.Retry(() =>
            {
                try
                {
                    CreateOrderOutDto = _orderController.Add(AddOrderDto).GetAwaiter().GetResult().ToJson().FromJson<CreateOrderOutDto>();
                }
                catch (PostgresException e)
                {
                    if (e.Message.Contains("unique_order_no"))
                    {
                        return false;
                    }
                }
                return true;
            }, 10);
        _orderServiceStartWorkflow.orderServiceMock = this;
        return _orderServiceStartWorkflow;
    }

    public OrderServiceMock UpdateOrder()
    {
        UpdateOrderDto order = _orderController.Get(CreateOrderOutDto.Id).GetAwaiter().GetResult();
        _orderController.Update(order).GetAwaiter().GetResult();
        return this;
    }

    public CreateOrderOutDto GetCreateResult()
    {
        return CreateOrderOutDto;
    }

    public OrderServiceMock 办理到派单员(Action action = null, bool isSafetyDepartment = false)
    {
        action?.Invoke();
        var stepNextInfo = _orderController.GetNextStepsWithRecommend(CreateOrderOutDto.Id).GetAwaiter().GetResult().ToJson().FromJson<NextStepsDto<NextStepOption>>();
        var stepInfo = stepNextInfo.Steps.FirstOrDefault(m => m.Value == "派单组");
        var stepOrg = stepInfo.Items.FirstOrDefault(m => m.Username == "单元测试派单员");

        var order = _orderRepository.Get(CreateOrderOutDto.Id);
        var handleDto = new NextWorkflowDto<OrderHandleFlowDto>
        {
            Data = new OrderHandleFlowDto
            {
                OrderId = CreateOrderOutDto.Id,
                IsSafetyDepartment = isSafetyDepartment
            },
            Workflow = new NextWorkflowDto
            {
                WorkflowId = order.WorkflowId,
                StepId = stepNextInfo.StepId,
                NextHandlers = [stepOrg],
                NextStepCode = stepInfo.Key,
                NextStepName = stepInfo.Value,
                Opinion = "办理到派单组意见",
                BackToCountersignEnd = false,
                IsSms = false,
                IsForwarded = false,
                HandlerType = EHandlerType.OrgLevel,
                BusinessType = EBusinessType.Send,
                FlowDirection = EFlowDirection.CenterToCenter,
                CurrentTag = TagDefaults.OrderMark
            }
        };
        _orderController.Handle(handleDto).GetAwaiter().GetResult();
        return this;

    }

    public OrderServiceMock 办理到一级部门(Action action = null)
    {
        action?.Invoke();
        var stepNextInfo = _orderController.GetNextStepsWithRecommend(CreateOrderOutDto.Id).GetAwaiter().GetResult().ToJson().FromJson<NextStepsDto<NextStepOption>>();
        var stepInfo = stepNextInfo.Steps.FirstOrDefault(m => m.Value == "一级部门");
        var stepOrg = stepInfo.Items.FirstOrDefault(m => m.OrgName == "测试部门");

        var order = _orderRepository.Get(CreateOrderOutDto.Id);
        var handleDto = new NextWorkflowDto<OrderHandleFlowDto>
        {
            Data = new OrderHandleFlowDto
            {
                OrderId = CreateOrderOutDto.Id,
            },
            Workflow = new NextWorkflowDto
            {
                WorkflowId = order.WorkflowId,
                StepId = stepNextInfo.StepId,
                NextHandlers = [stepOrg],
                NextStepCode = stepInfo.Key,
                NextStepName = stepInfo.Value,
                Opinion = "办理意见",
                BackToCountersignEnd = false,
                IsSms = false,
                IsForwarded = false,
                HandlerType = EHandlerType.OrgLevel,
                BusinessType = EBusinessType.Department,
            }
        };
        _orderController.Handle(handleDto).GetAwaiter().GetResult();
        return this;
    }

    public OrderServiceMock 办理到归档(Action action = null, Action<OrderHandleFlowDto> dataAction = null, Action<NextWorkflowDto> workflowAction = null)
    {
        action?.Invoke();
        var stepNextInfo = _orderController.GetNextStepsWithRecommend(CreateOrderOutDto.Id).GetAwaiter().GetResult().ToJson().FromJson<NextStepsDto<NextStepOption>>();
        var stepInfo = stepNextInfo.Steps.FirstOrDefault(m => m.Value == "归档");
        var stepOrg = stepInfo.Items.FirstOrDefault();

        var order = _orderRepository.Get(CreateOrderOutDto.Id);

        var handleDto = new NextWorkflowDto<OrderHandleFlowDto>
        {
            Data = new OrderHandleFlowDto
            {
                OrderId = CreateOrderOutDto.Id,
                RealHandlerName = "经办人",
                RealHandlerPhone = "13666666666",
                RealContactLocale = true,
                RealIsContacted = true,
                IsOther = true,
                OtherRemark = "其它原因",
                RealCommunicationAddress = "地点地点地点",
                RealCommunicationTime = DateTime.Now,
            },
            Workflow = new NextWorkflowDto
            {
                NextStepCode = "end",
                NextStepName = "归档",
                Opinion = "办理到归档",
                BackToCountersignEnd = false,
                IsSms = false,
                IsForwarded = false,
                HandlerType = EHandlerType.OrgLevel,
                BusinessType = EBusinessType.Department,
                FlowDirection = EFlowDirection.OrgToOrg,
                WorkflowId = order.WorkflowId,
                StepId = stepNextInfo.StepId,
            }
        };
        dataAction?.Invoke(handleDto.Data);
        workflowAction?.Invoke(handleDto.Workflow);
        try
        {
            _orderController.Handle(handleDto).GetAwaiter().GetResult();
        }
        catch (Exception e)
        {
            var msg = e.Message;
            if (msg.Contains("RealtimeService") == false)
            {
                throw;
            }
            // ignore
        }
        return this;
    }

    public OrderServiceMock 办理到二级部门(Action action = null)
    {
        action?.Invoke();
        var stepNextInfo = _orderController.GetNextStepsWithRecommend(CreateOrderOutDto.Id).GetAwaiter().GetResult().ToJson().FromJson<NextStepsDto<NextStepOption>>();
        var stepInfo = stepNextInfo.Steps.FirstOrDefault(m => m.Value == "二级部门");
        var stepOrg = stepInfo.Items.FirstOrDefault(m => m.OrgName == "测试二级部门");

        var order = _orderRepository.Get(CreateOrderOutDto.Id);

        var handleDto = new NextWorkflowDto<OrderHandleFlowDto>
        {
            Data = new OrderHandleFlowDto
            {
                OrderId = CreateOrderOutDto.Id,
            },
            Workflow = new NextWorkflowDto
            {
                NextHandlers = [stepOrg],
                NextStepCode = stepInfo.Key,
                NextStepName = stepInfo.Value,
                Opinion = "办理到二级部门",
                BackToCountersignEnd = false,
                IsSms = false,
                IsForwarded = false,
                HandlerType = EHandlerType.OrgLevel,
                BusinessType = EBusinessType.Department,
                FlowDirection = EFlowDirection.OrgToOrg,
                WorkflowId = order.WorkflowId,
                StepId = stepNextInfo.StepId,
            }
        };
        _orderController.Handle(handleDto).GetAwaiter().GetResult();
        return this;
    }

    public OrderServiceMock 办理一级部门汇总(Action action = null)
    {
        action?.Invoke();
        var stepNextInfo = _orderController.GetNextStepsWithRecommend(CreateOrderOutDto.Id).GetAwaiter().GetResult().ToJson().FromJson<NextStepsDto<NextStepOption>>();
        var stepInfo = stepNextInfo.Steps.FirstOrDefault(m => m.Value == "一级部门汇总");
        var stepOrg = stepInfo.Items.FirstOrDefault(m => m.OrgName == "测试部门");

        var order = _orderRepository.Get(CreateOrderOutDto.Id);

        var handleDto = new NextWorkflowDto<OrderHandleFlowDto>
        {
            Data = new OrderHandleFlowDto
            {
                OrderId = CreateOrderOutDto.Id,
                RealHandlerName = "经办人",
                RealHandlerPhone = "13666666666",
                RealContactLocale = true,
                RealIsContacted = true,
                IsOther = true,
                IsEvasive = true,
                OtherRemark = "其它原因",
                RealCommunicationAddress = "地点地点地点",
                RealCommunicationTime = DateTime.Now
            },
            Workflow = new NextWorkflowDto
            {
                NextHandlers = [stepOrg],
                NextStepCode = stepInfo.Key,
                NextStepName = stepInfo.Value,
                Opinion = "办理到一级部门汇总",
                BackToCountersignEnd = false,
                IsSms = false,
                IsForwarded = false,
                HandlerType = EHandlerType.AssignedUser,
                BusinessType = EBusinessType.Department,
                FlowDirection = EFlowDirection.OrgToOrg,
                StepType = EStepType.Summary,
                WorkflowId = order.WorkflowId,
                StepId = stepNextInfo.StepId,
            }
        };
        _orderController.Handle(handleDto).GetAwaiter().GetResult();
        return this;
    }

    public OrderServiceMock 发布工单(Action action = null, IList<Kv>? snapshotLabels = null)
    {
        action?.Invoke();
        var baseData = _orderController.PublishOrderPageBase(CreateOrderOutDto.Id).GetAwaiter().GetResult();
        var inDto = new PublishOrderDto
        {
            Id = CreateOrderOutDto.Id,
            PublishState = false,
            ArrangeTitle = baseData.OrderTitle,
            ArrangeContent = baseData.Content,
            ArrangeOpinion = baseData.ActualOpinion,
            IdNames = [baseData.ActualHandleOrgName],
            ProPublishState = false,
            Resolve = true,
            SnapshotLabels = snapshotLabels
        };

        _orderController.PublishOrder(inDto).GetAwaiter().GetResult();
        return this;
    }

    public OrderServiceMock 部门审核网格员红包(Action action = null)
    {
        action?.Invoke();
        var baseData = _redPackController.GetRedPackGuiderAuditItems(new SnapshotOrderGuiderAuditItemsInDto(null, null, 0)).GetAwaiter().GetResult();
        var item = baseData.Items.FirstOrDefault(m => m.No == CreateOrderOutDto.No);
        if (item == null)
            throw UserFriendlyException.SameMessage("获取审核红包信息错误, 不存在被测试的对象.");
        var inDto = new UpdateRedPackGuiderAuditInDto
        {
            RedPackAuditId = item.RedPackAuditId,
            Status = ESnapshotSMSStatus.Agree,
            Opinion = "红包审核通过",
        };

        _redPackController.UpdateRedPackGuiderAuditAsync(inDto).GetAwaiter().GetResult();
        return this;
    }

    public OrderServiceMock 部门审核市民红包(Action action = null)
    {
        action?.Invoke();
        var baseData = _redPackController.GetRedPackAuditItems(new SnapshotOrderAuditItemsInDto(null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, 0)).GetAwaiter().GetResult();
        var item = baseData.Items.FirstOrDefault(m => m.No == CreateOrderOutDto.No);
        if (item == null)
            throw UserFriendlyException.SameMessage("获取审核红包信息错误, 不存在被测试的对象.");
        var inDto = new UpdateRedPackAuditInDto
        {
            SMSTemplateId = "",
            IsSendSms = false,
            RedPackAuditId = item.RedPackAuditId,
            Status = ESnapshotSMSStatus.Agree,
            Opinion = "红包审核通过",
        };

        _redPackController.UpdateRedPackAuditAsync(inDto).GetAwaiter().GetResult();
        return this;

    }

    public OrderServiceMock 发送回访短信(Action action = null)
    {
        action?.Invoke();
        var id = _orderVisitRepository.Queryable()
            .Where(m => m.No == CreateOrderOutDto.No)
            .Select(m => m.Id)
            .First();
        var inDto = new VisitSmsInDto
        {
            Ids = [id]
        };
        _orderController.VisitPushSMSAsync(inDto).GetAwaiter().GetResult();
        return this;
    }

    private ApiResponse<FileJson> UploadImage()
    {
        #region 图片
        var base64String = " ";

        #endregion

        byte[] imageBytes = Convert.FromBase64String(base64String);
        var uploadUrl = _systemSettingCacheManager.FileServerUrl + "/file/upload?source=hotline";
        var file = "测试图片" + DateTime.Now.ToString("ss") + ".png";
        var resultJson = UploadFileFromMemory(imageBytes, file, uploadUrl);
        if (resultJson.IsNullOrEmpty()) return new ApiResponse<FileJson>() { Code = -1 };
        var result = resultJson.FromJson<ApiResponse<FileJson>>();
        return result;
    }

    public GuiderSystemInDto GetGuiderSystemInDto(string number)
    {
        List<GuiderSystemInDto> items = [ new GuiderSystemInDto
        {
            ReplyCode = CreateOrderOutDto.No,
            AppealNumber = number,
            ReplyDate = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"),
            ReplyUserName = "18181552753@zgsg",
            ReplyBMName = "瓦市村村民委员会",
            ReplyResultType = "2",
            ReplyISTrue = "1",
            IsRepeat = "0",
            IsHiddenDanger = "1",
            MemberName = "许利洪",
            MemberMobile = "18181552753",
            ReplyContent = "到现场查实，存在安全隐患",
            OrgId = "4828",
            OrgName = "瓦市村民委员会",
            OrgFullName = "四川省/自贡市/沿滩区/永安镇/瓦市村村民委员会",
            DepartmentNo = "510311106206",
            ParentOrgId = "4821",
            ReplyFileList =
                    [
                        "http://10.0.188.11:1234/tqOssManager/getObjectByUri/sichuan/scgrid/jpg/2024/12/5/095020318625.jpg"
                    ]
        },
        new GuiderSystemInDto {
            ReplyCode = CreateOrderOutDto.No,
            AppealNumber = number,
            ReplyDate = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"),
            ReplyUserName = "18015707487@zgsg",
            ReplyBMName = "大岩社区第一网格",
            ReplyResultType = "2",
            ReplyISTrue = "1",
            IsRepeat = "0",
            IsHiddenDanger = "1",
            MemberName = "黄敬",
            MemberMobile = "18015707487",
            ReplyContent = "到现场查实，存在安全隐患",
            OrgId = "138497",
            OrgName = "大岩社区第一网格",
            OrgFullName = "四川省/自贡市/自贡高新区/红旗街道/大岩社区居民委员会/大岩社区第一网格",
            DepartmentNo = "510323004002001",
            ParentOrgId = "137874",
            ReplyFileList =
                    [
                        "http://10.0.188.11:1234/tqOssManager/getObjectByUri/sichuan/scgrid/jpg/2024/12/5/095020318625.jpg"
                    ]
        },
        new GuiderSystemInDto {
            ReplyCode = CreateOrderOutDto.No,
            AppealNumber = number,
            ReplyDate = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"),
            ReplyUserName = "18015707367@zgsg",
            ReplyBMName = "悦景社区第一网格",
            ReplyResultType = "2",
            ReplyISTrue = "1",
            IsRepeat = "0",
            IsHiddenDanger = "0",
            MemberName = "余文惠",
            MemberMobile = "18015707367",
            ReplyContent = "确认情况属实，但是不属于我们管辖。属于市政工程。",
            OrgId = "138563",
            OrgName = "悦景社区第一网格",
            OrgFullName = "四川省/自贡市/自贡高新区/红旗街道/悦景社区居民委员会/悦景社区第一网格",
            DepartmentNo = "510323004004001",
            ParentOrgId = "137875",
            ReplyFileList =
                    [
                        "http://10.0.188.11:1234/tqOssManager/getObjectByUri/sichuan/scgrid/jpg/2024/12/5/095020318625.jpg"
                    ]
        },
        new GuiderSystemInDto {
            ReplyCode = CreateOrderOutDto.No,
            AppealNumber = number,
            ReplyDate = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"),
            ReplyUserName = "18015707408@zgsg",
            ReplyBMName = "大湾社区第一网格",
            ReplyResultType = "2",
            ReplyISTrue = "1",
            IsRepeat = "0",
            IsHiddenDanger = "0",
            MemberName = "邓文文",
            MemberMobile = "15928137497",
            ReplyContent = "网格员到现场核实，情况属实，此地方属于物业处理，已通知物业及时处理。",
            OrgId = "138520",
            OrgName = "大湾社区第一网格",
            OrgFullName = "四川省/自贡市/自贡高新区/红旗街道/大湾社区居民委员会/大湾社区第一网格",
            DepartmentNo = "510323004001001",
            ParentOrgId = "137873",
            ReplyFileList =
                    [
                        "http://10.0.188.11:1234/tqOssManager/getObjectByUri/sichuan/scgrid/jpg/2024/12/5/095020318625.jpg"
                    ]
        },
        new GuiderSystemInDto {
            ReplyCode = CreateOrderOutDto.No,
            AppealNumber = number,
            ReplyDate = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss"),
            ReplyUserName = "18015707443@zgsg",
            ReplyBMName = "明珠社区第一网格",
            ReplyResultType = "2",
            ReplyISTrue = "",
            IsRepeat = "",
            IsHiddenDanger = "",
            MemberName = "周洪英",
            MemberMobile = "15881342458",
            ReplyContent = "现场查看情况属实，属于汇东公园管辖范围",
            OrgId = "138372",
            OrgName = "明珠社区第一网格",
            OrgFullName = "四川省/自贡市/自贡高新区/丹桂街道/明珠社区居民委员会/明珠社区第一网格",
            DepartmentNo = "510323001010001",
            ParentOrgId = "137777",
            ReplyFileList =
                    [
                        "http://10.0.188.11:1234/tqOssManager/getObjectByUri/sichuan/scgrid/jpg/2024/12/5/095020318625.jpg"
                    ]
        }];
        var index = new Random().Next(0, items.Count);
        return items[index];
    }

    private string UploadFileFromMemory(byte[] fileBytes, string fileName, string uploadUrl)
    {
        try
        {
            using HttpClient client = new HttpClient();
            using var multipartContent = new MultipartFormDataContent();
            var fileContent = new ByteArrayContent(fileBytes);
            fileContent.Headers.ContentType = MediaTypeHeaderValue.Parse("image/jpeg");

            multipartContent.Add(fileContent, "fileData", fileName);

            HttpResponseMessage response = client.PostAsync(uploadUrl, multipartContent).GetAwaiter().GetResult();
            response.EnsureSuccessStatusCode();

            var result = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
            return result;

        }
        catch (Exception e)
        {
            var msg = e.Message;
        }
        return string.Empty;
    }

    public OrderServiceMock StepHandle(Func<CreateOrderOutDto, OrderServiceMock, Task> handle)
    {
        handle(CreateOrderOutDto, this).GetAwaiter().GetResult();
        return this;
    }

    public OrderServiceMock StepHandle(Func<CreateOrderOutDto, Task> handle)
    {
        handle(CreateOrderOutDto).GetAwaiter().GetResult();
        return this;
    }


    public OrderServiceMock 办理到工单标注(Action action = null)
    {
        action?.Invoke();
        var stepNextInfo = _orderController.GetNextStepsWithRecommend(CreateOrderOutDto.Id).GetAwaiter().GetResult().ToJson().FromJson<NextStepsDto<NextStepOption>>();
        var stepInfo = stepNextInfo.Steps.FirstOrDefault(m => m.Value == "工单标记");
        var stepOrg = stepInfo.Items.FirstOrDefault(m => m.Username == "单元测试班长");

        var handleDto = new NextWorkflowDto<OrderHandleFlowDto>
        {
            Data = new OrderHandleFlowDto
            {
                OrderId = CreateOrderOutDto.Id,
                IsSafetyDepartment = true,
            },
            Workflow = new NextWorkflowDto
            {
                NextHandlers = [stepOrg],
                NextStepCode = stepInfo.Key,
                NextStepName = stepInfo.Value,
                Opinion = "办理到工单标记意见",
                BackToCountersignEnd = false,
                IsSms = false,
                IsForwarded = false,
                HandlerType = EHandlerType.OrgLevel,
                BusinessType = EBusinessType.Send,
                FlowDirection = EFlowDirection.CenterToCenter,
            }
        };
        _orderController.Handle(handleDto).GetAwaiter().GetResult();
        return this;
    }

    public OrderServiceMock 部门审核特殊红包(Action action, double? approvedAmount = 0)
    {
        action?.Invoke();
        var baseData = _redPackController.GetRedPackSpecialAuditItems(new SnapshotOrderAuditItemsInDto(null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, 0)).GetAwaiter().GetResult();
        var item = baseData.Items.FirstOrDefault(m => m.No == CreateOrderOutDto.No);
        var basedata = _systemDicDataCacheManager.SnapshotRedPackSpecialType.First();
        if (item == null)
            throw UserFriendlyException.SameMessage("获取特殊审核红包信息错误, 不存在被测试的对象.");
        var inDto = new UpdateRedPackSpecialAuditInDto
        {
            AuditTypeId = basedata.Id,
            ApprovedAmount = approvedAmount,
            RedPackAuditId = item.RedPackAuditId,
            Status = ERedPackAuditStatus.Agree,
            Opinion = "红包审核通过",
        };

        _redPackController.UpdateRedPackSpecialAuditAsync(inDto).GetAwaiter().GetResult();
        return this;

    }

    public string 申请延期(Action action = null)
    {
        action?.Invoke();
        var options = _orderController.GetDelayFlowStartOptions().Result as NextStepsDto<NextStepOption>;
        var step = options.Steps.First();
        var req = new StartWorkflowDto<ApplyDelayDto>
        {
            Workflow = new BasicWorkflowDto
            {
                NextStepCode = step.Key,
                NextStepName = step.Value,
                NextHandlers = new List<StepAssignInfo> { step.Items.First() },
                Opinion = "单元测试延期申请",
                FlowDirection = step.FlowDirection,
                BackToCountersignEnd = step.BackToCountersignEnd,
                HandlerType = step.HandlerType,
                BusinessType = step.BusinessType,
            },
            Data = new ApplyDelayDto
            {
                OrderId = CreateOrderOutDto.Id,
                DelayNum = 3,
                DelayReason = "单元测试延期理由",
                DelayUnit = ETimeType.WorkDay,
                Files = new()
            }
        };

        return _orderController.ApplyDelay(req).GetAwaiter().GetResult();

    }
}
