using CommunityToolkit.Mvvm.ComponentModel;
using HMI.Base;
using HMI.Core.Entity;
using HMI.Core.Manager;
using HMI.Core.Util;
using HMI.UI.Util;
using LSMSInterface;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Plugin.ChangeModel.Entity;
using System.Collections.ObjectModel;
using System.Data;
using System.IO;
using System.Windows;
using System.Windows.Controls;
namespace Plugin.ChangeModel
{
///
/// ChangeModel.xaml 的交互逻辑
///
[ObservableObject]
public partial class ChangeModel : SimpleMaskControl
{
public ChangeModel()
{
api = new LSMSApi();
DataContext = this;
InitializeComponent();
}
[ObservableProperty]
private ObservableCollection datasource;
[ObservableProperty]
private ObservableCollection lineNameSource;
[ObservableProperty]
private ObservableCollection workorderSource;
[ObservableProperty]
private ObservableCollection productModelSource;
[ObservableProperty]
private string currentLineName;
[ObservableProperty]
private string currentWorkorder;
[ObservableProperty]
private string currentProductModel;
[ObservableProperty]
private Visibility workOrderVisiable = Visibility.Collapsed;
private string configLineName;
private string mesIp;
private int mesPort;
private LSMSApi api;
private bool isMesConnected = false;
private SqliteHelper sqliteHelper;
public void ConnectMes()
{
string msg = string.Empty;
try
{
if (api.Connect(this.mesIp, this.mesPort, ref msg))
{
isMesConnected = true;
}
else
{
throw new Exception(msg);
}
}
catch (Exception ex)
{
isMesConnected = false;
log.Error("ConnectMes Failed.", ex);
MsgBoxHelper.Error(Window.GetWindow(this), this.lang("cm.mesConnectFail", ex.Message));
}
}
public override void InitFinish()
{
base.InitFinish();
ParameterData parameter;
try
{
parameter = ParameterManager.GetCommonParameterByName("MesIp");
mesIp = parameter.Value;
}
catch
{
mesIp = "127.0.0.1";
}
try
{
parameter = ParameterManager.GetCommonParameterByName("MesPort");
mesPort = int.Parse(parameter.Value);
}
catch
{
mesPort = 9909;
}
try
{
parameter = ParameterManager.GetCommonParameterByName("ChangeModelByWorkOrder");
var res = bool.Parse(parameter.Value);
if (res) WorkOrderVisiable = Visibility.Visible;
}
catch
{
WorkOrderVisiable = Visibility.Collapsed;
}
try
{
var dbPath = Path.Combine(BaseFolder, "ChangeModel.db");
if (!File.Exists(dbPath))
{
SqliteHelper.CreateDatabase(dbPath);
}
sqliteHelper = new SqliteHelper(dbPath);
sqliteHelper.ExecuteSql(@"CREATE TABLE IF NOT EXISTS change_model_record (
id INTEGER PRIMARY KEY AUTOINCREMENT,
lineName TEXT NOT NULL,
workOrder TEXT,
productModel TEXT NOT NULL,
customProperty TEXT,
changeTime TIME,
changeResult TEXT,
info TEXT);");
}
catch (Exception ex)
{
log.Error("Init ChangeModel DB Failed.", ex);
}
}
public override void Active()
{
base.Active();
if (!isMesConnected)
{
ConnectMes();
RefreshLineNameSource();
}
}
public override void DoClose(object sender, EventArgs e)
{
try
{
sqliteHelper?.Dispose();
string errMsg = string.Empty;
api?.DisConnect(ref errMsg);
base.DoClose(sender, e);
}
catch {
}
}
private void RefreshLineNameSource()
{
try
{
if (PingMes(out string errMsg))
{
string lineStr = api.GetAllLine();
JObject job = (JObject)JsonConvert.DeserializeObject(lineStr);
LineNameSource = new ObservableCollection(job["ProductLines"].ToString().Split(','));
try
{
var parameter = ParameterManager.GetCommonParameterByName("LineName");
configLineName = parameter.Value;
CurrentLineName = parameter.Value;
}
catch
{
}
}
else
{
throw new Exception(errMsg);
}
}
catch (Exception ex)
{
log.Error("RefreshLineNameSource Failed.", ex);
MsgBoxHelper.ErrorMessage(Window.GetWindow(this), this.lang("cm.rfhLineNameFail", ex.Message));
}
}
private void RefreshWorkOrderByLineName(string lineName)
{
try
{
if (PingMes(out string errMsg))
{
string workOrderStr = api.GetWorkOrderByLineName(lineName, out errMsg);
if (string.IsNullOrEmpty(errMsg))
{
JObject res = (JObject)JsonConvert.DeserializeObject(workOrderStr);
JArray workOrders = (JArray)res["Data"];
WorkorderSource = new ObservableCollection(workOrders.Select(j => j["Code"].ToString()).ToArray());
}
string infoStr = api.GetProductInfoByLineName(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.FFF"), lineName, out errMsg);
if (string.IsNullOrEmpty(errMsg))
{
JObject job = JsonConvert.DeserializeObject(infoStr) as JObject;
CurrentWorkorder = job["Order"]?.ToString();
}
}
else
{
throw new Exception(errMsg);
}
}
catch (Exception ex)
{
log.Error("RefreshWorkOrderByLineName Failed.", ex);
MsgBoxHelper.ErrorMessage(Window.GetWindow(this), this.lang("cm.rfhWorkOrderFail", ex.Message));
}
}
private void RefreshProductByLineName(string lineName)
{
try
{
if (PingMes(out string errMsg))
{
string workOrderStr = api.GetProductsByLineName(lineName, out string ErrMsg);
if (string.IsNullOrEmpty(errMsg))
{
JObject res = (JObject)JsonConvert.DeserializeObject(workOrderStr);
JArray arr = res["Products"] as JArray;
ProductModelSource = new ObservableCollection(arr.Select(j => j["model"].ToString()).ToArray());
}
string lineStr = api.GetProductInfoByLineName(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.FFF"), lineName, out errMsg);
if (string.IsNullOrEmpty(errMsg))
{
JObject job = (JObject)JsonConvert.DeserializeObject(lineStr);
CurrentProductModel = job["Model"]?.ToString();
}
}
else
{
throw new Exception(errMsg);
}
}
catch (Exception ex)
{
log.Error("RefreshProductByLineName Failed.", ex);
MsgBoxHelper.ErrorMessage(Window.GetWindow(this), this.lang("cm.rfhModelFail", ex.Message));
}
}
private void MesChangeModel()
{
ShowMask(() =>
{
if (PingMes(out string errMsg))
{
var info = new Dictionary() {
{ "Model",CurrentProductModel}
};
if (WorkOrderVisiable == Visibility.Visible)
{
info["Order"] = CurrentWorkorder;
}
if (!api.ChangeModel2(CurrentLineName, info, out errMsg))
{
throw new Exception(errMsg);
}
sqliteHelper.ExecuteSql($@"INSERT INTO change_model_record (lineName, workOrder,productModel, customProperty,
changeTime,changeResult,info) Values
('{CurrentLineName}','{CurrentWorkorder}','{CurrentProductModel}',NULL,'{DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.FFF")}', 'OK', NULL)");
RefreshLog();
if (!api.RefreshCache(out errMsg))
{
throw new Exception($"Refresh MES Cache Failed.: {errMsg}");
}
ToastHelper.Success("换型成功");
}
else
{
throw new Exception(errMsg);
}
},
(ex) =>
{
log.Error("MesChangeModel Failed.", ex);
MsgBoxHelper.ErrorMessage(Window.GetWindow(this), this.lang("cm.changeFail", ex.Message));
}, "请稍后", "换型中...");
}
private bool PingMes(out string errMsg)
{
errMsg = string.Empty;
if (!isMesConnected)
{
errMsg = "MES未连接,请先连接MES";
return false;
}
try
{
if (!api.IsConnect(ref errMsg))
{
isMesConnected = false;
return false;
}
return true;
}
catch (Exception ex)
{
errMsg = ex.Message;
isMesConnected = false;
return false;
}
}
private void RefreshLog()
{
try
{
DataTable dt = sqliteHelper.GetDataTable(@"SELECT lineName AS LineName
,productModel AS ProductModel
,customProperty AS CustomProperty
,changeTime AS ChangeTime
,changeResult AS ChangeResult
,info AS Info
FROM change_model_record order by changeTime desc limit 100;");
this.Dispatcher.BeginInvoke((Action)delegate ()
{
table.ItemsSource = dt.DefaultView;
});
}
catch (Exception ex)
{
log.Error("Refresh ChangeModel Log Failed.", ex);
ToastHelper.Error(this.lang("cm.rfhLogFail", ex.Message));
}
}
partial void OnCurrentLineNameChanged(string lineName)
{
RefreshWorkOrderByLineName(lineName);
RefreshProductByLineName(lineName);
}
private void Button_Click(object sender, RoutedEventArgs e)
{
switch ((sender as Button).Name)
{
case "changeModelBtn":
DoChangeModel();
break;
case "refreshLogBtn":
ShowMask(RefreshLog, null, "请稍后", "正在刷新...");
break;
case "refreshInfoBtn":
RefreshInfo();
break;
case "deleteLogBtn":
DeleteLog();
break;
default:
break;
}
}
private void DeleteLog()
{
if (MsgBoxHelper.WarnMessage(this, this.lang("cm.makeSureDelLog")) != MessageBoxResult.OK)
{
return;
}
ShowMask(() =>
{
try
{
sqliteHelper.ExecuteSql($@"DELETE FROM change_model_record WHERE ID NOT IN
(SELECT id FROM change_model_record Order by changeTime DESC limit 10);");
RefreshLog();
}
catch (Exception ex)
{
log.Error("DeleteLog Failed.", ex);
ToastHelper.Error(this.lang("cm.delLogFail", ex.Message));
}
}, null, "请稍后", "正在清理...");
}
private void RefreshInfo()
{
try
{
RefreshLineNameSource();
RefreshWorkOrderByLineName(CurrentLineName);
RefreshProductByLineName(CurrentLineName);
}
catch (Exception ex)
{
log.Error("Refresh Info Failed.", ex);
ToastHelper.Error(this.lang("cm.rfhInfoErr", ex.Message));
}
}
private void DoChangeModel()
{
if (string.IsNullOrEmpty(CurrentLineName) || string.IsNullOrEmpty(CurrentProductModel)) return;
if (MsgBoxHelper.WarnMessage(this, this.lang("cm.makeSureChangeModel")) != MessageBoxResult.OK)
{
return;
}
MesChangeModel();
}
private void SimpleControl_Loaded(object sender, RoutedEventArgs e)
{
RefreshLog();
}
}
}