using Hotline.CallCenter.Calls;
using Hotline.FlowEngine.Workflows;
using Hotline.Settings.Hotspots;
using Hotline.Share.Dtos.File;
using Hotline.Share.Enums.FlowEngine;
using Hotline.Share.Enums.Order;
using Hotline.Share.Enums.Settings;
using Hotline.Users;
using SqlSugar;
using System.ComponentModel;
using XF.Domain.Exceptions;
using XF.Domain.Extensions;
using XF.Domain.Repository;

namespace Hotline.Orders
{
    /// <summary>
    /// 工单
    /// </summary>
    [Description("工单")]
    [SugarIndex("unique_order_no", nameof(Order.No), OrderByType.Desc, true)]
    [SugarIndex("index_order_creationtime", nameof(Order.CreationTime), OrderByType.Asc)]
    [SugarIndex("index_order_startTime", nameof(Order.StartTime), OrderByType.Asc)]
    public partial class Order : PositionWorkflowEntity
    {
        public Order()
        {
            //HotspotCodeLv1 ??= HotspotCode?[..2];
        }

        /// <summary>
        /// 第一次评价结果
        /// </summary>
        public string? FirstVisitResult { get; set; }

        public string? FirstVisitResultCode { get; set; }

        #region 来电信息

        /// <summary>
        /// 来源渠道（电话、网站、APP等）
        /// </summary>
        public string? SourceChannel { get; set; }

        public string? SourceChannelCode { get; set; }

        /// <summary>
        /// 渠道为电话时，此字段存在（Call.Id）
        /// </summary>
        public string? CallId { get; set; }


        /// <summary>
        /// 来电归属地
        /// </summary>
        public string? CallAddress { get; set; }

        /// <summary>
        /// 来电号码
        /// </summary>
        public string? FromPhone { get; set; }

        /// <summary>
        /// 转接号码（转接来源）
        /// </summary>
        public string? TransferPhone { get; set; }

        /// <summary>
        /// 来电/信人姓名
        /// </summary>
        public string? FromName { get; set; }

        /// <summary>
        /// 来电/信人性别
        /// </summary>
        public EGender FromGender { get; set; }

        /// <summary>
        /// 来电/信人身份
        /// </summary>
        public EIdentityType? IdentityType { get; set; }

        /// <summary>
        /// 证件类型
        /// </summary>
        public string? LicenceTypeCode { get; set; }

        public string? LicenceType { get; set; }

        /// <summary>
        /// 证件号码
        /// </summary>
        public string? LicenceNo { get; set; }

        /// <summary>
        /// 年龄段
        /// </summary>
        public string? AgeRangeCode { get; set; }

        public string? AgeRange { get; set; }

        /// <summary>
        /// 联系电话
        /// </summary>
        [SugarColumn(ColumnDescription = "联系电话", IsNullable = true)]
        public string? Contact { get; set; }

        [SugarColumn(ColumnDescription = "联系电话脱敏", IsNullable = true)]
        public string? ContactMask { get; set; }

        /// <summary>
        /// 是否接受短信，勾选校验手机号
        /// </summary>
        public bool AcceptSms { get; set; }

        /// <summary>
        /// 是否已发送短信
        /// </summary>
        public bool SmsSended { get; set; }

        /// <summary>
        /// 是否保密
        /// </summary>
        public bool IsSecret { get; set; }

        /// <summary>
        /// 工作单位(当“来电/信人身份”为“企业”时必填，其他情况非必填)
        /// </summary>
        [SugarColumn(ColumnDescription = "工作单位", IsNullable = true)]
        public string? Company { get; set; }

        #endregion

        #region 诉求信息

        /// <summary>
        /// 受理类型
        /// </summary>
        public string? AcceptType { get; set; }

        public string? AcceptTypeCode { get; set; }

        public string Title { get; set; }

        /// <summary>
        /// 工单标签（自贡）
        /// </summary>
        public string? OrderTag { get; set; }
        public string? OrderTagCode { get; set; }

        #region 热点

        /// <summary>
        /// 热点
        /// </summary>
        public string? HotspotId { get; set; }

        //public string? HotspotCode { get; set; }
        //public string? HotspotCodeLv1 { get; set; }

        public string? HotspotName { get; set; }

        public string? HotspotSpliceName { get; set; }

        /// <summary>
        /// 外部数据（为前端提供级联功能）
        /// </summary>
        public string? HotspotExternal { get; set; }

        #endregion

        #region 事件分类

        public string? EventCategoryId { get; set; }
        public string? EventCategoryName { get; set; }
        public string? EventCategorySpliceName { get; set; }
        public string? EventCategoryExternal { get; set; }

        #endregion

        /// <summary>
        /// 事发时间
        /// </summary>
        public DateTime? IncidentTime { get; set; }

        /// <summary>
        /// 事件目的
        /// </summary>
        public string? IncidentPurpose { get; set; }

        /// <summary>
        /// 重复工单Id
        /// </summary>
        [SugarColumn(ColumnDescription = "重复工单Id", ColumnDataType = "json", IsJson = true)]
        public List<string>? DuplicateIds { get; set; }

        /// <summary>
        /// 推送分类
        /// </summary>
        public string? PushTypeCode { get; set; }

        public string? PushType { get; set; }

        /// <summary>
        /// 附件
        /// </summary>
        [SugarColumn(ColumnDataType = "json", IsJson = true)]
        public List<FileDto>? Additions { get; set; } = new();

        /// <summary>
        /// 诉求内容
        /// </summary>
        [SugarColumn(ColumnDataType = "varchar(8000)")]
        public string Content { get; set; }

        #endregion

        #region 工单属性

        /// <summary>
        /// 工单状态
        /// </summary>
        public EOrderStatus Status { get; set; }

        /// <summary>
        /// 过期状态 //todo 延迟消息更新此字段
        /// </summary>
        public EExpiredStatus ExpiredStatus { get; set; }

        /// <summary>
        /// 来源，区分省平台或110等其他平台同步过来的工单
        /// </summary>
        public ESource Source { get; set; }

        /// <summary>
        /// 处理方式（直办、交办）
        /// </summary>
        public EProcessType ProcessType { get; set; } = EProcessType.Zhiban;

        ///// <summary>
        ///// 进展情况
        ///// </summary>
        //[SugarColumn(DefaultValue = "0")]
        //public EProgress Progress { get; set; }

        /// <summary>
        /// 是否公开
        /// </summary>
        public bool IsPublicity { get; set; }

        /// <summary>
        /// 是否为省工单（省派发工单非政民互动直派的为省工单）
        /// </summary>
        public bool IsProvince { get; set; }

        /// <summary>
        /// 工单编码（20220101000001）
        /// </summary>
        public string? No { get; set; }

        /// <summary>
        /// 是否已撤销
        /// </summary>
        public bool IsCancel { get; set; }

        /// <summary>
        /// 市民查询密码
        /// </summary>
        public string? Password { get; set; }

        /// <summary>
        /// 企业名称
        /// </summary>
        public string? EnterpriseName { get; set; }

        /// <summary>
        /// 企业Code
        /// </summary>
        public string? EnterpriseCode { get; set; }


        /// <summary>
        /// 专班名称
        /// </summary>
        public string? ZhuanBanMingCheng { get; set; }

        /// <summary>
        /// 专班Code
        /// </summary>
        public string? ZhuanBanCode { get; set; }

        #endregion

        #region 流程信息

        /// <summary>
        /// 工单开始时间(受理/接办时间=流程开启时间)
        /// </summary>
        public DateTime? StartTime { get; set; }

        /// <summary>
        /// 超期时间（期满时间）
        /// </summary>
        public DateTime? ExpiredTime { get; set; }

        /// <summary>
        /// 即将超期时间
        /// </summary>
        public DateTime? NearlyExpiredTime { get; set; }


        /// <summary>
        /// 即将超期时间第一级
        /// </summary>
        public DateTime? NearlyExpiredTimeOne { get; set; }

        /// <summary>
        /// 交办时间(中心交部门办理时间)
        /// </summary>
        public DateTime? CenterToOrgTime { get; set; }

        /// <summary>
        /// 交办意见
        /// </summary>
        [SugarColumn(Length = 8000)]
        public string? CenterToOrgOpinion { get; set; }

        /// <summary>
        /// 交办人
        /// </summary>
        public string? CenterToOrgHandlerId { get; set; }
        public string? CenterToOrgHandlerName { get; set; }

        /// <summary>
        /// 归档时间（暂为流程结束时间，因流程结束自动归档）
        /// </summary>
        public DateTime? FiledTime { get; set; }

        /// <summary>
        /// 办结时长（秒）
        /// 办结时间-交办时间
        /// </summary>
        public double? HandleDuration { get; set; }

        /// <summary>
        /// 办结工作日时长（秒）
        /// </summary>
        public double? HandleDurationWorkday { get; set; }

        /// <summary>
        /// 办结时长（秒）归档时间-受理时间（工单创建时间）
        /// </summary>
        public double? CreationTimeHandleDuration { get; set; }

        /// <summary>
        /// 办结工作日时长（秒）归档时间-受理时间（工单创建时间）
        /// </summary>
        public double? CreationTimeHandleDurationWorkday { get; set; }

        /// <summary>
        /// 办结时长（秒） 归档时间-派单时间（中心到部门时间）
        /// </summary>
        public double? CenterToOrgHandleDuration { get; set; }

        /// <summary>
        /// 办结工作日时长（秒）归档时间-派单时间（中心到部门时间）
        /// </summary>
        public double? CenterToOrgHandleDurationWorkday { get; set; }

        /// <summary>
        /// 归档时长（秒）
        /// 归档时间-交办时间
        /// </summary>
        public double? FileDuration { get; set; }

        /// <summary>
        /// 归档工作时长（秒）
        /// </summary>
        public double? FileDurationWorkday { get; set; }

        /// <summary>
        /// 全流程时长（秒）
        /// 归档时间-创建时间
        /// </summary>
        public double? AllDuration { get; set; }

        public double? AllDurationWorkday { get; set; }

        /// <summary>
        /// 办理时间限制(如：24小时、7个工作日)
        /// </summary>
        public string? TimeLimit { get; set; }

        public int? TimeLimitCount { get; set; }

        public ETimeType? TimeLimitUnit { get; set; }

        #region 会签实际办理对象

        [SugarColumn(ColumnDataType = "json", IsJson = true)]
        public List<string>? CsActualHandleOrgIds { get; set; }

        [SugarColumn(ColumnDataType = "json", IsJson = true)]
        public List<string>? CsActualHandleUserIds { get; set; }

        #endregion

        #region 实际办理信息（节点，部门，意见）

        public string? ActualHandleStepId { get; set; }

        /// <summary>
        /// 实际办理节点code（会签状态此字段保存最外层会签发起节点code）
        /// </summary>
        public string? ActualHandleStepCode { get; set; }

        /// <summary>
        /// 实际办理节点名称（会签状态此字段保存最外层会签发起节点名称）
        /// </summary>
        public string? ActualHandleStepName { get; set; }

        /// <summary>
        /// 到达实际办理节点时间（stepBox创建时间）
        /// </summary>
        public DateTime? ActualHandleStepCreateTime { get; set; }

        /// <summary>
        /// 实际办理节点签收时间
        /// </summary>
        public DateTime? ActualHandleStepAcceptTime { get; set; }

        /// <summary>
        /// 实际办理时间
        /// </summary>
        public DateTime? ActualHandleTime { get; set; }

        /// <summary>
        /// 实际办理人id
        /// </summary>
        public string? ActualHandlerId { get; set; }

        /// <summary>
        /// 实际办理人名称
        /// </summary>
        public string? ActualHandlerName { get; set; }

        /// <summary>
        /// 实际办理部门名称
        /// </summary>
        public string? ActualHandleOrgName { get; set; }

        /// <summary>
        /// 实际办理部门编码
        /// </summary>
        public string? ActualHandleOrgCode { get; set; }

        /// <summary>
        /// 实际办理部门行政区划编码
        /// </summary>
        public string? ActualHandleOrgAreaCode { get; set; }

        /// <summary>
        /// 实际办理部门行政区划名称
        /// </summary>
        public string? ActualHandleOrgAreaName { get; set; }

        ///// <summary>
        ///// 实际办理对象(会签停留在顶级发起节点)
        ///// 办理时选择的办理对象，可能是部门也可能是用户
        ///// </summary>
        //public string? ActualHandlerValue { get; set; }
        //public string? ActualHandlerKey { get; set; }
        //public EHandlerType? ActualHandlerType { get; set; }

        /// <summary>
        /// 实际办理意见（办理中...or 最终办理意见）
        /// </summary>
        [SugarColumn(Length = 8000)]
        public string ActualOpinion { get; set; } = "办理中...";

        /// <summary>
        /// 真实办理人姓名（手动填写）
        /// </summary>
        public string? RealHandlerName { get; set; }

        /// <summary>
        /// 真实办理人电话（手动填写）
        /// </summary>
        public string? RealHandlerPhone { get; set; }

        /// <summary>
        /// 沟通方式（手动填写）
        /// </summary>
        public ERealCommunicationMode? RealCommunicationMode { get; set; }

        /// <summary>
        /// 沟通时间（手动填写）
        /// </summary>
        public DateTime? RealCommunicationTime { get; set; }

        /// <summary>
        /// 沟通地点（手动填写）
        /// </summary>
        public string? RealCommunicationAddress { get; set; }

        /// <summary>
        /// 已与市民沟通
        /// </summary>
        public bool? RealIsContacted { get; set; }

        /// <summary>
        /// 已与市民现场沟通
        /// </summary>
        public bool? RealContactLocale { get; set; }

        #endregion

        #region 当前办理节点信息(指派时赋值)

        public string? CurrentStepId { get; set; }

        /// <summary>
        /// 当前办理节点code（非会签：当前被指派节点，会签：会签发起节点）
        /// </summary>
        public string? CurrentStepCode { get; set; }

        /// <summary>
        /// 当前节点名称
        /// </summary>
        public string? CurrentStepName { get; set; }

        /// <summary>
        /// 到达当前节点时间
        /// </summary>
        public DateTime? CurrentStepCreateTime { get; set; }

        /// <summary>
        /// 当前办理节点签收时间
        /// </summary>
        public DateTime? CurrentStepAcceptTime { get; set; }

        /// <summary>
        /// 当前办理时间
        /// </summary>
        public DateTime? CurrentHandleTime { get; set; }

        /// <summary>
        /// 当前办理人id
        /// </summary>
        public string? CurrentHandlerId { get; set; }

        /// <summary>
        /// 当前办理人名称
        /// </summary>
        public string? CurrentHandlerName { get; set; }

        /// <summary>
        /// 当前办理部门名称
        /// </summary>
        public string? CurrentHandleOrgName { get; set; }

        /// <summary>
        /// 当前办理部门编码
        /// </summary>
        public string? CurrentHandleOrgId { get; set; }

        /// <summary>
        /// 当前办理部门等级
        /// </summary>
        public int? CurrentHandleOrgLevel { get; set; }

        /// <summary>
        /// 当前办理部门行政区划编码
        /// </summary>
        public string? CurrentHandleOrgAreaCode { get; set; }

        /// <summary>
        /// 当前办理部门行政区划名称
        /// </summary>
        public string? CurrentHandleOrgAreaName { get; set; }

        #endregion

        #region 一级部门

        /// <summary>
        /// 一级部门code
        /// </summary>
        [SugarColumn(IsNullable = true)]
        public string? OrgLevelOneCode { get; set; }

        /// <summary>
        /// 一级部门名称
        /// </summary>
        [SugarColumn(IsNullable = true)]
        public string? OrgLevelOneName { get; set; }

        #endregion

        #region 二级部门

        /// <summary>
        /// 二级部门code
        /// </summary>
        [SugarColumn(IsNullable = true)]
        public string? OrgLevelTwoCode { get; set; }
        /// <summary>
        /// 二级部门名称
        /// </summary>
        [SugarColumn(IsNullable = true)]
        public string? OrgLevelTwoName { get; set; }

        #endregion

        #region 受理人(开启流程的话务员)

        /// <summary>
        /// 受理人id
        /// </summary>
        public string? AcceptorId { get; set; }

        /// <summary>
        /// 受理人名称
        /// </summary>
        public string? AcceptorName { get; set; }

        /// <summary>
        /// 受理人工号
        /// </summary>
        public string? AcceptorStaffNo { get; set; }

        /// <summary>
        /// 受理人部门编码
        /// </summary>
        public string? AcceptorOrgCode { get; set; }

        /// <summary>
        /// 受理人部门名称
        /// </summary>
        public string? AcceptorOrgName { get; set; }

        #endregion

        #region 派单人

        /// <summary>
        /// 派单次数
        /// </summary>
        public int? SendOrderNumber { get; set; } = 0;
        #endregion

        /// <summary>
        /// 会签类型
        /// </summary>
        public ECounterSignType? CounterSignType { get; set; }

        #region 签收

        /// <summary>
        /// 签收人id
        /// </summary>
        public string? SignerId { get; set; }

        /// <summary>
        /// 签收人名称
        /// </summary>
        public string? SignerName { get; set; }

        #endregion

        #region 归档冗余字段

        /// <summary>
        /// 归档人名称
        /// </summary>
        public string? FileUserName { get; set; }
        /// <summary>
        /// 归档人ID
        /// </summary>
        public string? FileUserId { get; set; }

        /// <summary>
        /// 归档人部门Id
        /// </summary>
        public string? FileUserOrgId { get; set; }

        /// <summary>
        /// 归档人部门名称
        /// </summary>
        public string? FileUserOrgName { get; set; }

        /// <summary>
        /// 归档人部门是否属于中心
        /// </summary>
        public bool? FileOrgIsCenter { get; set; }

        /// <summary>
        /// 归档人类型
        /// </summary>
        public EFileUserType? FileUserRole { get; set; }

        /// <summary>
        /// 归档意见
        /// </summary>
        [SugarColumn(ColumnDataType = "varchar(8000)")]
        public string? FileOpinion { get; set; }



        #endregion

        #endregion

        #region 省工单字段

        /// <summary>
        /// 省期满时间（省工单才有）
        /// </summary>
        public DateTime? ExpiredTimeProvince { get; set; }

        /// <summary>
        /// 同步省工单编号和省上传下来的工单都用这个字段
        /// </summary>
        public string? ProvinceNo { get; set; }

        /// <summary>
        /// 外部工单唯一标识
        /// </summary>
        public string? ExternalId { get; set; }

        /// <summary>
        /// 工单标签
        /// </summary>
        public string? TagNames { get; set; }

        #endregion

        #region 附件冗余

        [SugarColumn(ColumnDataType = "json", IsJson = true, IsNullable = true)]
        public List<FileJson>? FileJson { get; set; }

        #endregion

        #region 市州工单互转
        /// <summary>
        /// 是否转发
        /// </summary>
        public bool? Transpond { get; set; }

        /// <summary>
        /// 转发市州Id
        /// </summary>
        public string? TranspondCityId { get; set; }

        /// <summary>
        /// 转发市州名称
        /// </summary>
        public string? TranspondCityName { get; set; }

        /// <summary>
        /// 转发市州Value
        /// </summary>
        public string? TranspondCityValue { get; set; }
        #endregion

        #region 重办

        /// <summary>
        /// 重办次数
        /// </summary>
        public int? ReTransactNum { get; set; }
        #endregion

        /// <summary>
        /// 敏感标签
        /// </summary>
        [SugarColumn(ColumnDataType = "json", IsJson = true, IsNullable = true)]
        public List<string>? Sensitive { get; set; }

        /// <summary>
        /// 是否行政执法类
        /// </summary>
        public bool? IsEnforcementOrder { get; set; }

        /// <summary>
        /// 形式主义工单
        /// </summary>
        [SugarColumn(DefaultValue = "f")]
        public bool IsFormalistWorkOrder { get; set; }

        /// <summary>
        /// 敏感类工单
        /// </summary>
        [SugarColumn(DefaultValue = "f")]
        public bool IsSensitiveWorkOrders { get; set; }

        /// <summary>
        /// 24小时办结
        /// </summary>
        [SugarColumn(DefaultValue = "f")]
        public bool Is24HoursComplete { get; set; }

        /// <summary>
        /// 部门是否解决
        /// </summary>
        [SugarColumn(DefaultValue = "f")]
        public bool IsResolved { get; set; }

        /// <summary>
        /// 是否紧急
        /// </summary>
        [SugarColumn(DefaultValue = "f")]
        public bool IsUrgent { get; set; }

        /// <summary>
        /// 重点关注事件,保存前端选择，用于返回前端数据
        /// </summary>
        public string? FocusOnEvents { get; set; }

        /// <summary>
        /// 待发布人Id
        /// </summary>
        public string? WaitForPublisherId { get; set; }

        /// <summary>
        /// 是否政民互动公开
        /// </summary>
        [SugarColumn(DefaultValue = "f")]
        public bool IsProvinceZmhd { get; set; }

        /// <summary>
        /// 初审人姓名
        /// </summary>
        [SugarColumn(ColumnDescription = "初审人姓名")]
        public string? AuditFirstName { get; set; }

        /// <summary>
        /// 初审时间
        /// </summary>
        [SugarColumn(ColumnDescription = "初审时间")]
        public DateTime? AuditFirstTime { get; set; }

        /// <summary>
        /// 政民互动公开ID
        /// </summary>
        [SugarColumn(ColumnDescription = "政民互动公开ID")]
        public string? OrderProvinceZmhdId { get; set; }

		/// <summary>
		/// 超期部门
		/// </summary>
		[SugarColumn(IsIgnore = true)]
		public string? DaysOverdueOrgName { get; set; }
	}

	public partial class Order
    {
        /// <summary>
        /// 受理人
        /// </summary>
        [Navigate(NavigateType.OneToOne, nameof(AcceptorId))]
        public User Acceptor { get; set; }

        /// <summary>
        /// 热点
        /// </summary>
        [Navigate(NavigateType.OneToOne, nameof(HotspotId))]
        public Hotspot Hotspot { get; set; }

        /// <summary>
        /// 办理流程
        /// </summary>
        [Navigate(NavigateType.OneToOne, nameof(WorkflowId))]
        public Workflow Workflow { get; set; }

        /// <summary>
        /// 工单扩展信息
        /// </summary>
        [Navigate(NavigateType.OneToOne, nameof(Id))]
        public OrderExtension OrderExtension { get; set; }

        /// <summary>
        /// 已发布工单
        /// </summary>
        [Navigate(NavigateType.OneToOne, nameof(Id), nameof(Orders.OrderPublish.OrderId))]
        public OrderPublish OrderPublish { get; set; }

        /// <summary>
        /// 已回访工单
        /// </summary>
        [Navigate(NavigateType.OneToMany, nameof(OrderVisit.OrderId))]
        public List<OrderVisit> OrderVisits { get; set; }

        /// <summary>
        /// 甄别
        /// </summary>
        [Navigate(NavigateType.OneToMany, nameof(OrderScreen.OrderId))]
        public List<OrderScreen> OrderScreens { get; set; }

        /// <summary>
        /// 
        /// </summary>
        [Navigate(NavigateType.OneToMany, nameof(OrderSpecial.OrderId))]
        public List<OrderSpecial> OrderSpecials { get; set; }

        /// <summary>
        /// 延期
        /// </summary>
        [Navigate(NavigateType.OneToMany, nameof(OrderDelay.OrderId))]
        public List<OrderDelay> OrderDelays { get; set; }

        /// <summary>
        /// 工单补充
        /// </summary>
        [Navigate(NavigateType.OneToMany, nameof(OrderComplement.OrderId))]
        public List<OrderComplement> OrderComplements { get; set; }

        /// <summary>
        /// 通话记录
        /// </summary>
        //[Navigate(NavigateType.OneToOne, nameof(CallId), nameof(TrCallRecord.CallAccept))] //由CallAccept改成OtherAccept
        [Navigate(NavigateType.OneToOne, nameof(CallId), nameof(TrCallRecord.OtherAccept))]
        public TrCallRecord CallRecord { get; set; }


        #region Method

        public void Cancel()
        {
            IsCancel = true;
        }

        public void Redo()
        {
            Status = EOrderStatus.Handling;
            ExpiredStatus = EExpiredStatus.Normal;
        }

        public void CheckIfFiled()
        {
            if (Status is EOrderStatus.Filed)
                throw UserFriendlyException.SameMessage("工单已归档");
        }

        public void Init()
        {
            if (!string.IsNullOrEmpty(Contact))
                ContactMask = Contact.MaskPhoneNumber();
            Status = EOrderStatus.WaitForAccept;
            ExpiredStatus = EExpiredStatus.Normal;
        }

        public void AutoAccept(string userId, string? userName, string? staffNo)
        {
            AcceptorId = userId;
            AcceptorName = userName;
            AcceptorStaffNo = staffNo;
        }

        /// <summary>
        /// 开始工单办理流程
        /// </summary>
        public void StartManageFlow() => Status = EOrderStatus.Handling;

        /// <summary>
        /// 更新工单办理中状态
        /// </summary>
        public void UpdateHandlingStatus(bool isInCountersign) =>
            Status = isInCountersign && Status < EOrderStatus.Filed ? EOrderStatus.Countersigning : EOrderStatus.Handling;

        /// <summary>
        /// 归档
        /// </summary>
        public void File(DateTime filedTime, double handleDurationWorkday, double fileDurationWorkday, double allDurationWorkday
            , double creationTimeHandleDurationWorkday, double centerToOrgHandleDurationWorkday)
        {
            if (Status is EOrderStatus.Filed) return;
            Status = EOrderStatus.Filed;
            FiledTime = filedTime;
            HandleDurationWorkday = handleDurationWorkday;
            FileDurationWorkday = fileDurationWorkday;
            AllDurationWorkday = allDurationWorkday;
            CreationTimeHandleDurationWorkday = creationTimeHandleDurationWorkday;
            CenterToOrgHandleDurationWorkday = centerToOrgHandleDurationWorkday;

            //计算实际办结时长
            SetHandleDuration();
            SetFileDuration();
            SetAllDuration();
            SetCreationTimeHandleDurationWorkday();
            SetCenterToOrgHandleDurationWorkday();
        }

        /// <summary>
        /// 特提之后 归档信息清空
        /// </summary>
        public void FileEmpty() {
            FiledTime = null;
			HandleDurationWorkday = 0;
            HandleDuration = 0;
			FileDurationWorkday = 0;
            FileDuration = 0;
			AllDurationWorkday = 0;
            AllDuration = 0;
			CreationTimeHandleDurationWorkday = 0;
            CreationTimeHandleDuration = 0;
			CenterToOrgHandleDurationWorkday = 0;
            CenterToOrgHandleDuration = 0;
		}

		/// <summary>
		/// 发布
		/// </summary>
		/// <param name="isPublicity"></param>
		public void Publish(bool isPublicity)
        {
            //Progress = EProgress.Published;
            Status = EOrderStatus.Published;
            IsPublicity = isPublicity;
        }

        /// <summary>
        /// 已回访
        /// </summary>
        public void Visited(string resultCode, string result)
        {
            if (string.IsNullOrEmpty(resultCode) || string.IsNullOrEmpty(result))
                return;
            if (!string.IsNullOrEmpty(FirstVisitResultCode)) return;
            FirstVisitResultCode = resultCode;
            FirstVisitResult = result;

            //Progress = EProgress.Visited;
            Status = EOrderStatus.Visited;
        }

        public void CenterToOrg(string timelimit, int timelimitCount, ETimeType timilimitUnit,
            DateTime expiredTime, DateTime nearlyExpiredTime,DateTime nearlyExpiredTimeOne,
            string opinion, string handlerId, string handlerName,
            bool canUpdateOrderSender)
        {
            ProcessType = EProcessType.Jiaoban;
            TimeLimit = timelimit;
            TimeLimitCount = timelimitCount;
            TimeLimitUnit = timilimitUnit;
            ExpiredTime = expiredTime;
            if (CenterToOrgTime is null || canUpdateOrderSender)
            {
                CenterToOrgTime = DateTime.Now;
                CenterToOrgOpinion = opinion;
                CenterToOrgHandlerId = handlerId;
                CenterToOrgHandlerName = handlerName;
            }
            NearlyExpiredTime = nearlyExpiredTime;
            NearlyExpiredTimeOne = nearlyExpiredTimeOne;
            SendOrderNumber += 1;

            if (string.IsNullOrEmpty(WaitForPublisherId))
                WaitForPublisherId = handlerId;
        }

        public void OrgToCenter(string timelimit, int timelimitCount, ETimeType timilimitUnit, DateTime expiredTime, DateTime nearlyExpiredTime,DateTime nearlyExpiredTimeOne)
        {
            ProcessType = EProcessType.Zhiban;
            TimeLimit = timelimit;
            TimeLimitCount = timelimitCount;
            TimeLimitUnit = timilimitUnit;
            ExpiredTime = expiredTime;
            NearlyExpiredTime = nearlyExpiredTime;
            NearlyExpiredTimeOne = nearlyExpiredTimeOne;
            CenterToOrgTime = null;
            CenterToOrgOpinion = null;
            CenterToOrgHandlerId = null;
            CenterToOrgHandlerName = null;
        }

        public void CenterToCenter(string timelimit, int timelimitCount, ETimeType timilimitUnit, DateTime expiredTime, DateTime nearlyExpiredTime, DateTime nearlyExpiredTimeOne)
        {
            TimeLimit = timelimit;
            TimeLimitCount = timelimitCount;
            TimeLimitUnit = timilimitUnit;
            ExpiredTime = expiredTime;
            NearlyExpiredTime = nearlyExpiredTime;
            NearlyExpiredTimeOne = nearlyExpiredTimeOne;
        }

        public void SetHandleDuration()
        {
            if (!ActualHandleTime.HasValue) return;
            if (!CenterToOrgTime.HasValue) return;
            HandleDuration = Math.Round((ActualHandleTime - CenterToOrgTime).Value.TotalSeconds);
        }

        public void SetAllDuration()
        {
            if (!FiledTime.HasValue) return;
            if (!StartTime.HasValue) return;
            AllDuration = Math.Round((FiledTime - StartTime).Value.TotalSeconds);
        }

        public void SetFileDuration()
        {
            if (!FiledTime.HasValue) return;
            if (!CenterToOrgTime.HasValue) return;
            FileDuration = Math.Round((FiledTime - CenterToOrgTime).Value.TotalSeconds);
        }

        /// <summary>
        ///  办结时长（秒） 归档时间-受理时间（工单创建时间）
        /// </summary>
        public void SetCreationTimeHandleDurationWorkday()
        {
            if (!FiledTime.HasValue)
                CreationTimeHandleDuration = 0;
            else
            {
                var count = Math.Round((FiledTime - CreationTime).Value.TotalSeconds);
                CreationTimeHandleDuration = count <= 0 ? 1 : count;
            }

        }

        /// <summary>
        ///  办结时长（秒） 归档时间-派单时间（工单创建时间）
        /// </summary>
        public void SetCenterToOrgHandleDurationWorkday()
        {
            if (FiledTime.HasValue && CenterToOrgTime.HasValue)
            {
                var count = Math.Round((FiledTime - CenterToOrgTime).Value.TotalSeconds);
                CenterToOrgHandleDuration = count <= 0 ? 1 : count;
            }
            else
                CenterToOrgHandleDuration = 0;
        }

        /// <summary>
        /// 是否已签收
        /// </summary>
        public bool IsSigned() => !string.IsNullOrEmpty(SignerId);

        /// <summary>
        /// 签收
        /// </summary>
        public void Sign(string userId, string userName)
        {
            if (string.IsNullOrEmpty(SignerId))
            {
                SignerId = userId;
                SignerName = userName;
            }
        }

        ///// <summary>
        ///// 返回未签收状态
        ///// </summary>
        //public void BackToUnsign()
        //{
        //    SignerId = string.Empty;
        //    SignerName = string.Empty;
        //}

        #endregion
    }

    public class UnsignedOrder
    {
        public Order Order { get; set; }

        public WorkflowStep WorkflowStep { get; set; }
    }
}