using Newtonsoft.Json;
using Prism.Mvvm;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
namespace TeamAAS.Communication.Models
{
/// 变量作用域:Global=机器级固定(不随产品变);Product=随产品变(存各产品快照)。
public enum VarScope { Global, Product }
///
/// 全局变量。
/// 持久化以 为唯一载体( 标了 JsonIgnore):
/// 反序列化时先落 DataType 再由 Text 解析出强类型值,避免 object 属性被 Newtonsoft
/// 还原成 long / JArray 而导致下游类型不匹配。
///
[Serializable]
public class GlobalVariableModel : BindableBase
{
/// Text ↔ Value 双向同步的重入保护
[JsonIgnore]
private bool _syncing;
private int _index;
public int Index
{
get => _index;
set => SetProperty(ref _index, value);
}
private string _name = "";
public string Name
{
get => _name;
set
{
if (SetProperty(ref _name, value))
{
RaisePropertyChanged(nameof(IsValid));
}
}
}
private string _dataType = "int";
public string DataType
{
get => _dataType;
set
{
if (!SetProperty(ref _dataType, value)) return;
// 换类型后同时重置 Value 和 Text:只改 Value 会让"值"列继续显示旧文本,
// 与实际值错位(原实现的 Bug)
_value = GetDefaultValue(value);
var t = ValueToText(_value);
if (_text != t)
{
_text = t;
RaisePropertyChanged(nameof(Text));
}
RaisePropertyChanged(nameof(DisplayValue));
RaisePropertyChanged(nameof(IsValid));
}
}
private object _value = 0;
///
/// 变量值。可由代码写入任意类型(object 类型变量尤其如此);写入后自动同步 Text 显示。
/// 不参与 JSON 序列化——持久化走 Text,加载时按 DataType 重新解析出强类型值。
///
[JsonIgnore]
public object Value
{
get => _value;
set
{
if (!SetProperty(ref _value, value)) return;
SyncTextFromValue();
RaisePropertyChanged(nameof(DisplayValue));
}
}
private string _text = "0";
/// 值列编辑用的文本表示,也是持久化载体。修改后按 DataType 解析进 Value。
public string Text
{
get => _text;
set
{
if (!SetProperty(ref _text, value)) return;
ParseValue(value);
}
}
private VarScope _scope = VarScope.Product;
/// 作用域:Global(机器级固定)/Product(随产品变)。默认 Product,兼容旧快照。
public VarScope Scope
{
get => _scope;
set => SetProperty(ref _scope, value);
}
private string _note = "";
public string Note
{
get => _note;
set => SetProperty(ref _note, value);
}
/// 只读展示值:集合统一渲染成 [a, b, c],其余取 ToString。
[JsonIgnore]
public string DisplayValue
{
get
{
if (_value == null) return "";
if (_value is string s) return s;
if (_value is IEnumerable en)
return "[" + string.Join(", ", en.Cast