| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435 | using Aitex.Core.RT.Event;using Aitex.Core.RT.Log;using Aitex.Core.WCF;using MECF.Framework.Common.DataCenter;using Prism.Commands;using Prism.Mvvm;using System;using System.Collections.Generic;using System.Collections.ObjectModel;using System.Linq;using System.Text;using System.Threading.Tasks;using System.Windows;using System.Windows.Media.Imaging;using PunkHPX8_MainPages.Unity;using PunkHPX8_MainPages.Views;namespace PunkHPX8_MainPages.ViewModels{    public class EventViewModel : BindableBase    {        #region 私有字段        //private int MenuPermission;        #endregion        #region 属性        public bool SearchAlarmEvent { get; set; }        public bool SearchWarningEvent { get; set; }        public bool SearchInfoEvent { get; set; }        public bool SearchOpeLog { get; set; }        public bool SearchPMA { get; set; }        public bool SearchPMB { get; set; }        public bool SearchPMC { get; set; }        public bool SearchPMD { get; set; }        //public bool SearchCoolDown { get; set; }        public bool SearchTM { get; set; }        public bool SearchLL { get; set; }        //public bool SearchBuf1 { get; set; }        public bool SearchSystem { get; set; }        public string SearchKeyWords { get; set; }        private bool m_IsAuto;        public bool IsAuto        {            get { return m_IsAuto; }            set             {                if (value == true)                {                    //EventClient.Instance.Start();                    GlobalEvents.Instance.EventItemRaiseChangedEvent += Instance_OnEvent;                }                else                {                    GlobalEvents.Instance.EventItemRaiseChangedEvent -= Instance_OnEvent;                }                SetProperty(ref m_IsAuto, value);            }        }        public DateTime SearchBeginTime { get; set; }        public DateTime SearchEndTime { get; set; }        public string Keywords { get; set; }        public ObservableCollection<string> EventList { get; set; }        public string SelectedEvent { get; set; }        public ObservableCollection<string> UserList { get; set; }        public string SelectedUser { get; set; }        public ObservableCollection<Aitex.Core.UI.View.Common.SystemLogItem> SearchedResult { get; set; } = new ObservableCollection<Aitex.Core.UI.View.Common.SystemLogItem>();        public Func<string, List<EventItem>> QueryDBEventFunc { get; set; }        public Func<List<string>> QueryEventList { get; set; }        #endregion        #region 命令        private DelegateCommand _SearchCommand;        public DelegateCommand SearchCommand =>            _SearchCommand ?? (_SearchCommand = new DelegateCommand(Search));        private DelegateCommand _ExportCommand;        public DelegateCommand ExportCommand =>            _ExportCommand ?? (_ExportCommand = new DelegateCommand(Export));        private DelegateCommand<object> _LoadCommand;        public DelegateCommand<object> LoadCommand =>            _LoadCommand ?? (_LoadCommand = new DelegateCommand<object>(OnLoad));        #endregion        public EventViewModel()        {            this.QueryDBEventFunc = (sql) => QueryDataClient.Instance.Service.QueryDBEvent(sql);            this.QueryEventList = () =>            {                List<string> result = new List<string>();                foreach (var eventName in Enum.GetNames(typeof(EventEnum)))                    result.Add(eventName);                return result;            };            var now = DateTime.Today;            SearchBeginTime = now;// -new TimeSpan(1, 0, 0, 0);            SearchEndTime = new DateTime(now.Year, now.Month, now.Day, 23, 59, 59, 999);            SelectedUser = "All";            SearchKeyWords = string.Empty;            SearchAlarmEvent = true;            SearchWarningEvent = true;            SearchInfoEvent = true;            SearchOpeLog = false;            SearchPMA = false;            SearchPMB = false;            SearchPMC = false;            SearchPMD = false;            //SearchCoolDown = false;            SearchTM = false;            SearchLL = false;            //SearchBuf1 = false;            SearchSystem = false;            //EventClient.Instance.OnEvent += Instance_OnEvent;        }        private void Instance_OnEvent(EventItem eventItem)        {            switch (eventItem.Type)            {                case EventType.EventUI_Notify:                    Application.Current.Dispatcher.Invoke(delegate                    {                        SearchedResult.Insert(0,new Aitex.Core.UI.View.Common.SystemLogItem()                         {                             ID=eventItem.Id.ToString(),                            LogType=eventItem.Level.ToString(),                            Time=eventItem.OccuringTime.ToString(),                            TargetChamber=eventItem.Source,                            Detail=eventItem.Description,                            Icon = new BitmapImage(new Uri(string.Format("pack://application:,,,/MECF.Framework.Common;component/Resources/SystemLog/{0}.png", eventItem.Level.ToString()), UriKind.Absolute))                        }                        );                    });                    break;                case EventType.Dialog_Nofity:                    //PopDialog(obj);                    break;                case EventType.KickOut_Notify:                    break;                case EventType.Sound_Notify:                    break;                case EventType.UIMessage_Notify:                    //PopUIMessage(obj);                    break;            }        }        #region 方法        private void OnLoad(Object eventView)        {            this.view = (EventView)eventView;            this.view.wfTimeFrom.Value = this.SearchBeginTime;            this.view.wfTimeTo.Value = this.SearchEndTime;            this.Preload();        }        /// <summary>        /// 预先载入数据        /// </summary>        public void Preload()        {            //初始化所有的枚举事件类型            EventList = new ObservableCollection<string>();            EventList.Add("All");            if (QueryEventList != null)            {                List<string> evList = QueryEventList();                foreach (string ev in evList)                    EventList.Add(ev);            }            SelectedEvent = "All";            //初始化所有的用户            //PreloadUsers();            //所有属性更新            //NotifyOfPropertyChange();            //第一次默认查询            //if (SearchedResult == null)                //Search();        }        /// <summary>        /// 导出        /// </summary>        public void Export()        {            try            {                Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();                dlg.DefaultExt = ".xls"; // Default file extension                 dlg.Filter = "Excel数据表格文件(*.xls)|*.xls"; // Filter files by extension                 Nullable<bool> result = dlg.ShowDialog();// Show open file dialog box                if (result == true) // Process open file dialog box results                {                    System.Data.DataSet ds = new System.Data.DataSet();                    ds.Tables.Add(new System.Data.DataTable("系统运行日志"));                    ds.Tables[0].Columns.Add("类型");                    ds.Tables[0].Columns.Add("时间");                    ds.Tables[0].Columns.Add("模块");                    ds.Tables[0].Columns.Add("发起源");                    ds.Tables[0].Columns.Add("内容描述");                    foreach (var item in SearchedResult)                    {                        var row = ds.Tables[0].NewRow();                        row[0] = item.LogType;                        row[1] = item.Time;                        row[2] = item.TargetChamber;                        row[3] = item.Initiator;                        row[4] = item.Detail;                        ds.Tables[0].Rows.Add(row);                    }                    ds.WriteXml(dlg.FileName);                }            }            catch (Exception ex)            {                LOG.WriteExeption(ex);                MessageBox.Show($"导出失败: {ex.Message}", "错误",                    MessageBoxButton.OK, MessageBoxImage.Error);            }        }        private string GetSourceWhere()        {            //if (!SearchPMA) sqlEvent += string.Format(" and \"Source\"<>'{0}' ", ChamberSet.ReactorA);            //if (!SearchPMB) sqlEvent += string.Format(" and \"Source\"<>'{0}' ", ChamberSet.ReactorB);            //if (!SearchPMC) sqlEvent += string.Format(" and \"Source\"<>'{0}' ", ChamberSet.ReactorC);            //if (!SearchPMD) sqlEvent += string.Format(" and \"Source\"<>'{0}' ", ChamberSet.ReactorD);            //if (!SearchSystem) sqlEvent += string.Format(" and \"Source\"<>'{0}' ", ChamberSet.System);            //if (!SearchLL) sqlEvent += string.Format(" and \"Source\"<>'{0}' ", ChamberSet.Loadlock);            //if (!SearchTM) sqlEvent += string.Format(" and \"Source\"<>'{0}' and \"Source\"<>'{1}' and \"Source\"<>'{2}' ",            //    ChamberSet.Loadlock, ChamberSet.Buffer1, ChamberSet.Cooldown);            return "";        }        /*         *gid integer NOT NULL DEFAULT nextval('event_data_gid_seq'::regclass),          event_id integer,          event_enum text,          type text,          source text,          description text,          level text,          occur_time timestamp without time zone,          CONSTRAINT event_data_pkey PRIMARY KEY (gid)         */        /// <summary>        /// 查询        /// </summary>        public void Search()        {            Task.Factory.StartNew(() =>            {                try                {                    SearchedResult = new ObservableCollection<Aitex.Core.UI.View.Common.SystemLogItem>();                    this.SearchBeginTime = this.view.wfTimeFrom.Value;                    this.SearchEndTime = this.view.wfTimeTo.Value;                    string sqlEvent = "";                    string sqlOperationLog = "";                    string sql = "";                    if (SearchAlarmEvent || SearchWarningEvent || SearchInfoEvent)                    {                        sqlEvent = string.Format("SELECT \"event_id\", \"event_enum\", \"type\", \"occur_time\", \"level\",\"source\" , \"description\" FROM \"event_data\" where \"occur_time\" >='{0}' and \"occur_time\" <='{1}' ", SearchBeginTime.ToString("yyyyMMdd HHmmss"), SearchEndTime.ToString("yyyyMMdd HHmmss"));                        sqlEvent += GetSourceWhere();                        sqlEvent += " and (FALSE ";                        if (SearchAlarmEvent) sqlEvent += " OR \"level\"='Alarm' ";                        if (SearchWarningEvent) sqlEvent += " OR \"level\"='Warning' ";                        if (SearchInfoEvent) sqlEvent += " OR \"level\"='Information' ";                        sqlEvent += " ) ";                        if (!string.IsNullOrWhiteSpace(SelectedEvent) && SelectedEvent != "All") sqlEvent += string.Format(" and lower(\"event_enum\")='{0}' ", SelectedEvent.ToLower());                        //if (!string.IsNullOrWhiteSpace(SearchKeyWords)) sqlEvent += string.Format(" and lower(\"description\") like '%{0}%' ", SearchKeyWords.ToLower());                        if (!string.IsNullOrWhiteSpace(SearchKeyWords)) sqlEvent += string.Format(" and lower(\"description\") like '%{0}%' or lower(\"type\") like '%{1}%'", SearchKeyWords.ToLower(), SearchKeyWords.ToLower());                    }                    if (SearchOpeLog)                    {                        //sqlOperationLog = string.Format(" SELECT \"UserName\" as \"Initiator\", 'UserOperation' as \"LogType\", \"Time\", \"ChamberId\" as \"TargetChamber\", \"Content\" as \"Description\" FROM \"OperationLog\" where \"Time\" >='{0}' and \"Time\" <='{1}' ", SearchBeginTime.ToString("yyyy/MM/dd HH:mm:ss"), SearchEndTime.ToString("yyyy/MM/dd HH:mm:ss"));                        //if (!SearchPMA) sqlOperationLog += string.Format(" and \"ChamberId\"<>'{0}' ", ChamberSet.ReactorA);                        //if (!SearchPMB) sqlOperationLog += string.Format(" and \"ChamberId\"<>'{0}' ", ChamberSet.ReactorB);                        //if (!SearchPMC) sqlOperationLog += string.Format(" and \"ChamberId\"<>'{0}' ", ChamberSet.ReactorC);                        //if (!SearchPMD) sqlOperationLog += string.Format(" and \"ChamberId\"<>'{0}' ", ChamberSet.ReactorD);                        //if (!SearchSystem) sqlOperationLog += string.Format(" and \"ChamberId\"<>'{0}' ", ChamberSet.System);                                              //if (!SearchLL) sqlOperationLog += string.Format(" and \"ChamberId\"<>'{0}' ", ChamberSet.Loadlock);                        //if (!SearchTM) sqlOperationLog += string.Format(" and \"ChamberId\"<>'{0}' and \"ChamberId\"<>'{1}' and \"ChamberId\"<>'{2}' ",                        //    ChamberSet.Loadlock, ChamberSet.Buffer1, ChamberSet.Cooldown);                        //if (!string.IsNullOrWhiteSpace(SelectedUser) && SelectedUser != "不限") sqlOperationLog += string.Format(" and lower(\"UserName\")='{0}' ", SelectedUser.ToLower());                        //if (!string.IsNullOrWhiteSpace(SearchKeyWords)) sqlOperationLog += string.Format(" and lower(\"Content\") like '%{0}%' ", SearchKeyWords.ToLower());                    }                    sql = sqlEvent;                    if (!string.IsNullOrEmpty(sqlOperationLog))                    {                        if (string.IsNullOrEmpty(sql))                        {                            sql = sqlOperationLog;                        }                        else                        {                            sql += " UNION ALL " + sqlOperationLog;                        }                    }                                        if (!string.IsNullOrEmpty(sql) && QueryDBEventFunc != null)                    {                        sql += " order by \"occur_time\" DESC limit 2000;";                        List<EventItem> lstEvent = QueryDBEventFunc(sql);                        if (lstEvent == null)                            return;                        Application.Current.Dispatcher.BeginInvoke(new Action(() =>                        {                                                        string logTypeStr;                            foreach (EventItem ev in lstEvent)                            {                                switch (ev.Level)                                {                                    case EventLevel.Information: logTypeStr = "Info"; break;                                    case EventLevel.Warning: logTypeStr = "Warning"; break;                                    case EventLevel.Alarm: logTypeStr = "Alarm"; break;                                    default: logTypeStr = "Undefine"; break;                                }                                                               SearchedResult.Add(new Aitex.Core.UI.View.Common.SystemLogItem()                                {                                                    ID = ev.Id.ToString() ,                                    Time = ((DateTime)ev.OccuringTime).ToString("yyyy/MM/dd HH:mm:ss.fff"),                                    LogType = logTypeStr,                                    Detail = ev.Description,                                    TargetChamber = ev.Source,                                    Initiator = "",                                    Icon = new BitmapImage(new Uri(string.Format("pack://application:,,,/MECF.Framework.Common;component/Resources/SystemLog/{0}.png", ev.Level.ToString()), UriKind.Absolute))                                }); ;                            }                            RaisePropertyChanged("SearchedResult");                            if (SearchedResult.Count >= 2000)                            {                                //MessageBox.Show("Only display max 2000 items,reset the query condition", "query too many result", MessageBoxButton.OK, MessageBoxImage.Warning);                            }                        }));                    }                    else                    {                        Application.Current.Dispatcher.BeginInvoke(new Action(() =>                        {                            SearchedResult = new ObservableCollection<Aitex.Core.UI.View.Common.SystemLogItem>();                            RaisePropertyChanged("SearchedResult");                        }));                    }                }                catch (Exception ex)                {                    //LOG.Write(ex);                    LOG.WriteExeption(ex);                }            });        }        private EventView view;        #endregion    }    public class SystemLogItem    {        /// <summary>        /// 时间        /// </summary>        public string Time { get; set; }        /// <summary>        /// ICON         /// </summary>        public object Icon { get; set; }        /// <summary>        /// 类型:操作日志|事件|其他        /// </summary>        public string LogType { get; set; }        /// <summary>        /// 针对腔体        /// </summary>        public string TargetChamber { get; set; }        /// <summary>        /// 发起方        /// </summary>        public string Initiator { get; set; }        /// <summary>        /// 详情        /// </summary>        public string Detail { get; set; }    }}
 |