using parkMonitor.entity;
using parkMonitor.model;
using parkMonitor.server.uiLogServer;
using parkMonitor.viewModel.objectTree;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace parkMonitor.server.monitorServer {
	/// <summary>PLC监控</summary>
	public class PLCMonitorCtl: IMonitorCtl {
		MonitorModel monitorMd = null;

		PLCParamCtl plcParamCtl = new PLCParamCtl();
		
		List<ListRootParam> lstParamData = new List<ListRootParam>();		//参数数据
		public Dictionary<int, DevParamModel> mapAddrToMd = new Dictionary<int, DevParamModel>();   //Address to Model

		public PLCMonitorCtl(MonitorModel _monitorMd) {
			monitorMd = _monitorMd;
		}

		public void init() {
			try {
				plcParamCtl.load();
			} catch(Exception ex) {
				UILogServer.ins.error(MonitorModel.logTitle, "PLC配置文件读取失败！\r\n" + ex.ToString());
				return;
			}

			lstParamData = plcParamCtl.lstParamData;

			MainModel.ins.mainWin.Dispatcher.Invoke(() => {
				initViewModel();
			});
		}

		public void getData() {
			IEquipments plc = EquipmentSimpleFactory.ins.FindEquipment(EquipmentName.PLC);
			if(plc == null) {
				return;
			}

			PLCMessage data = plc.GetMessage() as PLCMessage;
			if(data == null) {
				return;
			}
			List<PLCNode> lstData = data.extendedPlcList;
			//遍历状态
			for(int i = 0; i < lstData.Count; ++i) {
				int address = Int32.Parse(lstData[i].Address);
				int value = ushort.Parse(lstData[i].Value);

				if(!mapAddrToMd.ContainsKey(address)) {
					continue;
				}
				mapAddrToMd[address].value = value.ToString();

			}
		}

		/// <summary>从PLC获取数据</summary>
		//private void testGetDataFromPLC() {
		//	Random rad = new Random(DateTime.Now.Millisecond);
		//	foreach(ListMiddleParam md in monitorMd.mapMdToVM.Keys) {
		//		for(int i = 0; i < md.Count; ++i) {
		//			DevParamModel itemMd = md[i];
		//			if(itemMd.mapCbx.Count > 0) {
		//				itemMd.value = rad.Next(itemMd.mapCbx.Count).ToString();
		//			} else {
		//				itemMd.value = rad.Next(65535).ToString();
		//			}
		//		}
		//	}
		//}

		public void clear() {

		}

		/// <summary>初始化ViewModel</summary>
		private void initViewModel() {
			var treeVM = MainModel.ins.mainWinVM.LstObjectTree;
			//遍历大类
			for(int i = 0; i < lstParamData.Count; ++i) {
				var rootMd = lstParamData[i];
				ObjectTreeRootVM rootVM = new ObjectTreeRootVM() { Name = lstParamData[i].nameDesc, DevType = rootMd.type };
				monitorMd.setTreeRootVM(rootVM);
				lstParamData[i].rootVM = rootVM;

				treeVM.Add(rootVM);

				//遍历小类
				for(int j = 0; j < rootMd.Count; ++j) {
					var leafMd = rootMd[j];
					monitorMd.initMiddleMdToVM(rootVM, leafMd, rootMd.nameDesc + "&" + leafMd.nameDesc);

					//遍历状态
					for(int k = 0; k < leafMd.Count; ++k) {
						var itemMd = leafMd[k];
						mapAddrToMd[itemMd.addr] = itemMd;
					}
				}
			}
		}
	}
}
