using PLCSharp.Core.Prism;
using Prism.Commands;
using Prism.Dialogs;
using Prism.Events;
using Prism.Ioc;
using System.Collections.ObjectModel;
using System.IO;
namespace PLCSharp.VVMs.Workflows
{
///
/// 脚本管理对话框视图模型:新建 / 删除快捷脚本
///
public class ScriptManageDialogViewModel : DialogAwareBase
{
///
/// 脚本管理对话框视图模型
///
public ScriptManageDialogViewModel(IContainerExtension container, IEventAggregator ea, IDialogService dialogService) : base(container, ea, dialogService)
{
Title = "脚本管理";
_dialogService = dialogService;
}
private readonly IDialogService _dialogService;
///
/// 已有脚本列表
///
public ObservableCollection Scripts { get; set; } = [];
private SnippetItem _SelectedScript;
///
/// 选中的脚本
///
public SnippetItem SelectedScript
{
get { return _SelectedScript; }
set { SetProperty(ref _SelectedScript, value); }
}
private string _ScriptName = "";
///
/// 新建脚本名称
///
public string ScriptName
{
get { return _ScriptName; }
set { SetProperty(ref _ScriptName, value); }
}
private string _ScriptContent = "";
///
/// 新建脚本内容
///
public string ScriptContent
{
get { return _ScriptContent; }
set { SetProperty(ref _ScriptContent, value); }
}
///
/// 打开对话框后要执行的
///
/// parameters
public override void OnDialogOpened(IDialogParameters parameters)
{
LoadScripts();
}
///
/// 加载已有脚本列表
///
private void LoadScripts()
{
Scripts.Clear();
foreach (var item in ScriptManager.LoadAll())
{
Scripts.Add(item);
}
}
private DelegateCommand _Create;
///
/// 创建脚本
///
public DelegateCommand Create =>
_Create ??= new DelegateCommand(ExecuteCreate);
private void ExecuteCreate()
{
var name = ScriptName?.Trim() ?? "";
if (string.IsNullOrEmpty(name))
{
SendInfoDialog("请输入脚本名称!");
return;
}
if (name.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0)
{
SendInfoDialog("脚本名称包含非法字符(不能包含 \\ / : * ? \" < > |),请重新输入!");
return;
}
var result = ScriptManager.Create(name, ScriptContent);
switch (result)
{
case CreateScriptResult.InvalidName:
SendInfoDialog("脚本名称包含非法字符(不能包含 \\ / : * ? \" < > |),请重新输入!");
break;
case CreateScriptResult.AlreadyExists:
SendInfoDialog($"脚本 [{name}] 已存在!");
break;
case CreateScriptResult.DirectoryNotFound:
SendInfoDialog("未找到 Script 目录!");
break;
case CreateScriptResult.Failed:
SendErrDialog($"脚本 [{name}] 创建失败,请检查文件是否被占用或权限不足!");
break;
case CreateScriptResult.Success:
ScriptName = "";
ScriptContent = "";
LoadScripts();
SendInfoDialog($"脚本 [{name}] 创建成功!");
break;
}
}
private DelegateCommand _Delete;
///
/// 删除选中的脚本(右键菜单)
///
public DelegateCommand Delete =>
_Delete ??= new DelegateCommand(ExecuteDelete);
private void ExecuteDelete(SnippetItem item)
{
if (item == null) return;
_dialogService.ShowDialog("AlertDialog", new DialogParameters($"message=choose:确认删除脚本[{item.Name}]?"), r =>
{
if (r.Result != ButtonResult.Yes) return;
if (ScriptManager.Delete(item.Name))
{
Scripts.Remove(item);
SendInfoDialog($"脚本 [{item.Name}] 已删除!");
}
else
{
SendErrDialog($"脚本 [{item.Name}] 删除失败,请检查文件是否被占用或权限不足!");
}
});
}
}
}