diff --git a/AndroidPDACommand.csproj b/AndroidPDACommand.csproj index 5a2fa6713b59c994ffe6bc1f1a06aebe706b4949..06ad00e44f0a2bb5616559a81d7fe1901eb75f04 100644 --- a/AndroidPDACommand.csproj +++ b/AndroidPDACommand.csproj @@ -1,76 +1,38 @@ - - - + - Debug - AnyCPU - {8414FB54-B60D-4F9A-9505-B5E0B2D86C43} + net8.0-windows Library - Properties AndroidPDACommand AndroidPDACommand - v4.7.2 - 512 SAK SAK SAK SAK - true + true + true + true + false + false + false + false + bin\ true full false - bin\ DEBUG;TRACE prompt 4 - MinimumRecommendedRules.ruleset pdbonly true - bin\ TRACE prompt 4 - - - false - - - D:\ForguncyOtherVersion\8.0.6.0\Website\designerBin\Forguncy.Commands.dll - - - D:\ForguncyOtherVersion\8.0.6.0\Website\designerBin\Forguncy.Commands.Design.dll - - - D:\ForguncyOtherVersion\8.0.6.0\Website\designerBin\GrapeCity.Forguncy.Plugin.dll - - - False - D:\ForguncyOtherVersion\8.0.6.0\Website\bin\GrapeCity.Forguncy.ServerApi.dll - - - packages\Jiguang.JPush.1.2.5\lib\net45\Jiguang.JPush.dll - - - packages\Newtonsoft.Json.13.0.3\lib\net45\Newtonsoft.Json.dll - - - - - - - - - - - - - @@ -87,6 +49,12 @@ + + + + + + @@ -119,6 +87,7 @@ + @@ -143,77 +112,75 @@ - + + + + + D:\Forguncy 12\WebSite\designerBin\Forguncy.Commands.dll + False + + + D:\Forguncy 12\WebSite\designerBin\Forguncy.Commands.Design.dll + False + + + D:\Forguncy 12\WebSite\designerBin\GrapeCity.Forguncy.Plugin.dll + False + + + D:\Forguncy 12\WebSite\bin\GrapeCity.Forguncy.ServerApi.dll + False + + + + + - + PreserveNewest - - - + PreserveNewest - - + + PreserveNewest + + Always - - - + PreserveNewest + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - "D:\ForguncyCode\puglin\PluginTools\PluginPackageTool\bin\Release\PluginPackageTool.exe" "$(ProjectDir)\" "$(ConfigurationName)" - - \ No newline at end of file + + + + + + + + + diff --git a/Device_Info_Json.cs b/Device_Info_Json.cs new file mode 100644 index 0000000000000000000000000000000000000000..2c3c05a21f737c6dcbbd5e400adc1895889ab671 --- /dev/null +++ b/Device_Info_Json.cs @@ -0,0 +1,27 @@ +using GrapeCity.Forguncy.Commands; +using GrapeCity.Forguncy.Plugin; +using System.ComponentModel; + +namespace AndroidPDACommand +{ + [Icon("pack://application:,,,/AndroidPDACommand;component/Resources/Icon_Phone.png")] + [Category("活字格安卓容器(HAC)")] + [OrderWeight(903)] + public class Device_Info_Json : BaseCommand + { + [DisplayName("将设备信息JSON返回到变量")] + [Description("读取设备唯一标识、品牌、型号、Android版本、APP版本、WebView版本等基础信息。")] + [SearchableProperty] + [ResultToProperty] + public string DeviceInfoJson { get; set; } + + public override string ToString() + { + if (string.IsNullOrEmpty(DeviceInfoJson)) + { + return "读取设备信息"; + } + return "读取设备信息:" + DeviceInfoJson; + } + } +} diff --git a/JPushServerCommand.cs b/JPushServerCommand.cs index 317c421e4e5fcecbd923cda3079c40bddbd97a5b..c6ff1b64f1e62cb1d9dc9a7742601d86c755cdc8 100644 --- a/JPushServerCommand.cs +++ b/JPushServerCommand.cs @@ -12,7 +12,6 @@ using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using System.Windows.Markup; -using System.Xml.Serialization.Configuration; namespace AndroidPDACommand { @@ -66,7 +65,7 @@ namespace AndroidPDACommand if (!string.IsNullOrEmpty(url)) { - intentObj.Add("url", "intent:#Intent;action=com.huozige.lab.container.navigate;component=com.huozige.lab.container/com.huozige.lab.container.MainActivity;S.url=" + System.Web.HttpUtility.UrlEncode(url) + ";end"); + intentObj.Add("url", "intent:#Intent;action=com.huozige.lab.container.navigate;component=com.huozige.lab.container/com.huozige.lab.container.MainActivity;S.url=" + WebUtility.UrlEncode(url) + ";end"); } else { diff --git a/OfflinePlusAddPattern_Async.cs b/OfflinePlusAddPattern_Async.cs new file mode 100644 index 0000000000000000000000000000000000000000..e43cbe20a11713b32266db34d53512415df12ae4 --- /dev/null +++ b/OfflinePlusAddPattern_Async.cs @@ -0,0 +1,23 @@ +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; +using GrapeCity.Forguncy.Commands; +using GrapeCity.Forguncy.Plugin; + +namespace AndroidPDACommand +{ + [Icon("pack://application:,,,/AndroidPDACommand;component/Resources/Icon_OfflineDownload.png")] + [Category("活字格安卓容器(HAC)")] + public class OfflinePlusAddPattern_Async : BaseAsyncCommand + { + [Required] + [FormulaProperty] + [DisplayName("离线表单JSON")] + [Description("由“构建离线表单”命令生成的表单JSON。")] + public object PatternJson { get; set; } + + public override string ToString() + { + return "下载离线表单"; + } + } +} diff --git a/OfflinePlusBuildFormItem.cs b/OfflinePlusBuildFormItem.cs new file mode 100644 index 0000000000000000000000000000000000000000..2cf5b47d46f3e5be256bd651c33add4845f4601f --- /dev/null +++ b/OfflinePlusBuildFormItem.cs @@ -0,0 +1,25 @@ +using System.Collections.Generic; +using System.ComponentModel; +using GrapeCity.Forguncy.Commands; +using GrapeCity.Forguncy.Plugin; + +namespace AndroidPDACommand +{ + [Icon("pack://application:,,,/AndroidPDACommand;component/Resources/Icon_OfflineFormItem.png")] + [Category("活字格安卓容器(HAC)")] + public class OfflinePlusBuildFormItem : BaseCommand + { + [TreeProperty(NodeType = typeof(OfflineFormNode), DefaultNodeName = "节点")] + [DisplayName("页面内容")] + public List Items { get; set; } = new List(); + + [DisplayName("将页面内容返回到变量")] + [ResultToProperty] + public string ItemResult { get; set; } = "OfflineFormItem"; + + public override string ToString() + { + return "构建离线页面内容"; + } + } +} diff --git a/OfflinePlusBuildPattern.cs b/OfflinePlusBuildPattern.cs new file mode 100644 index 0000000000000000000000000000000000000000..5cc270f1c9cbd8af238b4280d28dbe1295c1fae7 --- /dev/null +++ b/OfflinePlusBuildPattern.cs @@ -0,0 +1,541 @@ +using System.Collections.Generic; +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; +using System.Linq; +using GrapeCity.Forguncy.Commands; +using GrapeCity.Forguncy.Plugin; + +namespace AndroidPDACommand +{ + [Icon("pack://application:,,,/AndroidPDACommand;component/Resources/Icon_OfflineBuild.png")] + [Category("活字格安卓容器(HAC)")] + public class OfflinePlusBuildPattern : BaseCommand + { + [FormulaProperty] + [DisplayName("项目编号")] + [Description("项目的唯一标识,全局唯一")] + public object PatternId { get; set; } + + [DisplayName("名称")] + [FormulaProperty] + public object Title { get; set; } + + [DisplayName("描述")] + [FormulaProperty] + public object Description { get; set; } + + [Required] + [FormulaProperty] + [DisplayName("版本号")] + [Description("同一项目编号下的表单定义版本,用于区分表单结构变更。")] + public string SchemaVersion { get; set; } = "1.0"; + + [DisplayName("步骤")] + [ObjectListProperty(ItemType = typeof(OfflineFormStep))] + public List Steps { get; set; } + + [DisplayName("将离线表单JSON返回到变量")] + [ResultToProperty] + public string PatternJson { get; set; } = "OfflinePatternJson"; + + public override string ToString() + { + return "构建离线表单"; + } + } + + public class OfflineFormStep : ObjectPropertyBase, INamedObject + { + public string Name { get; set; } + + [FormulaProperty] + [DisplayName("步骤编号")] + [Description("该步骤的唯一标识,同一个离线表单项目内必须唯一。")] + public object StepId { get; set; } + + [FormulaProperty] + [DisplayName("标题")] + public object Title { get; set; } + + [DisplayName("使用页面内容公式")] + public bool UseItemsFormula { get; set; } + + [TreeProperty(NodeType = typeof(OfflineFormNode), DefaultNodeName = "节点")] + [DisplayName("页面内容")] + public List Items { get; set; } = new List(); + + [FormulaProperty] + [DisplayName("页面内容")] + public object ItemsFormula { get; set; } + + public override bool GetDesignerPropertyVisible(string propertyName) + { + switch (propertyName) + { + case nameof(Items): + return !UseItemsFormula; + case nameof(ItemsFormula): + return UseItemsFormula; + default: + return base.GetDesignerPropertyVisible(propertyName); + } + } + } + + public class OfflineFormNode : ObjectPropertyBase, ITreeNode + { + public const string BaseItemTypeValueList = "textItem|passwordItem|selectItem|radioItem|datePicker|timePicker|imageItem|fileItem|signatureItem"; + public const string BaseItemTypeDisplayList = "文本框|密码框|选择框|单选框|日期选择|时间选择|图片列表|文件上传|签名"; + public const string ItemTypeValueList = BaseItemTypeValueList + "|listItem"; + public const string ItemTypeDisplayList = BaseItemTypeDisplayList + "|列表"; + + private static readonly string[] CommonFieldVisibleProperties = + { + nameof(ItemId), + nameof(ItemType), + nameof(Title), + nameof(Hint), + nameof(Required) + }; + + private static readonly HashSet FieldTypeControlledProperties = new HashSet(CommonFieldVisibleProperties) + { + nameof(Value), + nameof(CheckOptions), + nameof(SelectOptionsList), + nameof(RadioDirection), + nameof(IncludeTime), + nameof(IncludeSeconds), + nameof(MaxCount), + nameof(AllowImageUpload), + nameof(CompressionOptions), + nameof(WatermarkOptions), + nameof(FileItemConfig), + nameof(SignatureOptions), + nameof(ListItemOptions) + }; + + private static readonly Dictionary> FieldVisiblePropertiesByType = new Dictionary> + { + { "textItem", CreateFieldVisibleProperties(nameof(Value), nameof(CheckOptions)) }, + { "passwordItem", CreateFieldVisibleProperties(nameof(Value), nameof(CheckOptions)) }, + { "selectItem", CreateFieldVisibleProperties(nameof(Value), nameof(SelectOptionsList)) }, + { "radioItem", CreateFieldVisibleProperties(nameof(Value), nameof(RadioDirection), nameof(SelectOptionsList)) }, + { "datePicker", CreateFieldVisibleProperties(nameof(Value), nameof(IncludeTime)) }, + { "timePicker", CreateFieldVisibleProperties(nameof(Value), nameof(IncludeSeconds)) }, + { "imageItem", CreateFieldVisibleProperties(nameof(MaxCount), nameof(AllowImageUpload), nameof(CompressionOptions), nameof(WatermarkOptions)) }, + { "fileItem", CreateFieldVisibleProperties(nameof(FileItemConfig)) }, + { "signatureItem", CreateFieldVisibleProperties(nameof(Value), nameof(SignatureOptions)) }, + { "listItem", CreateFieldVisibleProperties(nameof(ListItemOptions)) } + }; + + [DisplayName("节点名称")] + public string Text { get; set; } + + [Browsable(false)] + public IEnumerable Children { get; set; } = new List(); + + [DisplayName("节点类型")] + [ComboProperty(ValueList = "group|text|field", DisplayList = "分组|普通文本|表单项")] + public string NodeType { get; set; } = "group"; + + [FormulaProperty] + [DisplayName("说明内容")] + public object Content { get; set; } + + [DisplayName("文本类型")] + [ComboProperty(ValueList = "plain|progress|document", DisplayList = "普通文本|填报进度|说明文档")] + public string TextMode { get; set; } = "plain"; + + [DefaultValue(true)] + [BoolProperty(IndentLevel = 1)] + [DisplayName("总填报项")] + public bool ShowProgressTotal { get; set; } = true; + + [DefaultValue(true)] + [BoolProperty(IndentLevel = 1)] + [DisplayName("已填报项")] + public bool ShowProgressCompleted { get; set; } = true; + + [DefaultValue(true)] + [BoolProperty(IndentLevel = 1)] + [DisplayName("完成率")] + public bool ShowProgressCompletionRate { get; set; } = true; + + [DisplayName("默认折叠")] + public bool DefaultCollapsed { get; set; } + + [DisplayName("启用填报进度")] + [Description("仅步骤中的最外层节点生效。启用后该节点作为一个填报进度统计单位。")] + public bool EnableProgress { get; set; } + + [DisplayName("填报进度标识项")] + [Description("仅最外层分组的直接表单项生效。启用后该表单项作为该填报单位的完成标识。")] + public bool ProgressIdentifier { get; set; } + + [FormulaProperty] + [DisplayName("编号")] + [Description("该表单项的唯一标识,全局唯一,无论是同一项目内,还是跨项目,都必须唯一,更建议使用项目编号作为前缀拼接;例如项目为Project01,则该表单项编号为Project01_Name")] + public object ItemId { get; set; } + + [DisplayName("类型")] + [ComboProperty(ValueList = ItemTypeValueList, DisplayList = ItemTypeDisplayList)] + public virtual string ItemType { get; set; } = "textItem"; + + [FormulaProperty] + [DisplayName("标题")] + public object Title { get; set; } + + [FormulaProperty] + [DisplayName("水印")] + public object Hint { get; set; } + + [DisplayName("必填")] + public bool Required { get; set; } + + [FormulaProperty] + [DisplayName("默认值")] + public object Value { get; set; } + + [DisplayName("包含时间")] + [Description("仅日期选择类型生效。启用后可同时选择日期和时间。")] + public bool IncludeTime { get; set; } + + [DisplayName("包含秒")] + [Description("仅时间选择类型生效。启用后可选择时分秒;关闭时使用系统原生时分选择器。")] + public bool IncludeSeconds { get; set; } + + + [ObjectProperty(ObjType = typeof(CheckOptions))] + [DisplayName("校验规则")] + public CheckOptions CheckOptions { get; set; } + + [ListProperty] + [DisplayName("选则项")] + public List SelectOptionsList { get; set; } + + [DisplayName("排列方向")] + [ComboProperty(ValueList = "vertical|horizontal", DisplayList = "垂直|水平")] + public string RadioDirection { get; set; } = "horizontal"; + + [FormulaProperty] + [DisplayName("图片最大数量")] + [Description("0表示不限制图片数量。")] + public object MaxCount { get; set; } = 0; + + [DisplayName("允许图片上传")] + [Description("仅图片列表类型生效。启用后填报时除拍照外还可以从本地选择图片。")] + public bool AllowImageUpload { get; set; } + + [ObjectProperty(ObjType = typeof(ImageCompressionOptions))] + [DisplayName("图片压缩设置")] + public ImageCompressionOptions CompressionOptions { get; set; } = new ImageCompressionOptions(); + + [ObjectProperty(ObjType = typeof(ImageWatermarkOptions))] + [DisplayName("拍照水印配置")] + public ImageWatermarkOptions WatermarkOptions { get; set; } = new ImageWatermarkOptions(); + + [ObjectProperty(ObjType = typeof(FileItemConfig))] + [DisplayName("文件上传配置")] + public FileItemConfig FileItemConfig { get; set; } = new FileItemConfig(); + + [ObjectProperty(ObjType = typeof(SignatureItemOptions))] + [DisplayName("签名配置")] + public SignatureItemOptions SignatureOptions { get; set; } = new SignatureItemOptions(); + + [ObjectProperty(ObjType = typeof(ListItemOptions))] + [DisplayName("列表配置")] + public ListItemOptions ListItemOptions { get; set; } = new ListItemOptions(); + + public override bool GetDesignerPropertyVisible(string propertyName) + { + var isField = NodeType == "field"; + var isText = NodeType == "text"; + var isGroup = NodeType == "group"; + var isTextProgress = isText && TextMode == "progress"; + var isTextPlain = isText && TextMode != "progress" && TextMode != "document"; + + switch (propertyName) + { + case nameof(TextMode): + return isText; + case nameof(Content): + return isTextPlain; + case nameof(ShowProgressTotal): + case nameof(ShowProgressCompleted): + case nameof(ShowProgressCompletionRate): + return isTextProgress; + case nameof(DefaultCollapsed): + return isGroup; + case nameof(EnableProgress): + return isGroup; + case nameof(ProgressIdentifier): + return isField; + default: + if (FieldTypeControlledProperties.Contains(propertyName)) + { + return isField && IsFieldPropertyVisible(ItemType, propertyName); + } + return base.GetDesignerPropertyVisible(propertyName); + } + } + + public override object Clone() + { + return new OfflineFormNode + { + Text = Text, + Children = Children == null ? new List() : Children.ToList(), + NodeType = NodeType, + Content = Content, + TextMode = TextMode, + ShowProgressTotal = ShowProgressTotal, + ShowProgressCompleted = ShowProgressCompleted, + ShowProgressCompletionRate = ShowProgressCompletionRate, + DefaultCollapsed = DefaultCollapsed, + EnableProgress = EnableProgress, + ProgressIdentifier = ProgressIdentifier, + ItemId = ItemId, + ItemType = ItemType, + Title = Title, + Hint = Hint, + Required = Required, + Value = Value, + IncludeTime = IncludeTime, + IncludeSeconds = IncludeSeconds, + CheckOptions = CheckOptions, + SelectOptionsList = SelectOptionsList, + RadioDirection = RadioDirection, + MaxCount = MaxCount, + AllowImageUpload = AllowImageUpload, + CompressionOptions = CompressionOptions, + WatermarkOptions = WatermarkOptions, + FileItemConfig = FileItemConfig, + SignatureOptions = SignatureOptions, + ListItemOptions = ListItemOptions + }; + } + + private static HashSet CreateFieldVisibleProperties(params string[] propertyNames) + { + var visibleProperties = new HashSet(CommonFieldVisibleProperties); + foreach (var propertyName in propertyNames) + { + visibleProperties.Add(propertyName); + } + return visibleProperties; + } + + private static bool IsFieldPropertyVisible(string itemType, string propertyName) + { + HashSet visibleProperties; + if (!FieldVisiblePropertiesByType.TryGetValue(itemType ?? "textItem", out visibleProperties)) + { + visibleProperties = FieldVisiblePropertiesByType["textItem"]; + } + return visibleProperties.Contains(propertyName); + } + } + + public class OfflineListFormNode : OfflineFormNode + { + [DisplayName("类型")] + [ComboProperty(ValueList = BaseItemTypeValueList, DisplayList = BaseItemTypeDisplayList)] + public override string ItemType { get; set; } = "textItem"; + + public override object Clone() + { + return new OfflineListFormNode + { + Text = Text, + Children = Children == null ? new List() : Children.ToList(), + NodeType = NodeType, + Content = Content, + TextMode = TextMode, + ShowProgressTotal = ShowProgressTotal, + ShowProgressCompleted = ShowProgressCompleted, + ShowProgressCompletionRate = ShowProgressCompletionRate, + DefaultCollapsed = DefaultCollapsed, + EnableProgress = EnableProgress, + ProgressIdentifier = ProgressIdentifier, + ItemId = ItemId, + ItemType = ItemType, + Title = Title, + Hint = Hint, + Required = Required, + Value = Value, + IncludeTime = IncludeTime, + IncludeSeconds = IncludeSeconds, + CheckOptions = CheckOptions, + SelectOptionsList = SelectOptionsList, + RadioDirection = RadioDirection, + MaxCount = MaxCount, + AllowImageUpload = AllowImageUpload, + CompressionOptions = CompressionOptions, + WatermarkOptions = WatermarkOptions, + FileItemConfig = FileItemConfig, + SignatureOptions = SignatureOptions, + ListItemOptions = ListItemOptions + }; + } + } + + public class CheckOptions : ObjectPropertyBase + { + [FormulaProperty] + [DisplayName("最小长度")] + public object MinLength { get; set; } + + [FormulaProperty] + [DisplayName("最大长度")] + public object MaxLength { get; set; } + + [FormulaProperty] + [DisplayName("正则表达式")] + public object RegexPattern { get; set; } + } + + public class SelectOptions : ObjectPropertyBase + { + [FormulaProperty] + [DisplayName("值")] + public object Value { get; set; } + + [FormulaProperty] + [DisplayName("显示文本")] + public object Label { get; set; } + } + + public class ImageCompressionOptions : ObjectPropertyBase + { + [DisplayName("启用压缩")] + [Description("默认关闭,关闭时按原图保存。启用后才使用下面的压缩参数。")] + public bool EnableCompression { get; set; } + + [FormulaProperty] + [DisplayName("最长边像素")] + public object MaxLongEdge { get; set; } = 1600; + + [FormulaProperty] + [DisplayName("JPEG质量")] + public object JpegQuality { get; set; } = 80; + + [FormulaProperty] + [DisplayName("目标大小KB")] + [Description("0表示不按文件大小继续压缩。")] + public object MaxFileSizeKb { get; set; } = 0; + + [FormulaProperty] + [DisplayName("最低JPEG质量")] + public object MinQuality { get; set; } = 60; + } + + public class ImageWatermarkOptions : ObjectPropertyBase + { + [DisplayName("时间戳水印")] + public bool EnableTimestamp { get; set; } = false; + + [ListProperty] + [DisplayName("自定义字段")] + public List Fields { get; set; } = new List + { + }; + } + + public class ImageWatermarkField : ObjectPropertyBase + { + [DisplayName("Key")] + public string Key { get; set; } + + [FormulaProperty] + [DisplayName("Value")] + public object Value { get; set; } + } + + public class FileItemConfig : ObjectPropertyBase + { + [FormulaProperty] + [DisplayName("最大数量")] + [Description("0表示不限制上传文件数量。")] + public object MaxCount { get; set; } = 0; + + [FormulaProperty] + [DisplayName("允许扩展名")] + [Description("逗号分隔,每个扩展名前带点;留空表示不限制,例如:.pdf,.doc,.docx。")] + public object AllowedExtensions { get; set; } + + [FormulaProperty] + [DisplayName("单文件最大大小KB")] + [Description("0表示不限制单文件大小。")] + public object MaxFileSizeKb { get; set; } = 0; + } + + public class SignatureItemOptions : ObjectPropertyBase + { + [DisplayName("使用人员数组公式")] + [Description("启用后直接使用下面公式返回的字符串数组作为签名人员。")] + public bool UseUsersFormula { get; set; } + + [ListProperty] + [DisplayName("签名人员")] + [Description("按签名顺序配置人员,生成JSON中的options.users字符串数组。")] + public List Users { get; set; } = new List(); + + [FormulaProperty] + [DisplayName("人员数组公式")] + [Description("返回签名人员字符串数组,例如:[\"张三\",\"李四\"]。")] + public object UsersFormula { get; set; } + + [FormulaProperty] + [DisplayName("免责声明")] + [Description("签名前展示的确认说明,生成JSON中的options.disclaimer。")] + public object Disclaimer { get; set; } + + public override bool GetDesignerPropertyVisible(string propertyName) + { + switch (propertyName) + { + case nameof(Users): + return !UseUsersFormula; + case nameof(UsersFormula): + return UseUsersFormula; + default: + return base.GetDesignerPropertyVisible(propertyName); + } + } + } + + public class SignatureUser : ObjectPropertyBase + { + [FormulaProperty] + [DisplayName("人员")] + public object Name { get; set; } + } + + public class ListItemOptions : ObjectPropertyBase + { + [FormulaProperty] + [DisplayName("最小数量")] + public object MinCount { get; set; } + + [FormulaProperty] + [DisplayName("最大数量")] + public object MaxCount { get; set; } + + [FormulaProperty] + [DisplayName("默认数量")] + public object DefaultCount { get; set; } + + [FormulaProperty] + [DisplayName("添加按钮文本")] + public object AddButtonText { get; set; } + + [FormulaProperty] + [DisplayName("列表项标题")] + public object ItemTitle { get; set; } + + [TreeProperty(NodeType = typeof(OfflineListFormNode), DefaultNodeName = "节点")] + [DisplayName("列表子项")] + public List Children { get; set; } = new List(); + } +} diff --git a/OfflinePlusDownloadManualPdf_Async.cs b/OfflinePlusDownloadManualPdf_Async.cs new file mode 100644 index 0000000000000000000000000000000000000000..0e6bd7471aa1355f752b7f1a293bd0c1e5011fac --- /dev/null +++ b/OfflinePlusDownloadManualPdf_Async.cs @@ -0,0 +1,29 @@ +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; +using GrapeCity.Forguncy.Commands; +using GrapeCity.Forguncy.Plugin; + +namespace AndroidPDACommand +{ + [Icon("pack://application:,,,/AndroidPDACommand;component/Resources/Icon_PDF.png")] + [Category("活字格安卓容器(HAC)")] + public class OfflinePlusDownloadManualPdf_Async : BaseAsyncCommand + { + [Required] + [FormulaProperty] + [DisplayName("项目编号")] + [Description("需要绑定说明 PDF 的离线表单项目编号。")] + public object PatternId { get; set; } + + [Required] + [FormulaProperty] + [DisplayName("说明 PDF 附件")] + [Description("选择保存说明 PDF 附件的单元格。多个附件名称请使用英文竖线(|)分隔,APP 会下载全部 PDF 并绑定到指定的离线表单项目。")] + public object ManualAttachmentCell { get; set; } + + public override string ToString() + { + return "下载离线表单说明PDF"; + } + } +} diff --git a/OfflinePlusGetPatterns_Async.cs b/OfflinePlusGetPatterns_Async.cs new file mode 100644 index 0000000000000000000000000000000000000000..0b73171d943a6218c97de61ce7673e97f4086985 --- /dev/null +++ b/OfflinePlusGetPatterns_Async.cs @@ -0,0 +1,103 @@ +using System.ComponentModel; +using System; +using GrapeCity.Forguncy.Commands; +using GrapeCity.Forguncy.Plugin; + +namespace AndroidPDACommand +{ + [Icon("pack://application:,,,/AndroidPDACommand;component/Resources/Icon_OfflineUpload.png")] + [Category("活字格安卓容器(HAC)")] + public class OfflinePlusGetPatterns_Async : BaseAsyncCommand + { + [DisplayName("动作")] + [ComboProperty(ValueList = "GetPatterns|ExportRecords|MarkRecordExported|DeleteReadRecords|DeleteProject|BatchExportRecords", DisplayList = "获取设备上的离线表单项目编号列表|导出离线表单数据|标记离线记录已导出|删除已读离线记录|删除离线表单项目|批量导出离线表单数据")] + public string Action { get; set; } = "GetPatterns"; + + [FormulaProperty] + [DisplayName("项目编号")] + public object ProjectId { get; set; } + + [FormulaProperty] + [DisplayName("记录编号")] + [Description("多个记录编号用英文逗号分隔。标记离线记录已导出时必填;删除已读离线记录时不填,则删除项目下所有已读记录。")] + public object RecordIds { get; set; } + + [DisplayName("将离线表单项目编号列表返回到变量")] + [ResultToProperty] + public string ProjectsResult { get; set; } + + [DisplayName("将离线表单数据返回到变量")] + [Description("导出离线记录数据。图片和文件字段会先按统一附件模型读取本地附件并上传,再把上传结果写回对应字段值。")] + [ResultToProperty] + public string ExportResult { get; set; } + + [ServerProperty] + [Browsable(false)] + [PageMetadataJsonIgnore] + [SaveJsonIgnore] + public UploadLimit FileUploadLimit { get; set; } = new UploadLimit(); + + [DisplayName("将操作结果返回到变量")] + [ResultToProperty] + public string OperationResult { get; set; } + + public override string ToString() + { + return "上传离线表单"; + } + + public override bool GetDesignerPropertyVisible(string propertyName, CommandScope commandScope) + { + if (propertyName == nameof(ProjectId)) + { + return Action == "ExportRecords" || Action == "MarkRecordExported" || Action == "DeleteReadRecords" || Action == "DeleteProject"; + } + if (propertyName == nameof(RecordIds)) + { + return Action == "MarkRecordExported" || Action == "DeleteReadRecords"; + } + if (propertyName == nameof(OperationResult)) + { + return Action == "MarkRecordExported" || Action == "DeleteReadRecords" || Action == "DeleteProject"; + } + if (propertyName == nameof(ExportResult)) + { + return Action == "ExportRecords" || Action == "BatchExportRecords"; + } + if (propertyName == nameof(ProjectsResult)) + { + return Action == "GetPatterns"; + } + return base.GetDesignerPropertyVisible(propertyName, commandScope); + } + } + + public class UploadLimit : ICloneable, IUploadLimit, ISupportDeclareObjectEmpty + { + public UploadLimit() + { + ExtensionFilter = ""; + SizeLimit = 0; + MaxUploadFileCount = 0; + } + + [DefaultValue("")] + public string ExtensionFilter { get; set; } + + [DefaultValue(0d)] + public double SizeLimit { get; set; } + + [DefaultValue(0)] + public int MaxUploadFileCount { get; set; } + + public object Clone() + { + return MemberwiseClone(); + } + + public bool IsObjectEmpty() + { + return SizeLimit == 0 && MaxUploadFileCount == 0 && ExtensionFilter == ""; + } + } +} diff --git a/OfflinePlusValidatePatternJson.cs b/OfflinePlusValidatePatternJson.cs new file mode 100644 index 0000000000000000000000000000000000000000..b96687b4bdacde36cd73d5de66fbf59f4fa12745 --- /dev/null +++ b/OfflinePlusValidatePatternJson.cs @@ -0,0 +1,32 @@ +using System.ComponentModel; +using System.ComponentModel.DataAnnotations; +using GrapeCity.Forguncy.Commands; +using GrapeCity.Forguncy.Plugin; + +namespace AndroidPDACommand +{ + [Icon("pack://application:,,,/AndroidPDACommand;component/Resources/Icon_OfflineDownload.png")] + [Category("活字格安卓容器(HAC)")] + public class OfflinePlusValidatePatternJson : BaseCommand + { + [Required] + [FormulaProperty] + [DisplayName("离线表单JSON")] + [Description("需要检测的JSON字符串或JSON对象。结构要求与“下载离线表单”命令的“离线表单JSON”参数一致。")] + public object PatternJson { get; set; } + + [DisplayName("将是否有效返回到变量")] + [ResultToProperty] + public string IsValidResult { get; set; } = "OfflinePatternJsonIsValid"; + + [DisplayName("将错误点返回到变量")] + [Description("校验成功时返回空字符串;失败时返回第一个错误的JSON路径和错误原因。")] + [ResultToProperty] + public string ErrorResult { get; set; } = "OfflinePatternJsonError"; + + public override string ToString() + { + return "检测离线表单JSON"; + } + } +} diff --git a/PluginConfig.json b/PluginConfig.json index 2ac37f60d2099891ed71e9d72ff8a8b48fdd08f9..85f3a6f2677ec3be2d11509a29e22ec569ff3e04 100644 --- a/PluginConfig.json +++ b/PluginConfig.json @@ -3,6 +3,7 @@ "AndroidPDACommand.dll" ], "javascript": [ + "Resources/OfflinePlusExportProgress.js", "Resources/AndroidPDACommand.js", "Resources/LPAPI-0.4.20181022.js" ], @@ -12,8 +13,8 @@ "name": "PDA(Android)交互命令", "pluginType": "command", "guid": "{16B8DF69-1379-41C1-9194-BE89BAF8BB32}", - "version": "1.22.0.0", + "version": "1.23.2.0", "dependenceVersion": "8.0.0.0", "bundleJavaScript": true, "bundleCSS": true -} \ No newline at end of file +} diff --git a/Resources/AndroidPDACommand.js b/Resources/AndroidPDACommand.js index e4ee502d83b5b8ecf4bd83170058ba0d717f796e..920a28c8722255c381c5ef0c37430aadbd902c52 100644 --- a/Resources/AndroidPDACommand.js +++ b/Resources/AndroidPDACommand.js @@ -1,10 +1,30 @@  var ERROR_NOT_RUN_IN_HAC = "当前APP不支持该命令,这通常是因为APP版本过低。您可以通过在葡萄城技术社区搜索“HAC”下载最新版APP。"; -var HAC_CallFunctionOutOfHAC = function () { - alert(ERROR_NOT_RUN_IN_HAC); +var HAC_CallFunctionOutOfHAC = function (debugInfo) { + var message = ERROR_NOT_RUN_IN_HAC; + if (debugInfo) { + message += "\r\n\r\n诊断信息:\r\n" + debugInfo; + } + alert(message); } +var HAC_GetOfflinePlusDebugInfo = function (commandName, stage) { + var offlinePlus = window.offlinePlus; + var hac = window.HAC; + return [ + "命令:" + commandName, + "阶段:" + stage, + "window.HAC:" + (hac ? typeof hac : "undefined"), + "window.HAC.registryCallback:" + (hac && hac.registryCallback ? typeof hac.registryCallback : "undefined"), + "window.offlinePlus:" + (offlinePlus ? typeof offlinePlus : "undefined"), + "window.offlinePlus.offlinePlusAddPatternAsync:" + (offlinePlus && offlinePlus.offlinePlusAddPatternAsync ? typeof offlinePlus.offlinePlusAddPatternAsync : "undefined"), + "window.offlinePlus.offlinePlusDownloadManualPdfAsync:" + (offlinePlus && offlinePlus.offlinePlusDownloadManualPdfAsync ? typeof offlinePlus.offlinePlusDownloadManualPdfAsync : "undefined"), + "window.offlinePlus.offlinePlusGetPatternsAsync:" + (offlinePlus && offlinePlus.offlinePlusGetPatternsAsync ? typeof offlinePlus.offlinePlusGetPatternsAsync : "undefined"), + "location:" + window.location.href + ].join("\r\n"); +}; + var HAC_GenerateCellInfo = function (context, formula) { var cellLocation = context.getCellLocation(formula); @@ -18,9 +38,9 @@ var HAC_GenerateCellInfo = function (context, formula) { return JSON.stringify(cellLocation); }; -var HAC_GenerateCallbackTicket = function (context, onSuccess) { +var HAC_GenerateCallbackTicket = function (context, onSuccess, debugInfo, onError) { if (!window.HAC) { - HAC_CallFunctionOutOfHAC(); + HAC_CallFunctionOutOfHAC(debugInfo || "window.HAC is undefined."); } else { var ticket = { @@ -32,6 +52,9 @@ var HAC_GenerateCallbackTicket = function (context, onSuccess) { } window.HAC.registryCallback(ticket, onSuccess, function (error) { + if (onError) { + onError(error); + } context.CommandExecutor.excuteCommand(context.CommandParam.CommandList, { runTimePageName: context.CommandExecutingInfo.runTimePageName, commandID: new Date().valueOf().toString(), @@ -55,6 +78,432 @@ var HAC_ReturnToParam = function (OutParamaterName, data) { } }; +var HAC_GetOfflinePlusManualPdfUrl = function (manualAttachmentValue) { + if (!manualAttachmentValue) { + return []; + } + + return (manualAttachmentValue + "").split("|").map(function (fileId) { + return fileId.trim(); + }).filter(function (fileId) { + return fileId !== ""; + }).map(function (fileId) { + return Forguncy.Helper.SpecialPath.getFileDownloadUrl(fileId); + }); +}; +/** + * 将DataURL转换为File对象 + * @param {*} dataUrl + * @param {*} fileName + * @returns File对象,或转换失败时返回null + */ +var HAC_DataUrlToFile = function (dataUrl, fileName) { + var parts = (dataUrl || "").split(","); + if (parts.length < 2) { + return null; + } + var header = parts[0]; + var mimeMatch = header.match(/data:([^;]+);base64/i); + var mimeType = mimeMatch ? mimeMatch[1] : "application/octet-stream"; + var binary = atob(parts.slice(1).join(",")); + var bytes = new Uint8Array(binary.length); + for (var i = 0; i < binary.length; i++) { + bytes[i] = binary.charCodeAt(i); + } + return new File([bytes], fileName || "offlineAttachment", { type: mimeType }); +}; + +/** + * 将字节数格式化为MB字符串 + */ +var HAC_FormatBytesAsMb = function (bytes) { + return (bytes / 1024 / 1024).toFixed(2) + " MB"; +}; + +/** + * 将文件上传到服务器临时目录,并返回服务器上的文件标识 + * @param {*} file + * @param {*} uploadLimitId + * @param {*} onProgress + * @returns Promise,成功时返回服务器上的文件标识,失败时返回错误信息 + */ +function HAC_UploadFileToTemp(file, uploadLimitId, onProgress) { + return new Promise(function (resolve, reject) { + var formData = new FormData(); + formData.append("file", file); + formData.append("uploadLimitId", uploadLimitId); + formData.append("uploadFolder", ""); + + var startTime = new Date().valueOf(); + var xhr = new XMLHttpRequest(); + xhr.open("POST", Forguncy.Common.uploadUrl, true); + xhr.setRequestHeader("Accept", "application/json"); + xhr.upload.onprogress = function (event) { + if (onProgress && event.lengthComputable) { + var elapsedSeconds = Math.max((new Date().valueOf() - startTime) / 1000, 0.1); + onProgress(event.loaded, event.total, event.loaded / elapsedSeconds); + } + }; + xhr.onload = function () { + if (xhr.status >= 200 && xhr.status < 300) { + resolve(xhr.responseText); + } else { + reject(xhr.responseText || xhr.statusText || "上传离线附件失败。"); + } + }; + xhr.onerror = function () { + reject("上传离线附件失败。"); + }; + xhr.send(formData); + }); +} +function HAC_GetOfflineRecordFieldValue(record, fieldId) { + var fieldValue = record && record.values && record.values[fieldId]; + if (fieldValue && typeof fieldValue === "object" && !Array.isArray(fieldValue) && + Object.prototype.hasOwnProperty.call(fieldValue, "value")) { + return fieldValue.value; + } + return fieldValue; +} + +function HAC_SetOfflineRecordFieldValue(record, fieldId, value) { + var fieldValue = record && record.values && record.values[fieldId]; + if (fieldValue && typeof fieldValue === "object" && !Array.isArray(fieldValue) && + Object.prototype.hasOwnProperty.call(fieldValue, "value")) { + // 只替换实际值,保留图片等字段的整体更新时间和其它元数据。 + fieldValue.value = value; + } else { + record.values[fieldId] = value; + } +} + +function HAC_ParseOfflineSignatureValues(record, fieldId) { + var fieldValue = HAC_GetOfflineRecordFieldValue(record, fieldId); + if (Array.isArray(fieldValue)) { + return fieldValue.slice(); + } + if (typeof fieldValue !== "string" || fieldValue.trim() === "") { + return []; + } + + try { + var values = JSON.parse(fieldValue); + return Array.isArray(values) ? values : []; + } catch (e) { + return []; + } +} + +function HAC_GetOfflineSignatureAttachmentIndex(record, attachment, fieldId) { + var path = attachment && attachment.path; + if (!Array.isArray(path) || path.length < 3) { + return -1; + } + + var signatureIndex = Number(path[2]); + if (!isFinite(signatureIndex) || signatureIndex < 0 || Math.floor(signatureIndex) !== signatureIndex) { + return -1; + } + + var signatureValues = HAC_ParseOfflineSignatureValues(record, fieldId); + var signatureValue = signatureValues[signatureIndex]; + var hasSignatureValue = signatureValue && typeof signatureValue === "object" && !Array.isArray(signatureValue) && + (Object.prototype.hasOwnProperty.call(signatureValue, "userName") || + Object.prototype.hasOwnProperty.call(signatureValue, "updateTime")); + var hasSignatureMetadata = attachment && attachment.updateTime !== undefined && attachment.updateTime !== null; + return hasSignatureValue || hasSignatureMetadata ? signatureIndex : -1; +} + +function HAC_ApplyUploadedSignatureValue(record, attachment, attachmentValue, fieldId, signatureIndex) { + var signatureValues = HAC_ParseOfflineSignatureValues(record, fieldId); + var oldSignatureValue = signatureValues[signatureIndex]; + var signatureValue = {}; + + if (oldSignatureValue && typeof oldSignatureValue === "object" && !Array.isArray(oldSignatureValue)) { + Object.keys(oldSignatureValue).forEach(function (key) { + signatureValue[key] = oldSignatureValue[key]; + }); + } + + if (!signatureValue.userName && attachment.originalName) { + signatureValue.userName = attachment.originalName; + } + signatureValue.fileName = attachmentValue; + if (attachment.updateTime !== undefined && attachment.updateTime !== null) { + signatureValue.updateTime = attachment.updateTime; + } + + signatureValues[signatureIndex] = signatureValue; + HAC_SetOfflineRecordFieldValue(record, fieldId, JSON.stringify(signatureValues)); +} + +/** + * 将上传后的附件值应用到记录中。普通附件保留字段整体更新时间;签名附件额外保留每张签名的更新时间。 + */ +function HAC_ApplyUploadedAttachmentValue(record, attachment, attachmentValue, uploadedValues) { + if (!record || !record.values || !attachment) { + return; + } + + var recordId = HAC_GetOfflineAttachmentRecordId(attachment); + var fieldId = HAC_GetOfflineAttachmentFieldId(attachment); + if (!recordId || !fieldId) { + return; + } + + var signatureIndex = HAC_GetOfflineSignatureAttachmentIndex(record, attachment, fieldId); + if (signatureIndex >= 0) { + HAC_ApplyUploadedSignatureValue(record, attachment, attachmentValue, fieldId, signatureIndex); + return; + } + + var key = recordId + "|" + fieldId; + if (!uploadedValues[key]) { + uploadedValues[key] = []; + } + uploadedValues[key].push(attachmentValue); + HAC_SetOfflineRecordFieldValue(record, fieldId, uploadedValues[key].join("|")); +} + +function HAC_GetOfflineAttachmentRecordId(attachment) { + return attachment && attachment.recordId || attachment && attachment.path && attachment.path[0] || ""; +} + +function HAC_GetOfflineAttachmentFieldId(attachment) { + return attachment && attachment.fieldId || attachment && attachment.path && attachment.path[1] || ""; +} + +function HAC_GetOfflineAttachmentUploadFileName(attachment) { + return attachment && (attachment.originalName || attachment.fileName || attachment.localName) || "offlineAttachment"; +} + +/** + * 处理离线导出附件 + * @param {*} projectId + * @param {*} exportData + * @param {*} uploadLimitId + * @returns Promise,成功时返回处理后的导出数据,失败时返回错误信息 + */ +async function HAC_ProcessOfflineExportAttachments(projectId, exportData, uploadLimitId) { + if (!exportData) { + return exportData; + } + var records = exportData.records || []; + if (!exportData.attachments || exportData.attachments.length === 0) { + delete exportData.attachments; + return exportData; + } + if (!uploadLimitId) { + throw "请设置文件上传限制ID。"; + } + if (!window.offlinePlus || !window.offlinePlus.offlinePlusLoadAttachment) { + HAC_CallFunctionOutOfHAC(HAC_GetOfflinePlusDebugInfo("上传离线表单", "调用offlinePlusLoadAttachment")); + throw "当前APP不支持读取离线附件。"; + } + + var uploadedValues = {}; + HAC_OfflineUploadProgress.update({ + percent: 0, + detail: "准备上传 " + exportData.attachments.length + " 个离线附件", + speed: "" + }); + for (var i = 0; i < exportData.attachments.length; i++) { + var attachment = exportData.attachments[i]; + if (!attachment || !attachment.localName || !HAC_GetOfflineAttachmentRecordId(attachment) || !HAC_GetOfflineAttachmentFieldId(attachment)) { + continue; + } + + var fileIndexText = (i + 1) + " / " + exportData.attachments.length; + HAC_OfflineUploadProgress.update({ + percent: exportData.attachments.length === 0 ? 0 : i / exportData.attachments.length * 100, + detail: "正在读取离线文件:" + fileIndexText + " " + attachment.localName, + speed: "" + }); + var dataUrl = window.offlinePlus.offlinePlusLoadAttachment(projectId, attachment.localName); + var file = HAC_DataUrlToFile(dataUrl, HAC_GetOfflineAttachmentUploadFileName(attachment)); + if (!file) { + throw "读取离线附件失败:" + attachment.localName; + } + + var attachmentValue = await HAC_UploadFileToTemp(file, uploadLimitId, function (loaded, total, bytesPerSecond) { + HAC_OfflineUploadProgress.update({ + percent: (i + (total > 0 ? loaded / total : 0)) / exportData.attachments.length * 100, + detail: "正在上传:" + fileIndexText + " " + file.name + "," + HAC_FormatBytesAsMb(loaded) + " / " + HAC_FormatBytesAsMb(total), + speed: "速度:" + HAC_FormatBytesAsMb(bytesPerSecond) + "/s" + }); + }); + var record = records.find(function (record) { + return record && record.recordId === HAC_GetOfflineAttachmentRecordId(attachment); + }); + HAC_ApplyUploadedAttachmentValue(record, attachment, attachmentValue, uploadedValues); + } + HAC_OfflineUploadProgress.update({ + percent: 100, + detail: "正在生成导出数据", + speed: "" + }); + delete exportData.attachments; + return exportData; +} + +/** + * 处理批量导出多条记录的附件 + * @param {*} exportDataArray 批量导出的数据数组,每项包含 { projectId, patternTitle, records, attachments } + * @param {*} uploadLimitId 上传限制ID + * @returns Promise,成功时返回处理后的导出数据数组 + */ +async function HAC_ProcessBatchExportAttachments(exportDataArray, uploadLimitId) { + if (!exportDataArray || !Array.isArray(exportDataArray) || exportDataArray.length === 0) { + return exportDataArray; + } + + if (!uploadLimitId) { + throw "请设置文件上传限制ID。"; + } + if (!window.offlinePlus || !window.offlinePlus.offlinePlusLoadAttachment) { + HAC_CallFunctionOutOfHAC(HAC_GetOfflinePlusDebugInfo("批量导出离线表单", "调用offlinePlusLoadAttachment")); + throw "当前APP不支持读取离线附件。"; + } + + // 统计所有附件总数并初始化进度显示 + var totalAttachments = 0; + HAC_BatchUploadProgress.ensure(exportDataArray.length); + exportDataArray.forEach(function (item, index) { + if (item && item.attachments) { + totalAttachments += item.attachments.length; + } + // 初始化每个表单项的进度显示 + var itemKey = "item_" + index; + var itemTitle = (item && item.projectId) || ("离线表单 " + (index + 1)); + HAC_BatchUploadProgress.initItem(itemKey, itemTitle); + }); + HAC_BatchUploadProgress.updateSummary({ + percent: 0, + title: "准备导出", + metaLeft: "已上传文件0/" + totalAttachments, + metaRight: totalAttachments > 0 ? ("共 " + totalAttachments + " 个附件待上传") : "无需上传附件" + }); + + if (totalAttachments === 0) { + // 没有附件,直接标记所有项为完成 + exportDataArray.forEach(function (item, index) { + if (item) { + delete item.attachments; + HAC_BatchUploadProgress.completeItem("item_" + index); + } + }); + HAC_BatchUploadProgress.updateSummary({ + percent: 100, + title: "导出数据", + metaLeft: "无需上传附件", + metaRight: "共 " + exportDataArray.length + " 项" + }); + return exportDataArray; + } + + var currentAttachmentIndex = 0; + var completedAttachmentCount = 0; + + HAC_BatchUploadProgress.updateSummary({ + percent: 0, + title: "准备上传附件", + metaLeft: "已上传文件0/" + totalAttachments, + metaRight: "共 " + totalAttachments + " 个附件待上传" + }); + + for (var itemIndex = 0; itemIndex < exportDataArray.length; itemIndex++) { + var exportItem = exportDataArray[itemIndex]; + if (!exportItem) { + continue; + } + + var itemKey = "item_" + itemIndex; + var projectId = exportItem.projectId; + var records = exportItem.records || []; + var attachments = exportItem.attachments || []; + var uploadedValues = {}; + var currentItemTitle = exportItem.projectId || ("离线表单 " + (itemIndex + 1)); + + if (!attachments || attachments.length === 0) { + delete exportItem.attachments; + HAC_BatchUploadProgress.completeItem(itemKey); + continue; + } + + HAC_BatchUploadProgress.updateItem(itemKey, { state: 'processing', detail: '准备处理 ' + attachments.length + ' 个附件...' }); + HAC_BatchUploadProgress.updateSummary({ + percent: completedAttachmentCount / totalAttachments * 100, + title: currentItemTitle, + metaLeft: "已上传文件" + completedAttachmentCount + "/" + totalAttachments, + metaRight: "准备处理 " + attachments.length + " 个附件" + }); + + for (var i = 0; i < attachments.length; i++) { + var attachment = attachments[i]; + if (!attachment || !attachment.localName || !HAC_GetOfflineAttachmentRecordId(attachment) || !HAC_GetOfflineAttachmentFieldId(attachment)) { + continue; + } + + currentAttachmentIndex++; + var progressPercent = (completedAttachmentCount / totalAttachments) * 100; + var attachmentName = attachment.localName || "附件"; + + HAC_BatchUploadProgress.updateItem(itemKey, { + progress: progressPercent, + detail: "正在上传 " + currentAttachmentIndex + "/" + totalAttachments + ":" + attachmentName + }); + HAC_BatchUploadProgress.updateSummary({ + percent: progressPercent, + title: currentItemTitle, + metaLeft: "已上传文件" + completedAttachmentCount + "/" + totalAttachments, + metaRight: attachmentName + }); + + try { + var dataUrl = window.offlinePlus.offlinePlusLoadAttachment(projectId, attachment.localName); + var file = HAC_DataUrlToFile(dataUrl, HAC_GetOfflineAttachmentUploadFileName(attachment)); + if (!file) { + throw "读取离线附件失败:" + attachment.localName; + } + + var attachmentValue = await HAC_UploadFileToTemp(file, uploadLimitId, function (loaded, total, bytesPerSecond) { + var itemProgress = ((completedAttachmentCount + (total > 0 ? loaded / total : 0)) / totalAttachments) * 100; + HAC_BatchUploadProgress.updateItem(itemKey, { + progress: itemProgress, + detail: "正在上传 " + HAC_FormatBytesAsMb(loaded) + "/" + HAC_FormatBytesAsMb(total) + ",速度:" + HAC_FormatBytesAsMb(bytesPerSecond) + "/s" + }); + HAC_BatchUploadProgress.updateSummary({ + percent: itemProgress, + title: currentItemTitle, + metaLeft: "已上传文件" + completedAttachmentCount + "/" + totalAttachments, + metaRight: attachmentName + " · " + HAC_FormatBytesAsMb(bytesPerSecond) + "/s" + }); + }); + + var record = records.find(function (record) { + return record && record.recordId === HAC_GetOfflineAttachmentRecordId(attachment); + }); + HAC_ApplyUploadedAttachmentValue(record, attachment, attachmentValue, uploadedValues); + completedAttachmentCount++; + HAC_BatchUploadProgress.updateSummary({ + percent: completedAttachmentCount / totalAttachments * 100, + title: currentItemTitle, + metaLeft: "已上传文件" + completedAttachmentCount + "/" + totalAttachments, + metaRight: attachmentName + " 已上传" + }); + } catch (e) { + HAC_BatchUploadProgress.errorItem(itemKey, "附件上传失败: " + (attachmentName || "未知")); + throw e; + } + } + + delete exportItem.attachments; + HAC_BatchUploadProgress.completeItem(itemKey); + } + + return exportDataArray; +} + var HAC_DothanPrinterOp = function (callback) { if (window.dothanPrinter) { var status = window.dothanPrinter.getStatus(); @@ -2652,3 +3101,1176 @@ var TSPLPrinterStandard_Print_Command = (function (_super) { Forguncy.CommandFactory.registerCommand("AndroidPDACommand.TSPLPrinterStandard_Print, AndroidPDACommand", TSPLPrinterStandard_Print_Command); + + +function HAC_OfflinePlusCreateFormNodeBuilder(context) { + let me = context; + + function evaluate(value) { + if (value === undefined || value === null) { + return value; + } + return me.evaluateFormula(value); + } + + function getList(value) { + return Array.isArray(value) ? value : []; + } + + function buildSelectOptions(options) { + return getList(options).map(function (option) { + return { + value: evaluate(option.Value), + label: evaluate(option.Label) + }; + }); + } + + function buildCheckOptions(options) { + if (!options) { + return undefined; + } + + var checkOptions = {}; + var minLength = evaluate(options.MinLength); + var maxLength = evaluate(options.MaxLength); + var regexPattern = evaluate(options.RegexPattern); + if (minLength !== undefined && minLength !== null && minLength !== "") { + checkOptions.minLength = minLength; + } + if (maxLength !== undefined && maxLength !== null && maxLength !== "") { + checkOptions.maxLength = maxLength; + } + if (regexPattern !== undefined && regexPattern !== null && regexPattern !== "") { + checkOptions.regexPattern = regexPattern; + } + return Object.keys(checkOptions).length > 0 ? checkOptions : undefined; + } + + function buildImageCompression(options) { + if (!options) { + return undefined; + } + + var compression = {}; + var maxLongEdge = evaluate(options.MaxLongEdge); + var jpegQuality = evaluate(options.JpegQuality); + var maxFileSizeKb = evaluate(options.MaxFileSizeKb); + var minQuality = evaluate(options.MinQuality); + compression.enableCompression = !!options.EnableCompression; + if (maxLongEdge !== undefined && maxLongEdge !== null && maxLongEdge !== "") { + compression.maxLongEdge = maxLongEdge; + } + if (jpegQuality !== undefined && jpegQuality !== null && jpegQuality !== "") { + compression.jpegQuality = jpegQuality; + } + if (maxFileSizeKb !== undefined && maxFileSizeKb !== null && maxFileSizeKb !== "") { + compression.maxFileSizeKb = maxFileSizeKb; + } + if (minQuality !== undefined && minQuality !== null && minQuality !== "") { + compression.minQuality = minQuality; + } + return Object.keys(compression).length > 0 ? compression : undefined; + } + + function buildImageWatermark(options) { + if (!options) { + return undefined; + } + + var fields = getList(options.Fields); + if (!options.EnableTimestamp && fields.length === 0) { + return undefined; + } + + var watermark = {}; + var items = fields.map(function (field) { + return { + key: field.Key, + value: evaluate(field.Value) + }; + }); + + if (options.EnableTimestamp) { + watermark.enableTimestamp = true; + } + if (items.length > 0) { + watermark.items = items; + } + return Object.keys(watermark).length > 0 ? watermark : undefined; + } + + function buildFileItemConfig(options) { + if (!options) { + return undefined; + } + + var config = {}; + var maxCount = evaluate(options.MaxCount); + var allowedExtensions = evaluate(options.AllowedExtensions); + var maxFileSizeKb = evaluate(options.MaxFileSizeKb); + if (maxCount !== undefined && maxCount !== null && maxCount !== "") { + config.maxCount = maxCount; + } + if (allowedExtensions !== undefined && allowedExtensions !== null && allowedExtensions !== "") { + config.allowedExtensions = allowedExtensions; + } + if (maxFileSizeKb !== undefined && maxFileSizeKb !== null && maxFileSizeKb !== "") { + config.maxFileSizeKb = maxFileSizeKb; + } + return Object.keys(config).length > 0 ? config : undefined; + } + + function buildSignatureUsers(options) { + if (!options) { + return []; + } + + if (options.UseUsersFormula) { + return getList(evaluate(options.UsersFormula)).map(function (user) { + if (user && typeof user === "object" && !Array.isArray(user)) { + return evaluate(user.Name); + } + return evaluate(user); + }).filter(function (userName) { + return userName !== undefined && userName !== null && String(userName).trim() !== ""; + }).map(function (userName) { + return String(userName); + }); + } + + return getList(options.Users).map(function (user) { + return evaluate(user && user.Name); + }).filter(function (userName) { + return userName !== undefined && userName !== null && String(userName).trim() !== ""; + }).map(function (userName) { + return String(userName); + }); + } + + function buildListItemOptions(node) { + var options = {}; + var listOptions = node.ListItemOptions || {}; + var minCount = evaluate(listOptions.MinCount); + var maxCount = evaluate(listOptions.MaxCount); + var defaultCount = evaluate(listOptions.DefaultCount); + var addButtonText = evaluate(listOptions.AddButtonText); + var itemTitle = evaluate(listOptions.ItemTitle); + var children = buildNodes(listOptions.Children); + + if (children.length === 0 && getList(node.Children).length > 0) { + children = buildNodes(node.Children); + } + + if (minCount !== undefined && minCount !== null && minCount !== "") { + options.minCount = minCount; + } + if (maxCount !== undefined && maxCount !== null && maxCount !== "") { + options.maxCount = maxCount; + } + if (defaultCount !== undefined && defaultCount !== null && defaultCount !== "") { + options.defaultCount = defaultCount; + } + if (addButtonText !== undefined && addButtonText !== null && addButtonText !== "") { + options.addButtonText = addButtonText; + } + if (itemTitle !== undefined && itemTitle !== null && itemTitle !== "") { + options.itemTitle = itemTitle; + } + if (children.length > 0) { + options.children = children; + } + return Object.keys(options).length > 0 ? options : undefined; + } + + var fieldTypeSpecs = { + textItem: { + apply: function (field, node) { + var checkOptions = buildCheckOptions(node.CheckOptions); + if (checkOptions) { + field.options = checkOptions; + } + } + }, + passwordItem: { + apply: function (field, node) { + var checkOptions = buildCheckOptions(node.CheckOptions); + if (checkOptions) { + field.options = checkOptions; + } + } + }, + selectItem: { + apply: function (field, node) { + var selectOptions = buildSelectOptions(node.SelectOptionsList); + if (selectOptions.length > 0) { + field.options = { + selectOptions: selectOptions + }; + } + } + }, + radioItem: { + apply: function (field, node) { + var options = {}; + var direction = node.RadioDirection || "horizontal"; + var selectOptions = buildSelectOptions(node.SelectOptionsList); + if (direction) { + options.direction = direction; + } + if (selectOptions.length > 0) { + options.selectOptions = selectOptions; + } + if (Object.keys(options).length > 0) { + field.options = options; + } + } + }, + datePicker: { + apply: function (field, node) { + field.options = { + includeTime: !!node.IncludeTime + }; + } + }, + timePicker: { + apply: function (field, node) { + if (node.IncludeSeconds) { + field.options = { + includeSeconds: true + }; + } + } + }, + imageItem: { + apply: function (field, node) { + var options = {}; + var maxCount = evaluate(node.MaxCount); + var compression = buildImageCompression(node.CompressionOptions); + var watermark = buildImageWatermark(node.WatermarkOptions); + if (maxCount !== undefined && maxCount !== null && maxCount !== "") { + options.maxCount = maxCount; + } + if (node.AllowImageUpload) { + options.allowImageUpload = true; + } + if (compression) { + options.compression = compression; + } + if (watermark) { + options.watermark = watermark; + } + if (Object.keys(options).length > 0) { + field.options = options; + } + } + }, + fileItem: { + apply: function (field, node) { + var config = buildFileItemConfig(node.FileItemConfig); + if (config) { + field.options = { + fileItemConfig: config + }; + } + } + }, + signatureItem: { + apply: function (field, node) { + var signatureOptions = node.SignatureOptions || {}; + var users = buildSignatureUsers(signatureOptions); + var disclaimer = evaluate(signatureOptions.Disclaimer); + if (users.length > 0) { + field.options = { + users: users + }; + if (disclaimer !== undefined && disclaimer !== null) { + field.options.disclaimer = String(disclaimer); + } + } + } + }, + listItem: { + apply: function (field, node) { + var options = buildListItemOptions(node); + if (options) { + field.options = options; + } + } + } + }; + + function applyFieldTypeSpec(field, node) { + var spec = fieldTypeSpecs[node.ItemType]; + if (spec && spec.apply) { + spec.apply(field, node); + } + } + + function buildField(node) { + var field = { + itemId: evaluate(node.ItemId), + itemType: node.ItemType, + title: evaluate(node.Title), + hint: evaluate(node.Hint), + required: !!node.Required + }; + + var value = evaluate(node.Value); + if (value !== undefined && value !== null && value !== "") { + field.value = value; + } + applyFieldTypeSpec(field, node); + return field; + } + + function buildNode(node, options) { + options = options || {}; + var nodeType = node.NodeType || "group"; + var children = getList(node.Children); + var isListField = nodeType === "field" && node.ItemType === "listItem"; + + if (nodeType !== "group" && !isListField && children.length > 0) { + console.warn("离线表单节点不是分组,但包含子节点。", node); + } + + var result; + if (nodeType === "field") { + result = { + nodeType: "field", + title: node.Text, + field: buildField(node) + }; + } else if (nodeType === "text") { + var textMode = node.TextMode || "plain"; + if (textMode === "progress") { + result = { + nodeType: "text", + title: node.Text, + textMode: "progress", + progressDisplay: { + total: !!node.ShowProgressTotal, + completed: !!node.ShowProgressCompleted, + completionRate: !!node.ShowProgressCompletionRate + } + }; + } else if (textMode === "document") { + result = { + nodeType: "text", + title: node.Text, + textMode: "document" + }; + } else { + // Preserve the existing JSON shape for the default text mode. + result = { + nodeType: "text", + title: node.Text, + content: evaluate(node.Content) + }; + } + } else { + result = { + nodeType: "group", + title: node.Text, + defaultCollapsed: !!node.DefaultCollapsed, + children: buildNodes(children, { + allowProgressIdentifier: !!options.isStepRoot && !!node.EnableProgress + }) + }; + } + + if (options.isStepRoot && nodeType === "group" && node.EnableProgress) { + result.enableProgress = true; + } + if (nodeType === "field" && (options.isStepRoot || options.allowProgressIdentifier) && node.ProgressIdentifier) { + result.progressIdentifier = true; + } + return result; + } + + function buildNodes(nodes, options) { + return getList(nodes).map(function (node) { + return buildNode(node, options); + }); + } + + function buildFormItem(nodes) { + var items = buildNodes(nodes, { isStepRoot: true }); + if (items.length <= 1) { + return items[0]; + } + + var timestamp = new Date().getTime(); + return { + nodeType: "group", + key: "offlineFormItemGroup_" + timestamp, + title: "页面内容分组_" + timestamp, + defaultCollapsed: false, + children: items + }; + } + + return { + evaluate: evaluate, + getList: getList, + buildNode: buildNode, + buildNodes: buildNodes, + buildFormItem: buildFormItem + }; +} + +var OfflinePlusBuildFormItem_Command = (function (_super) { + __extends(OfflinePlusBuildFormItem_Command, _super); + function OfflinePlusBuildFormItem_Command() { + return _super !== null && _super.apply(this, arguments) || this; + } + + OfflinePlusBuildFormItem_Command.prototype.execute = function () { + let params = this.CommandParam; + var formNodeBuilder = HAC_OfflinePlusCreateFormNodeBuilder(this); + var item = formNodeBuilder.buildFormItem(params.Items); + HAC_ReturnToParam(params.ItemResult, item); + }; + + return OfflinePlusBuildFormItem_Command; +}(Forguncy.CommandBase)); + +Forguncy.CommandFactory.registerCommand("AndroidPDACommand.OfflinePlusBuildFormItem, AndroidPDACommand", OfflinePlusBuildFormItem_Command); + +var OfflinePlusBuildPattern_Command = (function (_super) { + __extends(OfflinePlusBuildPattern_Command, _super); + function OfflinePlusBuildPattern_Command() { + return _super !== null && _super.apply(this, arguments) || this; + } + + OfflinePlusBuildPattern_Command.prototype.execute = function () { + + let params = this.CommandParam; + var formNodeBuilder = HAC_OfflinePlusCreateFormNodeBuilder(this); + + function buildSteps(steps) { + return formNodeBuilder.getList(steps).map(function (step) { + return { + stepId: formNodeBuilder.evaluate(step.StepId), + title: formNodeBuilder.evaluate(step.Title), + items: step.UseItemsFormula ? formNodeBuilder.evaluate(step.ItemsFormula) : formNodeBuilder.buildNodes(step.Items, { isStepRoot: true }) + }; + }); + } + + const steps = buildSteps(params.Steps); + let patternParam = { + patternId: formNodeBuilder.evaluate(params.PatternId), + schemaVersion: formNodeBuilder.evaluate(params.SchemaVersion), + title: formNodeBuilder.evaluate(params.Title), + description: formNodeBuilder.evaluate(params.Description), + steps: steps + }; + + var patternParamJson = JSON.stringify(patternParam, null, 2); + console.log(patternParam); + HAC_ReturnToParam(params.PatternJson, patternParamJson); + }; + + + return OfflinePlusBuildPattern_Command; +}(Forguncy.CommandBase)); + +Forguncy.CommandFactory.registerCommand("AndroidPDACommand.OfflinePlusBuildPattern, AndroidPDACommand", OfflinePlusBuildPattern_Command); + +function HAC_OfflinePlusValidatePatternJson(patternJson) { + function fail(path, message) { + return { isValid: false, error: path + ":" + message }; + } + + function isObject(value) { + return value !== null && typeof value === "object" && !Array.isArray(value); + } + + function isBlank(value) { + return value === undefined || value === null || (typeof value === "string" && value.trim() === ""); + } + + function validateNonNegativeNumber(value, path) { + if (value !== undefined && value !== null && value !== "" && + (typeof value !== "number" || !isFinite(value) || value < 0)) { + return fail(path, "必须是大于或等于0的数字:" + value); + } + return null; + } + + function validateSelectOptions(selectOptions, path) { + if (!Array.isArray(selectOptions) || selectOptions.length === 0) { + return fail(path, "必须是非空数组"); + } + for (var optionIndex = 0; optionIndex < selectOptions.length; optionIndex++) { + var optionPath = path + "[" + optionIndex + "]"; + if (!isObject(selectOptions[optionIndex])) { + return fail(optionPath, "必须是对象"); + } + if (isBlank(selectOptions[optionIndex].value)) { + return fail(optionPath + ".value", "不能为空"); + } + if (isBlank(selectOptions[optionIndex].label)) { + return fail(optionPath + ".label", "不能为空"); + } + } + return null; + } + + function validateNode(node, path, itemIds, allowListItem) { + if (allowListItem === undefined) { + allowListItem = true; + } + + if (!isObject(node)) { + return fail(path, "必须是对象"); + } + + var nodeType = node.nodeType; + if (["group", "text", "field"].indexOf(nodeType) < 0) { + return fail(path + ".nodeType", "必须是group、text或field"); + } + if (node.enableProgress !== undefined && typeof node.enableProgress !== "boolean") { + return fail(path + ".enableProgress", "必须是布尔值"); + } + if (node.progressIdentifier !== undefined && typeof node.progressIdentifier !== "boolean") { + return fail(path + ".progressIdentifier", "必须是布尔值"); + } + + if (nodeType === "group") { + if (!Array.isArray(node.children)) { + return fail(path + ".children", "必须是数组"); + } + for (var groupIndex = 0; groupIndex < node.children.length; groupIndex++) { + var groupError = validateNode(node.children[groupIndex], path + ".children[" + groupIndex + "]", itemIds, allowListItem); + if (groupError) { + return groupError; + } + } + return null; + } + + if (nodeType === "text") { + var textMode = node.textMode || "plain"; + if (["plain", "progress", "document"].indexOf(textMode) < 0) { + return fail(path + ".textMode", "必须是plain、progress或document"); + } + if (textMode === "progress") { + if (!isObject(node.progressDisplay)) { + return fail(path + ".progressDisplay", "必须是对象"); + } + var progressDisplay = node.progressDisplay; + var progressDisplayProperties = ["total", "completed", "completionRate"]; + for (var progressDisplayIndex = 0; progressDisplayIndex < progressDisplayProperties.length; progressDisplayIndex++) { + var progressDisplayProperty = progressDisplayProperties[progressDisplayIndex]; + if (typeof progressDisplay[progressDisplayProperty] !== "boolean") { + return fail(path + ".progressDisplay." + progressDisplayProperty, "必须是布尔值"); + } + } + return null; + } + if (textMode === "document") { + return null; + } + if (node.content === undefined || node.content === null) { + return fail(path + ".content", "缺少说明内容"); + } + return null; + } + + if (!isObject(node.field)) { + return fail(path + ".field", "必须是对象"); + } + + var field = node.field; + if (isBlank(field.itemId)) { + return fail(path + ".field.itemId", "不能为空"); + } + var itemIdKey = String(field.itemId); + if (itemIds[itemIdKey]) { + return fail(path + ".field.itemId", "与" + itemIds[itemIdKey] + "重复"); + } + itemIds[itemIdKey] = path + ".field.itemId"; + + var itemTypes = ["textItem", "passwordItem", "selectItem", "radioItem", "datePicker", "timePicker", "imageItem", "fileItem", "signatureItem"]; + if (allowListItem) { + itemTypes.push("listItem"); + } + if (itemTypes.indexOf(field.itemType) < 0) { + return fail(path + ".field.itemType", "是不支持的表单项类型"); + } + if (isBlank(field.title)) { + return fail(path + ".field.title", "不能为空"); + } + if (field.required !== undefined && typeof field.required !== "boolean") { + return fail(path + ".field.required", "必须是布尔值"); + } + if (field.options !== undefined && !isObject(field.options)) { + return fail(path + ".field.options", "必须是对象"); + } + + var options = field.options || {}; + var numberError; + if (field.itemType === "datePicker") { + if (options.includeTime !== undefined && typeof options.includeTime !== "boolean") { + return fail(path + ".field.options.includeTime", "必须是布尔值"); + } + } else if (field.itemType === "timePicker") { + if (options.includeSeconds !== undefined && typeof options.includeSeconds !== "boolean") { + return fail(path + ".field.options.includeSeconds", "必须是布尔值"); + } + } else if (field.itemType === "selectItem") { + var selectError = validateSelectOptions(options.selectOptions, path + ".field.options.selectOptions"); + if (selectError) { + return selectError; + } + } else if (field.itemType === "radioItem") { + if (options.direction !== undefined && ["horizontal", "vertical"].indexOf(options.direction) < 0) { + return fail(path + ".field.options.direction", "必须是horizontal或vertical"); + } + var radioError = validateSelectOptions(options.selectOptions, path + ".field.options.selectOptions"); + if (radioError) { + return radioError; + } + } else if (field.itemType === "signatureItem") { + if (!Array.isArray(options.users) || options.users.length === 0) { + return fail(path + ".field.options.users", "必须是非空数组"); + } + for (var userIndex = 0; userIndex < options.users.length; userIndex++) { + if (typeof options.users[userIndex] !== "string" || isBlank(options.users[userIndex])) { + return fail(path + ".field.options.users[" + userIndex + "]", "必须是非空字符串"); + } + } + if (options.disclaimer !== undefined && typeof options.disclaimer !== "string") { + return fail(path + ".field.options.disclaimer", "必须是字符串"); + } + } else if (field.itemType === "listItem") { + if (!Array.isArray(options.children) || options.children.length === 0) { + return fail(path + ".field.options.children", "必须是非空数组"); + } + numberError = validateNonNegativeNumber(options.minCount, path + ".field.options.minCount") || + validateNonNegativeNumber(options.maxCount, path + ".field.options.maxCount") || + validateNonNegativeNumber(options.defaultCount, path + ".field.options.defaultCount"); + if (numberError) { + return numberError; + } + for (var listIndex = 0; listIndex < options.children.length; listIndex++) { + var listError = validateNode(options.children[listIndex], path + ".field.options.children[" + listIndex + "]", itemIds, false); + if (listError) { + return listError; + } + } + } else if (field.itemType === "imageItem") { + numberError = validateNonNegativeNumber(options.maxCount, path + ".field.options.maxCount"); + if (numberError) { + return numberError; + } + } + + return null; + } + + if (patternJson === undefined || patternJson === null || patternJson === "") { + return fail("$", "离线表单JSON不能为空"); + } + + var pattern; + try { + pattern = typeof patternJson === "string" ? JSON.parse(patternJson) : patternJson; + } catch (e) { + return fail("$", "JSON格式不正确" + (e && e.message ? "(" + e.message + ")" : "")); + } + + if (!isObject(pattern)) { + return fail("$", "根节点必须是对象"); + } + if (isBlank(pattern.patternId)) { + return fail("$.patternId", "不能为空"); + } + if (isBlank(pattern.schemaVersion)) { + return fail("$.schemaVersion", "不能为空"); + } + if (isBlank(pattern.title)) { + return fail("$.title", "不能为空"); + } + if (!Array.isArray(pattern.steps) || pattern.steps.length === 0) { + return fail("$.steps", "必须是非空数组"); + } + + var stepIds = Object.create(null); + var itemIds = Object.create(null); + for (var stepIndex = 0; stepIndex < pattern.steps.length; stepIndex++) { + var step = pattern.steps[stepIndex]; + var stepPath = "$.steps[" + stepIndex + "]"; + if (!isObject(step)) { + return fail(stepPath, "必须是对象"); + } + if (isBlank(step.stepId)) { + return fail(stepPath + ".stepId", "不能为空"); + } + var stepIdKey = String(step.stepId); + if (stepIds[stepIdKey]) { + return fail(stepPath + ".stepId", "与" + stepIds[stepIdKey] + "重复"); + } + stepIds[stepIdKey] = stepPath + ".stepId"; + if (isBlank(step.title)) { + return fail(stepPath + ".title", "不能为空"); + } + if (!Array.isArray(step.items) || step.items.length === 0) { + console.log(Array.isArray(step.items) + "-" + step.items.length) + return fail(stepPath + ".items", "必须是非空数组"); + } + for (var itemIndex = 0; itemIndex < step.items.length; itemIndex++) { + var itemError = validateNode(step.items[itemIndex], stepPath + ".items[" + itemIndex + "]", itemIds, true); + if (itemError) { + return itemError; + } + } + } + + return { isValid: true, error: "", value: pattern }; +} + +var OfflinePlusValidatePatternJson_Command = (function (_super) { + __extends(OfflinePlusValidatePatternJson_Command, _super); + function OfflinePlusValidatePatternJson_Command() { + return _super !== null && _super.apply(this, arguments) || this; + } + + OfflinePlusValidatePatternJson_Command.prototype.execute = function () { + var params = this.CommandParam; + var patternJson = this.evaluateFormula(params.PatternJson); + var result = HAC_OfflinePlusValidatePatternJson(patternJson); + HAC_ReturnToParam(params.IsValidResult, result.isValid); + HAC_ReturnToParam(params.ErrorResult, result.error); + }; + + return OfflinePlusValidatePatternJson_Command; +}(Forguncy.CommandBase)); + +Forguncy.CommandFactory.registerCommand("AndroidPDACommand.OfflinePlusValidatePatternJson, AndroidPDACommand", OfflinePlusValidatePatternJson_Command); + +var OfflinePlusAddPattern_Async_Command = (function (_super) { + __extends(OfflinePlusAddPattern_Async_Command, _super); + function OfflinePlusAddPattern_Async_Command() { + return _super !== null && _super.apply(this, arguments) || this; + } + + OfflinePlusAddPattern_Async_Command.prototype.execute = async function () { + + let me = this; + let params = this.CommandParam; + let finalPatternParamJson = ""; + + function evaluate(value) { + if (value === undefined || value === null) { + return value; + } + return me.evaluateFormula(value); + } + + function applyFieldUpdateTime(pattern) { + var now = new Date(); + var updateTime = (now.getTime() - now.getTimezoneOffset() * 60000) / 86400000 + 25569; + + function applyToNodes(nodes) { + if (!Array.isArray(nodes)) { + return; + } + + nodes.forEach(function (node) { + if (!node || typeof node !== "object") { + return; + } + + if (node.nodeType === "field" && node.field && typeof node.field === "object") { + node.field.updateTime = updateTime; + if (node.field.itemType === "listItem" && node.field.options) { + applyToNodes(node.field.options.children); + } + return; + } + + if (node.nodeType === "group") { + applyToNodes(node.children); + } + }); + } + + if (pattern && Array.isArray(pattern.steps)) { + pattern.steps.forEach(function (step) { + if (step && typeof step === "object") { + applyToNodes(step.items); + } + }); + } + } + + var patternJson = evaluate(params.PatternJson); + var validationResult = HAC_OfflinePlusValidatePatternJson(patternJson); + if (!validationResult.isValid) { + alert("离线表单JSON不正确:" + validationResult.error); + return; + } + var patternParam = validationResult.value; + + let ticket = HAC_GenerateCallbackTicket(me, function (payload, payload2) { + // alert("离线表单项目设置成功\r\n\r\nJSON Schema:\r\n" + finalPatternParamJson); + me.CommandExecutor.excuteCommand(me.CommandParam.CommandList, { + runTimePageName: me.CommandExecutingInfo.runTimePageName, + commandID: new Date().valueOf().toString(), + initParams: { + "IsSuccess": true, + "Error": "" + }, + locationString: "执行window.offlinePlus.offlinePlusAddPattern" + }); + }, HAC_GetOfflinePlusDebugInfo("下载离线表单", "生成回调ticket")); + if (!ticket) { + console.error(HAC_GetOfflinePlusDebugInfo("下载离线表单", "生成回调ticket失败")); + return; + } + + applyFieldUpdateTime(patternParam); + patternParam.ticket = ticket; + finalPatternParamJson = JSON.stringify(patternParam, null, 2); + + console.log(patternParam); + if (window.offlinePlus && window.offlinePlus.offlinePlusAddPatternAsync) { + window.offlinePlus.offlinePlusAddPatternAsync(finalPatternParamJson); + } else { + HAC_CallFunctionOutOfHAC(HAC_GetOfflinePlusDebugInfo("下载离线表单", "调用offlinePlusAddPatternAsync")); + } + }; + + + return OfflinePlusAddPattern_Async_Command; +}(Forguncy.CommandBase)); + +Forguncy.CommandFactory.registerCommand("AndroidPDACommand.OfflinePlusAddPattern_Async, AndroidPDACommand", OfflinePlusAddPattern_Async_Command); + +var OfflinePlusDownloadManualPdf_Async_Command = (function (_super) { + __extends(OfflinePlusDownloadManualPdf_Async_Command, _super); + function OfflinePlusDownloadManualPdf_Async_Command() { + return _super !== null && _super.apply(this, arguments) || this; + } + + OfflinePlusDownloadManualPdf_Async_Command.prototype.execute = function () { + var me = this; + var params = this.CommandParam; + var patternId = this.evaluateFormula(params.PatternId); + var manualAttachmentValue = this.evaluateFormula(params.ManualAttachmentCell); + var manualPdfUrl = HAC_GetOfflinePlusManualPdfUrl(manualAttachmentValue); + + var ticket = HAC_GenerateCallbackTicket(me, function (payload, payload2) { + me.CommandExecutor.excuteCommand(me.CommandParam.CommandList, { + runTimePageName: me.CommandExecutingInfo.runTimePageName, + commandID: new Date().valueOf().toString(), + initParams: { + "IsSuccess": true, + "Error": "" + }, + locationString: "执行window.offlinePlus.offlinePlusDownloadManualPdfAsync" + }); + }, HAC_GetOfflinePlusDebugInfo("下载绑定说明PDF", "生成回调ticket")); + if (!ticket) { + console.error(HAC_GetOfflinePlusDebugInfo("下载绑定说明PDF", "生成回调ticket失败")); + return; + } + + if (window.offlinePlus && window.offlinePlus.offlinePlusDownloadManualPdfAsync) { + window.offlinePlus.offlinePlusDownloadManualPdfAsync(patternId, manualPdfUrl, ticket); + } else { + HAC_CallFunctionOutOfHAC(HAC_GetOfflinePlusDebugInfo("下载绑定说明PDF", "调用offlinePlusDownloadManualPdfAsync")); + } + }; + + return OfflinePlusDownloadManualPdf_Async_Command; +}(Forguncy.CommandBase)); + +Forguncy.CommandFactory.registerCommand("AndroidPDACommand.OfflinePlusDownloadManualPdf_Async, AndroidPDACommand", OfflinePlusDownloadManualPdf_Async_Command); + +var OfflinePlusGetPatterns_Async_Command = (function (_super) { + __extends(OfflinePlusGetPatterns_Async_Command, _super); + function OfflinePlusGetPatterns_Async_Command() { + return _super !== null && _super.apply(this, arguments) || this; + } + + OfflinePlusGetPatterns_Async_Command.prototype.execute = function () { + var params = this.CommandParam; + var action = params.Action || "GetPatterns"; + + if (action === "ExportRecords") { + if (!HAC_OfflineExportExecution.begin()) { + return; + } + var projectId = this.evaluateFormula(params.ProjectId); + var fileUploadLimit = (params.ServerPropertiesId && params.ServerPropertiesId.FileUploadLimit) || ""; + let me = this; + HAC_OfflineUploadProgress.update({ + percent: 0, + title: "正在上传离线附件", + detail: "正在读取设备上的离线数据", + speed: "" + }); + let ticket = HAC_GenerateCallbackTicket(me, async function (payload, payload2) { + try { + var exportData = JSON.parse(payload); + if (exportData) { + exportData = await HAC_ProcessOfflineExportAttachments(projectId, exportData, fileUploadLimit); + payload = JSON.stringify(exportData); + } + HAC_ReturnToParam(params.ExportResult, payload); + me.CommandExecutor.excuteCommand(me.CommandParam.CommandList, { + runTimePageName: me.CommandExecutingInfo.runTimePageName, + commandID: new Date().valueOf().toString(), + initParams: { + "ExportResult": payload, + "IsSuccess": true, + "Error": "" + }, + locationString: "执行window.offlinePlus.offlinePlusExportRecordsAsync" + }); + } catch (e) { + me.CommandExecutor.excuteCommand(me.CommandParam.CommandList, { + runTimePageName: me.CommandExecutingInfo.runTimePageName, + commandID: new Date().valueOf().toString(), + initParams: { + "ExportResult": payload, + "IsSuccess": false, + "Error": e ? e.toString() : "导出离线附件失败。" + }, + locationString: "处理离线附件上传时出错" + }); + } finally { + HAC_OfflineUploadProgress.close(); + HAC_OfflineExportExecution.complete(); + } + }, HAC_GetOfflinePlusDebugInfo("上传离线表单", "生成导出数据回调ticket"), function () { + HAC_OfflineUploadProgress.close(); + HAC_OfflineExportExecution.complete(); + }); + + if (!ticket) { + HAC_OfflineUploadProgress.close(); + HAC_OfflineExportExecution.complete(); + return; + } + + if (window.offlinePlus && window.offlinePlus.offlinePlusExportRecordsAsync) { + try { + window.offlinePlus.offlinePlusExportRecordsAsync(projectId, ticket); + } catch (e) { + HAC_OfflineUploadProgress.close(); + HAC_OfflineExportExecution.complete(); + throw e; + } + } else { + HAC_CallFunctionOutOfHAC(HAC_GetOfflinePlusDebugInfo("上传离线表单", "调用offlinePlusExportRecordsAsync")); + HAC_OfflineUploadProgress.close(); + HAC_OfflineExportExecution.complete(); + } + return; + } + + if (action === "MarkRecordExported") { + var projectId = this.evaluateFormula(params.ProjectId); + var recordIds = this.evaluateFormula(params.RecordIds); + let me = this; + let ticket = HAC_GenerateCallbackTicket(me, function (payload, payload2) { + HAC_ReturnToParam(params.OperationResult, payload); + me.CommandExecutor.excuteCommand(me.CommandParam.CommandList, { + runTimePageName: me.CommandExecutingInfo.runTimePageName, + commandID: new Date().valueOf().toString(), + initParams: { + "OperationResult": payload, + "IsSuccess": true, + "Error": "" + }, + locationString: "执行window.offlinePlus.offlinePlusMarkRecordExportedAsync" + }); + }, HAC_GetOfflinePlusDebugInfo("上传离线表单", "生成标记导出回调ticket")); + + if (window.offlinePlus && window.offlinePlus.offlinePlusMarkRecordExportedAsync) { + window.offlinePlus.offlinePlusMarkRecordExportedAsync(projectId, recordIds, ticket); + } else { + HAC_CallFunctionOutOfHAC(HAC_GetOfflinePlusDebugInfo("上传离线表单", "调用offlinePlusMarkRecordExportedAsync")); + } + return; + } + + if (action === "DeleteReadRecords") { + var projectId = this.evaluateFormula(params.ProjectId); + var recordIds = this.evaluateFormula(params.RecordIds); + let me = this; + let ticket = HAC_GenerateCallbackTicket(me, function (payload, payload2) { + HAC_ReturnToParam(params.OperationResult, payload); + me.CommandExecutor.excuteCommand(me.CommandParam.CommandList, { + runTimePageName: me.CommandExecutingInfo.runTimePageName, + commandID: new Date().valueOf().toString(), + initParams: { + "OperationResult": payload, + "IsSuccess": true, + "Error": "" + }, + locationString: "执行window.offlinePlus.offlinePlusDeleteReadRecordsAsync" + }); + }, HAC_GetOfflinePlusDebugInfo("上传离线表单", "生成删除已读记录回调ticket")); + + if (window.offlinePlus && window.offlinePlus.offlinePlusDeleteReadRecordsAsync) { + window.offlinePlus.offlinePlusDeleteReadRecordsAsync(projectId, recordIds, ticket); + } else { + HAC_CallFunctionOutOfHAC(HAC_GetOfflinePlusDebugInfo("上传离线表单", "调用offlinePlusDeleteReadRecordsAsync")); + } + return; + } + + if (action === "DeleteProject") { + var projectId = this.evaluateFormula(params.ProjectId); + let me = this; + let ticket = HAC_GenerateCallbackTicket(me, function (payload, payload2) { + HAC_ReturnToParam(params.OperationResult, payload); + me.CommandExecutor.excuteCommand(me.CommandParam.CommandList, { + runTimePageName: me.CommandExecutingInfo.runTimePageName, + commandID: new Date().valueOf().toString(), + initParams: { + "OperationResult": payload, + "IsSuccess": true, + "Error": "" + }, + locationString: "执行window.offlinePlus.offlinePlusDeleteProjectAsync" + }); + }, HAC_GetOfflinePlusDebugInfo("上传离线表单", "生成删除离线表单项目回调ticket")); + + if (window.offlinePlus && window.offlinePlus.offlinePlusDeleteProjectAsync) { + window.offlinePlus.offlinePlusDeleteProjectAsync(projectId, ticket); + } else { + HAC_CallFunctionOutOfHAC(HAC_GetOfflinePlusDebugInfo("上传离线表单", "调用offlinePlusDeleteProjectAsync")); + } + return; + } + + if (action === "BatchExportRecords") { + if (!HAC_OfflineExportExecution.begin()) { + return; + } + var fileUploadLimit = (params.ServerPropertiesId && params.ServerPropertiesId.FileUploadLimit) || ""; + let me = this; + HAC_BatchUploadProgress.ensure(0); + HAC_BatchUploadProgress.updateSummary({ + percent: 0, + title: "准备导出", + metaLeft: "正在读取设备数据", + metaRight: "" + }); + let ticket = HAC_GenerateCallbackTicket(me, async function (payload, payload2) { + var batchExportError = ""; + var batchExportPayload = payload; + var batchExportSuccess = false; + try { + var exportDataArray = JSON.parse(payload); + if (exportDataArray && Array.isArray(exportDataArray)) { + exportDataArray = await HAC_ProcessBatchExportAttachments(exportDataArray, fileUploadLimit); + batchExportPayload = JSON.stringify(exportDataArray); + } + batchExportSuccess = true; + } catch (e) { + batchExportError = e ? e.toString() : "批量导出离线表单数据失败。"; + } + var continueBatchExport = function () { + HAC_OfflineExportExecution.complete(); + if (batchExportSuccess) { + HAC_ReturnToParam(params.ExportResult, batchExportPayload); + me.CommandExecutor.excuteCommand(me.CommandParam.CommandList, { + runTimePageName: me.CommandExecutingInfo.runTimePageName, + commandID: new Date().valueOf().toString(), + initParams: { + "ExportResult": batchExportPayload, + "IsSuccess": true, + "Error": "" + }, + locationString: "执行window.offlinePlus.offlinePlusExportMultipleRecordsAsync" + }); + } else { + me.CommandExecutor.excuteCommand(me.CommandParam.CommandList, { + runTimePageName: me.CommandExecutingInfo.runTimePageName, + commandID: new Date().valueOf().toString(), + initParams: { + "ExportResult": batchExportPayload, + "IsSuccess": false, + "Error": batchExportError + }, + locationString: "批量导出离线表单数据时出错" + }); + } + }; + HAC_BatchUploadProgress.finish({ + success: batchExportSuccess, + error: batchExportError, + onConfirm: continueBatchExport + }); + }, HAC_GetOfflinePlusDebugInfo("批量导出离线表单", "生成批量导出回调ticket"), function (error) { + HAC_BatchUploadProgress.finish({ + success: false, + error: error, + onConfirm: function () { + HAC_OfflineExportExecution.complete(); + } + }); + }); + + if (!ticket) { + HAC_BatchUploadProgress.close(); + HAC_OfflineExportExecution.complete(); + return; + } + + if (window.offlinePlus && window.offlinePlus.offlinePlusExportMultipleRecordsAsync) { + try { + window.offlinePlus.offlinePlusExportMultipleRecordsAsync(ticket); + } catch (e) { + HAC_BatchUploadProgress.close(); + HAC_OfflineExportExecution.complete(); + throw e; + } + } else { + HAC_CallFunctionOutOfHAC(HAC_GetOfflinePlusDebugInfo("批量导出离线表单", "调用offlinePlusExportMultipleRecordsAsync")); + HAC_BatchUploadProgress.close(); + HAC_OfflineExportExecution.complete(); + } + return; + } + + if (action !== "GetPatterns") { + alert("不支持的离线表单上传动作:" + action); + return; + } + + let me = this; + + let ticket = HAC_GenerateCallbackTicket(me, function (payload, payload2) { + HAC_ReturnToParam(params.ProjectsResult, payload); + me.CommandExecutor.excuteCommand(me.CommandParam.CommandList, { + runTimePageName: me.CommandExecutingInfo.runTimePageName, + commandID: new Date().valueOf().toString(), + initParams: { + "ProjectsResult": payload, + "IsSuccess": true, + "Error": "" + }, + locationString: "执行window.offlinePlus.offlinePlusGetPatternsAsync" + }); + }, HAC_GetOfflinePlusDebugInfo("上传离线表单", "生成回调ticket")); + + if (window.offlinePlus && window.offlinePlus.offlinePlusGetPatternsAsync) { + window.offlinePlus.offlinePlusGetPatternsAsync(ticket); + } else { + HAC_CallFunctionOutOfHAC(HAC_GetOfflinePlusDebugInfo("上传离线表单", "调用offlinePlusGetPatternsAsync")); + } + }; + + return OfflinePlusGetPatterns_Async_Command; +}(Forguncy.CommandBase)); + +Forguncy.CommandFactory.registerCommand("AndroidPDACommand.OfflinePlusGetPatterns_Async, AndroidPDACommand", OfflinePlusGetPatterns_Async_Command); diff --git a/Resources/Icon_OfflineBuild.png b/Resources/Icon_OfflineBuild.png new file mode 100644 index 0000000000000000000000000000000000000000..9430bea9db1a5a7f715d3ae3259bade60d8e00cb Binary files /dev/null and b/Resources/Icon_OfflineBuild.png differ diff --git a/Resources/Icon_OfflineDownload.png b/Resources/Icon_OfflineDownload.png new file mode 100644 index 0000000000000000000000000000000000000000..1295a66c444353576d3580da122e425f19b457b9 Binary files /dev/null and b/Resources/Icon_OfflineDownload.png differ diff --git a/Resources/Icon_OfflineFormItem.png b/Resources/Icon_OfflineFormItem.png new file mode 100644 index 0000000000000000000000000000000000000000..26e42e6d02f98faf21b2d29902644cb786662b0b Binary files /dev/null and b/Resources/Icon_OfflineFormItem.png differ diff --git a/Resources/Icon_OfflineUpload.png b/Resources/Icon_OfflineUpload.png new file mode 100644 index 0000000000000000000000000000000000000000..cb7876aa0535f3281c9228c20470eeb39031e1e6 Binary files /dev/null and b/Resources/Icon_OfflineUpload.png differ diff --git a/Resources/OfflinePlusExportProgress.js b/Resources/OfflinePlusExportProgress.js new file mode 100644 index 0000000000000000000000000000000000000000..2012c63b28c343e0b3265a62c0339ef7e43fa77a --- /dev/null +++ b/Resources/OfflinePlusExportProgress.js @@ -0,0 +1,504 @@ +/** + * 离线表单导出进度与执行状态组件。 + * 此文件必须先于 AndroidPDACommand.js 加载。 + */ +var HAC_OfflineExportExecution = { + isRunning: false, + begin: function () { + if (this.isRunning) { + alert("上一个导出动作尚未完成,请等待上一个导出完成。"); + return false; + } + this.isRunning = true; + return true; + }, + complete: function () { + this.isRunning = false; + } +}; +/** + * 离线附件上传进度显示组件 + */ +var HAC_OfflineUploadProgress = { + element: null, + panel: null, + collapseButton: null, + collapsedButton: null, + fill: null, + title: null, + detail: null, + speed: null, + preventScrollHandler: null, + collapseButtonHandler: null, + collapsedButtonHandler: null, + collapsed: false, + bodyOverflow: null, + documentOverflow: null, + ensure: function () { + if (this.element) { + return; + } + var root = document.createElement("div"); + root.style.cssText = "position:fixed;left:0;top:0;right:0;bottom:0;z-index:2147483647;background:rgba(0,0,0,.28);display:flex;align-items:center;justify-content:center;font-family:Arial,'Microsoft YaHei',sans-serif;touch-action:none;overscroll-behavior:contain;"; + root.innerHTML = "
" + + "
正在上传离线附件
" + + "
" + + "
" + + "
" + + "
" + + ""; + this.bodyOverflow = document.body.style.overflow; + this.documentOverflow = document.documentElement.style.overflow; + document.body.style.overflow = "hidden"; + document.documentElement.style.overflow = "hidden"; + this.preventScrollHandler = function (event) { + if (this.collapsed) { + return; + } + event.preventDefault(); + }.bind(this); + root.addEventListener("touchmove", this.preventScrollHandler, { passive: false }); + document.body.appendChild(root); + this.element = root; + this.panel = root.querySelector("[data-role='panel']"); + this.collapseButton = root.querySelector("[data-role='collapse']"); + this.collapsedButton = root.querySelector("[data-role='collapsed']"); + this.fill = root.querySelector("[data-role='fill']"); + this.title = root.querySelector("[data-role='title']"); + this.detail = root.querySelector("[data-role='detail']"); + this.speed = root.querySelector("[data-role='speed']"); + this.collapseButtonHandler = function () { + this.collapse(); + }.bind(this); + this.collapsedButtonHandler = function () { + this.expand(); + }.bind(this); + this.collapseButton.addEventListener("click", this.collapseButtonHandler); + this.collapsedButton.addEventListener("click", this.collapsedButtonHandler); + }, + lockPage: function () { + document.body.style.overflow = "hidden"; + document.documentElement.style.overflow = "hidden"; + }, + unlockPage: function () { + document.body.style.overflow = this.bodyOverflow || ""; + document.documentElement.style.overflow = this.documentOverflow || ""; + }, + collapse: function () { + this.ensure(); + this.collapsed = true; + this.panel.style.display = "none"; + this.collapsedButton.style.display = "block"; + this.element.style.background = "transparent"; + this.element.style.pointerEvents = "none"; + this.unlockPage(); + }, + expand: function () { + this.ensure(); + this.collapsed = false; + this.panel.style.display = "block"; + this.collapsedButton.style.display = "none"; + this.element.style.background = "rgba(0,0,0,.28)"; + this.element.style.pointerEvents = "auto"; + this.lockPage(); + }, + update: function (options) { + this.ensure(); + var percent = Math.max(0, Math.min(100, options.percent || 0)); + this.fill.style.width = percent.toFixed(1) + "%"; + this.title.textContent = options.title || "正在上传离线附件"; + this.detail.textContent = options.detail || ""; + this.speed.textContent = options.speed || ""; + this.collapsedButton.querySelector("[data-role='collapsed-title']").textContent = options.title || "正在上传离线附件"; + this.collapsedButton.querySelector("[data-role='collapsed-percent']").textContent = Math.floor(percent) + "%"; + }, + close: function () { + if (this.element && this.preventScrollHandler) { + this.element.removeEventListener("touchmove", this.preventScrollHandler); + } + if (this.collapseButton && this.collapseButtonHandler) { + this.collapseButton.removeEventListener("click", this.collapseButtonHandler); + } + if (this.collapsedButton && this.collapsedButtonHandler) { + this.collapsedButton.removeEventListener("click", this.collapsedButtonHandler); + } + if (this.element && this.element.parentNode) { + this.element.parentNode.removeChild(this.element); + } + this.unlockPage(); + this.element = null; + this.panel = null; + this.collapseButton = null; + this.collapsedButton = null; + this.fill = null; + this.title = null; + this.detail = null; + this.speed = null; + this.preventScrollHandler = null; + this.collapseButtonHandler = null; + this.collapsedButtonHandler = null; + this.collapsed = false; + this.bodyOverflow = null; + this.documentOverflow = null; + } +}; + +/** + * 批量离线附件上传进度显示组件 - 支持多行显示多个表单状态 + */ +var HAC_BatchUploadProgress = { + element: null, + panel: null, + collapseButton: null, + collapsedButton: null, + title: null, + countLabel: null, + listContainer: null, + summaryLabel: null, + currentTitle: null, + percentLabel: null, + fill: null, + metaLeft: null, + metaRight: null, + confirmButton: null, + itemMap: {}, + preventScrollHandler: null, + buttonClickHandler: null, + collapseButtonHandler: null, + collapsedButtonHandler: null, + confirmHandler: null, + collapsed: false, + bodyOverflow: null, + documentOverflow: null, + ensure: function (itemCount) { + if (this.element) { + return; + } + var root = document.createElement("div"); + root.style.cssText = "position:fixed;left:0;top:0;right:0;bottom:0;z-index:2147483647;background:#fff;display:flex;align-items:stretch;justify-content:center;font-family:Arial,'Microsoft YaHei',sans-serif;touch-action:none;overscroll-behavior:contain;box-sizing:border-box;"; + root.innerHTML = "" + + "
" + + "
" + + "
" + + "
批量导出离线表单
" + + "
批量上传已开始,状态会按处理进度实时更新。
" + + "
" + + "
" + + "
" + + "
" + + "正在导出:" + + "" + + "
" + + "0%" + + "
" + + "
" + + "
" + + "" + + "" + + "
" + + "
" + + "
" + + "
" + + "

单据列表

" + + "" + + "
" + + "
" + + "
" + + "
" + + "" + + "
" + + "
" + + "
" + + ""; + this.bodyOverflow = document.body.style.overflow; + this.documentOverflow = document.documentElement.style.overflow; + document.body.style.overflow = "hidden"; + document.documentElement.style.overflow = "hidden"; + this.preventScrollHandler = function (event) { + if (this.collapsed) { + return; + } + var list = root.querySelector("[data-role='list']"); + if (list && list.contains(event.target)) { + return; + } + event.preventDefault(); + }.bind(this); + root.addEventListener("touchmove", this.preventScrollHandler, { passive: false }); + document.body.appendChild(root); + this.element = root; + this.panel = root.querySelector("[data-role='panel']"); + this.collapseButton = root.querySelector("[data-role='collapse']"); + this.collapsedButton = root.querySelector("[data-role='collapsed']"); + this.title = root.querySelector("[data-role='title']"); + this.countLabel = root.querySelector("[data-role='count']"); + this.listContainer = root.querySelector("[data-role='list']"); + this.summaryLabel = root.querySelector("[data-role='summary-label']"); + this.currentTitle = root.querySelector("[data-role='current-title']"); + this.percentLabel = root.querySelector("[data-role='percent']"); + this.fill = root.querySelector("[data-role='fill']"); + this.metaLeft = root.querySelector("[data-role='meta-left']"); + this.metaRight = root.querySelector("[data-role='meta-right']"); + this.confirmButton = root.querySelector("[data-role='confirm']"); + this.buttonClickHandler = function () { + if (!this.confirmButton || this.confirmButton.disabled) { + return; + } + var confirmHandler = this.confirmHandler; + this.close(); + if (confirmHandler) { + confirmHandler(); + } + }.bind(this); + this.confirmButton.addEventListener("click", this.buttonClickHandler); + this.collapseButtonHandler = function () { + this.collapse(); + }.bind(this); + this.collapsedButtonHandler = function () { + this.expand(); + }.bind(this); + this.collapseButton.addEventListener("click", this.collapseButtonHandler); + this.collapsedButton.addEventListener("click", this.collapsedButtonHandler); + this.refreshCount(itemCount || 0); + this.updateSummary({ + percent: 0, + title: "准备导出", + metaLeft: "正在准备附件", + metaRight: "" + }); + }, + lockPage: function () { + document.body.style.overflow = "hidden"; + document.documentElement.style.overflow = "hidden"; + }, + unlockPage: function () { + document.body.style.overflow = this.bodyOverflow || ""; + document.documentElement.style.overflow = this.documentOverflow || ""; + }, + collapse: function () { + this.ensure(); + this.collapsed = true; + this.panel.style.display = "none"; + this.collapsedButton.style.display = "block"; + this.element.style.background = "transparent"; + this.element.style.pointerEvents = "none"; + this.unlockPage(); + }, + expand: function () { + this.ensure(); + this.collapsed = false; + this.panel.style.display = "flex"; + this.collapsedButton.style.display = "none"; + this.element.style.background = "#fff"; + this.element.style.pointerEvents = "auto"; + this.lockPage(); + }, + refreshCount: function (itemCount) { + if (!this.countLabel) { + return; + } + var count = itemCount || Object.keys(this.itemMap).length; + this.countLabel.textContent = "共 " + count + " 项"; + }, + renderStatus: function (statusIcon, state) { + if (!statusIcon) { + return; + } + switch (state) { + case 'processing': + statusIcon.style.color = "#2f7df6"; + statusIcon.innerHTML = ""; + break; + case 'completed': + statusIcon.style.color = "#52c41a"; + statusIcon.innerHTML = ""; + break; + case 'error': + statusIcon.style.color = "#ff4d4f"; + statusIcon.innerHTML = ""; + break; + default: + statusIcon.style.color = "#98a2b3"; + statusIcon.innerHTML = ""; + break; + } + }, + updateSummary: function (options) { + this.ensure(); + options = options || {}; + if (options.percent !== undefined) { + var percent = Math.max(0, Math.min(100, options.percent || 0)); + this.fill.style.width = percent.toFixed(1) + "%"; + this.percentLabel.textContent = Math.floor(percent) + "%"; + } + if (options.title !== undefined) { + this.currentTitle.textContent = options.title || "离线表单"; + this.collapsedButton.querySelector("[data-role='collapsed-title']").textContent = options.title || "离线表单"; + } + if (options.metaLeft !== undefined) { + this.metaLeft.textContent = options.metaLeft || ""; + } + if (options.metaRight !== undefined) { + this.metaRight.textContent = options.metaRight || ""; + } + if (options.label !== undefined) { + this.summaryLabel.textContent = options.label || ""; + } + if (options.percent !== undefined) { + this.collapsedButton.querySelector("[data-role='collapsed-percent']").textContent = Math.floor(percent) + "%"; + } + }, + finish: function (options) { + options = options || {}; + if (!this.element) { + if (options.onConfirm) { + options.onConfirm(); + } + return; + } + this.confirmHandler = options.onConfirm || null; + if (options.success === false) { + this.updateSummary({ + label: "导出结果:", + title: "处理完成", + metaLeft: "处理失败", + metaRight: options.error || "请查看失败项" + }); + } else { + this.updateSummary({ + label: "导出结果:", + percent: 100, + title: "处理完成", + metaLeft: "已完成全部动作", + metaRight: "可以关闭页面" + }); + } + if (this.confirmButton) { + this.confirmButton.disabled = false; + this.confirmButton.textContent = "确认"; + this.confirmButton.style.background = "#2f7df6"; + this.confirmButton.style.opacity = "1"; + this.confirmButton.style.cursor = "pointer"; + } + }, + /** + * 初始化表单项 + * @param {*} itemKey 表单项唯一标识 + * @param {*} itemTitle 表单显示标题 + */ + initItem: function (itemKey, itemTitle) { + this.ensure(); + if (this.itemMap[itemKey]) { + return; + } + + var itemDiv = document.createElement("div"); + itemDiv.style.cssText = "display:flex;align-items:center;justify-content:space-between;gap:18px;padding:17px 4px;border-bottom:1px solid #e4e8f0;background:#fff;"; + itemDiv.innerHTML = "
" + + "" + + "" + + "
" + + "
"; + + this.listContainer.appendChild(itemDiv); + this.itemMap[itemKey] = { + element: itemDiv, + statusIcon: itemDiv.querySelector("[data-role='status']"), + title: itemDiv.querySelector("[data-role='title']"), + progress: itemDiv.querySelector("[data-role='progress']"), + baseTitle: itemTitle || "离线表单", + state: 'pending' + }; + this.itemMap[itemKey].title.textContent = itemTitle || "离线表单"; + this.itemMap[itemKey].progress.textContent = "等待处理..."; + this.renderStatus(this.itemMap[itemKey].statusIcon, 'pending'); + this.refreshCount(); + }, + /** + * 更新表单项状态 + * @param {*} itemKey 表单项唯一标识 + * @param {*} options 状态选项 { state, progress, detail, titleSuffix } + */ + updateItem: function (itemKey, options) { + this.ensure(); + var item = this.itemMap[itemKey]; + if (!item) { + return; + } + + if (options.state) { + item.state = options.state; + this.renderStatus(item.statusIcon, options.state); + } + + if (options.detail !== undefined) { + item.progress.textContent = options.detail; + } + + if (options.titleSuffix !== undefined) { + item.title.textContent = item.baseTitle + options.titleSuffix; + } + + if (options.progress !== undefined) { + if (item.state !== 'completed' && item.state !== 'error') { + item.progress.textContent = "处理中: " + Math.floor(options.progress) + "%"; + } + } + }, + /** + * 标记表单项完成 + * @param {*} itemKey 表单项唯一标识 + */ + completeItem: function (itemKey) { + this.updateItem(itemKey, { state: 'completed', detail: '已完成' }); + }, + /** + * 标记表单项错误 + * @param {*} itemKey 表单项唯一标识 + * @param {*} error 错误信息 + */ + errorItem: function (itemKey, error) { + this.updateItem(itemKey, { state: 'error', detail: error || '处理失败' }); + }, + close: function () { + if (this.element && this.preventScrollHandler) { + this.element.removeEventListener("touchmove", this.preventScrollHandler); + } + if (this.confirmButton && this.buttonClickHandler) { + this.confirmButton.removeEventListener("click", this.buttonClickHandler); + } + if (this.collapseButton && this.collapseButtonHandler) { + this.collapseButton.removeEventListener("click", this.collapseButtonHandler); + } + if (this.collapsedButton && this.collapsedButtonHandler) { + this.collapsedButton.removeEventListener("click", this.collapsedButtonHandler); + } + if (this.element && this.element.parentNode) { + this.element.parentNode.removeChild(this.element); + } + this.unlockPage(); + this.element = null; + this.panel = null; + this.collapseButton = null; + this.collapsedButton = null; + this.title = null; + this.countLabel = null; + this.listContainer = null; + this.summaryLabel = null; + this.currentTitle = null; + this.percentLabel = null; + this.fill = null; + this.metaLeft = null; + this.metaRight = null; + this.confirmButton = null; + this.itemMap = {}; + this.preventScrollHandler = null; + this.buttonClickHandler = null; + this.collapseButtonHandler = null; + this.collapsedButtonHandler = null; + this.confirmHandler = null; + this.collapsed = false; + this.bodyOverflow = null; + this.documentOverflow = null; + } +};