using HTCoreServiceApp.Common;
using HTCoreServiceApp.DataHandle;
using HTCoreServiceApp.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.ModelBinding.Validation;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
using Newtonsoft.Json;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Linq.Expressions;
using System.Security.Cryptography.X509Certificates;
using System.Text.RegularExpressions;

namespace HTCoreServiceApp.Controllers
{
	[ApiController]
	[Route("[controller]/[action]")]
	public class DeviceControl : ControllerBase
	{
		private readonly DriverService _driverService;
		private readonly List<MetaGroup> metaGroups;
		private readonly List<MetaDriver> metaDrivers;
		private readonly List<MetaTag> metaTags;
		public DeviceControl(DriverService driverService)
		{
			_driverService = driverService;
			//string ConnectionStrings = AESKeyEncrypt.DecryptDES(ConfigHelper.ReadAppSettings("ConnectionStrings", "SqlServer"));
			var db = new SqlSugarClient(StaticLibrary.DBConfig);
			metaGroups = db.Queryable<MetaGroup>().ToList(); //db.MetaGroups.ToList();
			metaDrivers = db.Queryable<MetaDriver>().ToList(); //db.MetaDrivers.ToList();
			metaTags = db.Queryable<MetaTag>().ToList(); //db.MetaTags.ToList();
			db.Dispose();
		}
		[HttpGet]
		public string Get()  //请求方法行为
		{
			return "hello，这里是恒拓设备实时控制服务！";
		}
		[HttpGet]
		public string Getname(string name)  //请求方法行为
		{
			return $"服务器收到字符串：{name}";
		}
		[HttpGet]
		public int SetDeviceData(string groupName,string tagName,string value)
		{
			var ip = HttpContext.GetClientUserIp();
			//var cache = StaticLibrary.MemoryCacheHelper.Get<List<LiveGroupDictionary>>(driverName).Where(x=>x.GroupName == groupName).First();
			//var val = new List<LiveGroupDictionary>();
			//StaticLibrary.MemoryCacheHelper.TryGetValue(driverName,out val);
			//return LiveJsonIntegrate.MetaValues2Json(val.FirstOrDefault());

			int reCode = 0;

			//直接返回，取消后续写入步骤
			//return reCode;
			try
			{
				if (!string.IsNullOrEmpty(groupName) && !string.IsNullOrEmpty(tagName) && !string.IsNullOrEmpty(value))
				{
					//var context = StaticLibrary.DBContext;
					//return StaticLibrary.MemoryCacheHelper.GetString(groupName);
					var driverID = metaGroups.Where(x => x.GroupName == groupName).FirstOrDefault().DriverId;
					var driverName = metaDrivers.Where(x => x.DriverId == driverID).FirstOrDefault().DriverName;
					var groupID = metaGroups.Where(x => x.GroupName == groupName).FirstOrDefault().GroupId;
					var dataType = metaTags.Where(x => x.TagName == tagName && x.GroupId == groupID).First().DataType;
					var writeAddress = metaTags.Where(x => x.TagName == tagName && x.GroupId == groupID).First().PLCAddress;//231113 ,CDL QWZ 写入地址字段由WriteAddress修改为PLCAddress
					if(writeAddress == ""|| writeAddress == null)
					{
						reCode = 1;
						return reCode;
					}
                    var windex = writeAddress.IndexOf(".");
                    writeAddress = writeAddress.Remove(windex, 1).Insert(windex, ",");
                    //var valueHandle = 0;
                    if (dataType == (short)DataType.BOOL)
					{
						if (value.Equals("True") || value.Equals("true") || value.Equals("TRUE") || value.Equals("1"))
						{
							value = "1";
						}
						else if (value.Equals("False") || value.Equals("false") || value.Equals("FALSE") || value.Equals("0"))
						{
							value = "0";
						}
					}
					if (dataType == (short)DataType.IFLOAT)
					{
                        var iFloatPlaces = (int)metaTags.Where(x => x.TagName == tagName && x.GroupId == groupID).First().IFloatPlaces;
						value = ((int)(float.Parse(value) * (int)Math.Pow(10.0f, iFloatPlaces))).ToString();
                    }
                    var writePara = new
					{
						TagName = tagName,
						GroupName = groupName,
						WriteAddress = writeAddress,
						DataType = dataType,
						Value = value
					};
					string serJson = JsonConvert.SerializeObject(writePara);


					foreach (var driverThread in _driverService.DriverThreads)
					{
						if (driverThread.driverName == driverName)
						{
							reCode = driverThread.DriverWrite(serJson);
						}
					}
				}
				else
				{
					reCode = 1;
				}
			}
			catch (Exception ex)
			{
				reCode = 1;
			}
			return reCode;
		}
	}
}
