using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.SignalR;
using Microsoft.Extensions.Logging;
using Ropin.Environmentally.WebScada.Hubs;
using Microsoft.AspNet.SignalR.Client;
using Microsoft.AspNetCore.SignalR.Client;
using FBoxClientDriver.Contract;
using System.Threading;
using Microsoft.AspNetCore.Http;
using Serilog;
using Microsoft.AspNetCore.NodeServices;
using InfluxData.Net.InfluxDb;
using InfluxData.Net.Common.Enums;
using System.Linq;


namespace Ropin.Environmentally.WebScada
{
    public class DeviceController : Controller
    {
        private readonly IHubContext<MyHub> _hubContext;
        private readonly ILogger<DeviceController> _logger;
        private Microsoft.AspNetCore.SignalR.Client.HubConnection _hubConnection;
        private readonly INodeServices _services;
        private InfluxDbClient clientDb;
        public DeviceController(ILogger<DeviceController> logger, INodeServices services,IHubContext<MyHub> hubContext)
        {
            _logger = logger;
            _hubContext = hubContext;
            _services = services;
        }
        [HttpGet]
        public async Task<string> GetName()
        {
            string greetingMessage = await _services.InvokeAsync<string>("./scripts/greeter", "yandaniu");
//            string fun = @"function (callback, name) {
//    var greet = function (name) {
//        return 'Hello,Are you ' + name + '?';
//    }
//    callback(null, greet(name));
//}
//";
//            string greetingMessage = await _services.InvokeAsync<string>(fun, "yandaniu");
            return greetingMessage;
        }
        public TokenResult GetToken(AccessUser accessUser)
        {
            var url = "https://fbox360.com/idserver/core/connect/token";
            TokenResult token;
            Dictionary<string, object> data = new Dictionary<string, object>();
            try
            {
                if (accessUser == null)
                {
                    throw new Exception("参数为空");
                }
                else
                {
                    Dictionary<string, string> dict = new Dictionary<string, string>();
                    if (!string.IsNullOrEmpty(accessUser.refresh_token))
                    {
                        dict["grant_type"] = "refresh_token";
                        dict["refresh_token"] = accessUser.refresh_token;
                    }
                    else
                    {
                        dict["grant_type"] = "client_credentials";
                        dict["client_id"] = accessUser.client_id;
                        dict["client_secret"] = accessUser.client_secret;
                        dict["scope"] = "fbox";
                    }


                    using (HttpClient http = new HttpClient())
                    {
                        using (var content = new FormUrlEncodedContent(dict))
                        {
                            var msg = http.PostAsync(url, content);
                            if (msg.IsFaulted)
                            {
                                return null;
                            }
                            else
                            {
                                var result = msg.Result.Content.ReadAsStringAsync().Result;
                                token = JsonConvert.DeserializeObject<TokenResult>(result);
                            }


                            //return Content(result, "application/json");
                        }
                    }
                }
                return token;
            }
            catch (Exception ex)
            {
                return null;
            }
        }
        DeviceValueModel device = new DeviceValueModel();
        private void _fbox_DataMonitorValueChanged(object sender, IList<DataMonitorValueChangedArgs> e)
        {

            foreach (var dmon in e)
            {
                var deviceValue = $"dmv:{dmon.Uid},Value:{dmon.Value},Status:{dmon.Status},BoxNo:{dmon.BoxNo},Name:{dmon.Name},BoxId:{dmon.BoxId},GroupName:{dmon.GroupName},Timestamp:{dmon.Timestamp}";
                //Console.WriteLine(deviceValue);
                //logger.Error($"uid:{dmon.Uid},value:{dmon.Value},Status:{dmon.Status},BoxNo:{dmon.BoxNo},BoxId:{dmon.BoxId},GroupName:{dmon.GroupName},Timestamp:{dmon.Timestamp},Name:{dmon.Name}");
                System.DateTime currentTime = new System.DateTime();
                currentTime = System.DateTime.Now;
                Console.WriteLine(currentTime);
                //Clients.All.SendAsync("UpdateData", deviceValue);
                switch (dmon.Uid)
                {
                    case 224873575130485457:
                        device.Value = dmon.Value?.ToString();
                        device.Name = dmon.Name;
                        break;
                    case 225981652471795782:
                        device.Value10 = dmon.Value?.ToString();
                        device.Name10 = dmon.Name;
                        break;
                    case 224873679711261516:
                        device.Value11 = dmon.Value?.ToString();
                        device.Name11 = dmon.Name;
                        break;
                    case 225975315764502499:
                        device.Value12 = dmon.Value?.ToString();
                        device.Name12 = dmon.Name;
                        break;
                    case 225975390380118077:
                        device.Value13 = dmon.Value?.ToString();
                        device.Name13 = dmon.Name;
                        break;
                    case 224872713744176788:
                        device.Value14 = dmon.Value?.ToString();
                        device.Name14 = dmon.Name;
                        break;
                    default:
                        break;

                }
                //Clients.All.SendAsync("UpdateDeviceData", new MsgInfo { MsgContent = dmon.Value.ToString(), Title = dmon.Name } );
                //Clients.All.SendAsync("UpdateData", new MsgInfo { Title = dmon.Value.ToString(), MsgContent = dmon.Name });
                //Clients.All.SendAsync("ShowMsg", new MsgInfo { Title = "DeviceTitle", MsgContent = deviceValue });
                //logger.Info("时间" + currentTime + "Uid" + dmon.Uid + "名称:" + dmon.Name + "值:" + dmon.Value + "状态:" + dmon.Status + "盒子号:" + dmon.BoxNo + "分组名称:" + dmon.GroupName + "时间" + dmon.Timestamp);


            }
            _hubContext.Clients.All.SendAsync("UpdateDeviceData", device);
            //Clients.All.SendAsync("UpdateDeviceData", device);
            //接收数据,先存数据,再把数据显示到页面上
        }
        void devRun()
        {
            using (var dmon = new demo())
            {
                dmon._fbox.DataMonitorValueChanged += _fbox_DataMonitorValueChanged;
                dmon.Start().Wait();

                string ln = "aa";
                do
                {
                    ln = Console.ReadLine();
                } while (ln != "quit");
            }

        }


        public void js()
        {
            // 添加引用 using Microsoft.JScript;
            string jsStr = "var i=100; i++; i=i*100; var obj = {a:i};";

            //Stopwatch sw = new Stopwatch();
            //sw.Start();
            object ret1 = null;
            try
            {
                //ret1 = Eval.JScriptEvaluate(jsStr, VsaEngine.CreateEngine());
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.StackTrace.ToString(), "执行失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            //sw.Stop();

            //string res = "";
            //if (ret1 is ArrayObject)
            //{
            //    // 数组
            //    ArrayObject arr = (ArrayObject)ret1;

            //    res = arr[0].ToString();
            //}
            //else if (ret1 is JSObject)
            //{
            //    // 对象
            //    JSObject obj = (JSObject)ret1;

            //    res = obj["a"].ToString();
            //}
            //else
            //{
            //    // 单值
            //    res = ret1.ToString();
            //}

            //MessageBox.Show(res + " 用时:" + sw.ElapsedMilliseconds.ToString() + "ms");
        }

        public async Task<object> GetDevSpotSeries()
        {
            IniInflux();
            //传入查询命令,支持多条
            var queries = new[]
            {
                " SELECT * FROM fanyidev WHERE time > now() - 5m"
            };
            var dbName = "fanyidb";
            //从指定库中查询数据
            var response = await clientDb.Client.QueryAsync(queries, dbName);
            //得到Serie集合对象(返回执行多个查询的结果)
            var series = response.ToList();
            //取出第一条命令的查询结果,是一个集合
            var list = series[0].Values;
            //从集合中取出第一条数据
            //var info_model = list.FirstOrDefault();
            return list;
        }


        /// <summary>
        /// 条件获取历史数据
        /// </summary>
        /// <param name="point"></param>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        public async Task<object> GetDevSpotSeriesAsync(string[] point,DateTime start,DateTime end)
        {
            if (point?.Length == 0)
            {
                return null;
            }
            string strStart = start.ToString("yyyy-MM-ddTHH:mm:ssZ");
            string strEnd = end.ToString("yyyy-MM-ddTHH:mm:ssZ");
            string strId = point[0];

            IniInflux();
            //传入查询命令,支持多条
            var queries = new[]
            {
                //" SELECT * FROM fanyidev WHERE time > now() - 5m"
                //SELECT * FROM "fanyidev" WHERE time > now() - 535m AND time < now() -10m  and Id = '224257795187691889'
                //SELECT * FROM "fanyidev" WHERE time>'2023-01-10T10:07:00Z'  and time<'2023-10-25T17:58:00Z' and Id = '224257795187691889' order by time desc limit 10
                "SELECT * FROM fanyidev WHERE time>"+strStart+"  and time< "+strEnd + " and Id = "+strId+" order by time desc limit 10"
            };
            var dbName = "fanyidb";
            //从指定库中查询数据
            var response = await clientDb.Client.QueryAsync(queries, dbName);
            //得到Serie集合对象(返回执行多个查询的结果)
            var series = response.ToList();
            //取出第一条命令的查询结果,是一个集合
            var list = series[0].Values;
            //从集合中取出第一条数据
            //var info_model = list.FirstOrDefault();
            return list;
        }
        private void IniInflux()
        {
            //连接InfluxDb的API地址、账号、密码

            var infuxUrl = "http://60.204.212.71:8085/";

            var infuxUser = "admin";

            var infuxPwd = "123456";

            //创建InfluxDbClient实例

            clientDb = new InfluxDbClient(infuxUrl, infuxUser, infuxPwd, InfluxDbVersion.Latest);

        }

        public async Task<IActionResult> Index()
        {
            //QueryString queryString = Request.QueryString; // ?a=1
            string id = Request.Query["id"]; //1
            
            //Thread t = new Thread(devRun);//1创建线程对象
            //t.Start();//2从这里开始
            //t.IsBackground = true;//规定t为后台线程后台线程会在前台线程结束时结束




            //_hubConnection = new HubConnectionBuilder()
            //  //.WithUrl("https://www.ropiniot.com/DigitalEnvironmentallyWebScadaTest/myhub") //
            //  .WithUrl("http://localhost:5000/myhub")
            //  .WithAutomaticReconnect()//wait 0, 2, 10, and 30 seconds
            //  .Build();
            //_hubConnection.On<DeviceValueModel>("UpdateDataServer", (msg) =>
            //{
            //    DeviceValueModel value = msg;
            //});
            //await _hubConnection.StartAsync();
            //await _hubConnection.InvokeAsync("UpdateDataServer",
            //    new DataStatus { Status1 = "", Status2 = "" });
            //await _hubConnection.InvokeAsync("UpdateDataServer",
            //    new DataStatus { Status1 = txtStatus1.Text, Status2 = txtStatus2.Text });
            //await _hubContext.Clients.All.SendAsync("ShowMsg", new MsgInfo { Title = "TestTitle", MsgContent = content + count++ });
            DeviceValueModel model = new DeviceValueModel();
           
            TokenResult tokenResult = GetToken(new AccessUser { client_id = "b19d14eeacb74522bd29627b79c18ab8", client_secret = "7b89e021586c43d3b79440ba6eea0b67" });
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResult.access_token);
                var requestt = new HttpRequestMessage(HttpMethod.Get, "https://fbox360.com/api/client/box/grouped");
                requestt.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var response =  await client.SendAsync(requestt);
                string result = await response.Content.ReadAsStringAsync();
                if (response.StatusCode != HttpStatusCode.OK)
                {

                }
                else
                {
                    //todo 
                }
            }
            goto getDeviceValue;
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResult.access_token);
                var requestt = new HttpRequestMessage(HttpMethod.Get, " https://fbox360.com/api/v2/box/4316279314564828131/dmon/grouped");
                requestt.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var response = await client.SendAsync(requestt);
                string result = await response.Content.ReadAsStringAsync();
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    List<Device> deviceVueList = JsonConvert.DeserializeObject<List<Device>>(result);
                    model.Name = deviceVueList[0].items[0].grpName + deviceVueList[0].items[0].name;
                    model.Value = deviceVueList[0].items[0].intDigits;

                    model.Name10 = deviceVueList[0].items[1].grpName + deviceVueList[0].items[1].name;
                    model.Value10 = deviceVueList[0].items[1].intDigits;

                    model.Name11 = deviceVueList[0].items[2].grpName + deviceVueList[0].items[2].name;
                    model.Value11 = deviceVueList[0].items[2].intDigits;

                    model.Name12 = deviceVueList[0].items[3].grpName + deviceVueList[0].items[3].name;
                    model.Value12 = deviceVueList[0].items[3].intDigits;

                    model.Name13 = deviceVueList[0].items[4].grpName + deviceVueList[0].items[4].name;
                    model.Value13 = deviceVueList[0].items[4].intDigits;
                    //deviceVueList
                    //string strName = deviceVueList..name;

                }
                else
                {
                    //todo 
                }
            }
            getDeviceValue:
            using (HttpClient client = new HttpClient())
            {
                string postData = Newtonsoft.Json.JsonConvert.SerializeObject(new
                {
                    //names= new List<string> { "\"数据块_1\".运行时间记录_M", "蜂窝沸石转筒电子差压计D4实际值", "\"数据块_1\".运行时间记录_M", "蜂窝沸石转筒电子差压计D4实际值", "前处理过滤箱电子差压计D3实际值" }, //, "主加热器1", "辅助加热器1" 
                    //groupnames = new List<string> { "喷漆房1", "喷漆房1", "喷漆房4", "喷漆房4", "喷漆房4" }, //, "喷漆房1" , "喷漆房1" 
                    //ids = new List<string> { "224275280344535204"}, \"数据块_1\".运行时间记录_D
                    names = new List<string> {
                        "自动油雾过滤器电子差压计D0实际值",
        "前处理过滤箱电子差压计D2实际值",
        "前处理过滤箱电子差压计D3实际值",
        "蜂窝沸石转筒电子差压计D4实际值",
        "\"数据块_1\".运行时间记录_D",
        "\"数据块_1\".运行时间记录_H",
        "\"数据块_1\".运行时间记录_M",
        "报警1",
        "主加热器1",
        "辅助加热器1",
        "主风机1"}, 
                    groupnames = new List<string> {
                        "喷漆房1",
        "喷漆房1",
        "喷漆房1",
        "喷漆房1",
        "喷漆房1",
        "喷漆房1",
        "喷漆房1",
        "喷漆房1",
        "喷漆房1",
        "喷漆房1",
        "喷漆房1"},
                    timeOut = 6000
                });
                //string s = @"{\"ids\":[\"224275280344535204\"]}";


                #region ceshi
                using (var httpClient = new HttpClient())
                {
                    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResult.access_token);
                    httpClient.BaseAddress = new Uri("http://fbcs101.fbox360.com/api/v2/dmon/value/get?boxNo=300220010352");
                    httpClient.DefaultRequestHeaders.Accept.Clear();
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    var jsonString = postData;
                    HttpResponseMessage esponse = await httpClient.PostAsync(httpClient.BaseAddress, new StringContent(jsonString, Encoding.UTF8, "application/json"));

                    if (esponse.IsSuccessStatusCode)
                    {
                        string json = await esponse.Content.ReadAsStringAsync();

                        //List<DeviceVlue> deviceVueList = JsonConvert.DeserializeObject<List<DeviceVlue>>(json);
                        //model.Name = "自动油雾过滤器电子差压计D0实值";
                        //model.Value = deviceVueList[0].value.ToString().Split('.')[0];

                        //model.Name10 = deviceVueList[1].name;
                        //model.Value10 = deviceVueList[1].value.ToString().Split('.')[0];

                        //model.Name11 = deviceVueList[2].name;
                        //model.Value11 = deviceVueList[2].value.ToString().Split('.')[0];

                        //model.Name12 = deviceVueList[3].name;
                        //model.Value12 = deviceVueList[3].value.ToString().Split('.')[0];

                        //model.Name13 = "运行时间"; //(天)
                        //model.Value13 = deviceVueList[4].value.ToString().Split('.')[0];

                        //model.Name14 = "运行时间"; //(时)
                        //model.Value14 = deviceVueList[5].value.ToString().Split('.')[0];

                        //model.Name15 = "运行时间";//((分)) 
                        //model.Value15 = deviceVueList[6].value.ToString().Split('.')[0];

                        //model.Name16 = deviceVueList[7].name;//报警
                        //model.Value16 = deviceVueList[7].value.ToString().Split('.')[0];

                        //model.Name17 = "主加热器";//主加热器1
                        //model.Value17 = deviceVueList[8].value.ToString().Split('.')[0];

                        //model.Name18 = "辅助加热器";//辅助加热器1
                        //model.Value18 = deviceVueList[9].value.ToString();

                        //model.Name19 = "主风机";//主风机1
                        //model.Value19 = deviceVueList[10].value.ToString().Split('.')[0];


                    }
                }

                //Dictionary<string, string> dict = new Dictionary<string, string>();
                //dict["grant_type"] = "refresh_token";


                //using (HttpClient http = new HttpClient())
                //{
                //    http.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResult.access_token);
                //    using (var content = new FormUrlEncodedContent(dict))
                //    {
                //        var msg = http.PostAsync("http://fbcs101.fbox360.com/api/v2/dmon/value/get?boxNo=300221100748", content);
                //        if (msg.IsFaulted)
                //        {
                //            return null;
                //        }
                //        else
                //        {
                //            var result = msg.Result.Content.ReadAsStringAsync().Result;
                //        }
                //    }
                //}
                #endregion



                //client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResult.access_token);
                ////var requestt = new HttpRequestMessage(HttpMethod.Post, "http://fbcs101.fbox360.com/api/v2/box/4316279314564828131/dmon/value/get");
                //var requestt = new HttpRequestMessage(HttpMethod.Post, "http://fbcs101.fbox360.com/api/v2/dmon/value/get?boxNo=300221100748");
                //requestt.Content = new StringContent(postData);
                //requestt.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                //var response = await client.SendAsync(requestt);
                //string result = await response.Content.ReadAsStringAsync();
                //if (response.StatusCode == HttpStatusCode.OK)
                //{
                //    List<Device> deviceVueList = JsonConvert.DeserializeObject<List<Device>>(result);
                //    model.Name = deviceVueList[0].items[0].grpName + deviceVueList[0].items[0].name;
                //    model.Value = deviceVueList[0].items[0].intDigits;

                //    model.Name10 = deviceVueList[0].items[1].grpName + deviceVueList[0].items[1].name;
                //    model.Value10 = deviceVueList[0].items[1].intDigits;

                //    model.Name11 = deviceVueList[0].items[2].grpName + deviceVueList[0].items[2].name;
                //    model.Value11 = deviceVueList[0].items[2].intDigits;

                //    model.Name12 = deviceVueList[0].items[3].grpName + deviceVueList[0].items[3].name;
                //    model.Value12 = deviceVueList[0].items[3].intDigits;

                //    model.Name13 = deviceVueList[0].items[4].grpName + deviceVueList[0].items[4].name;
                //    model.Value13 = deviceVueList[0].items[4].intDigits;
                //    //deviceVueList
                //    //string strName = deviceVueList..name;

                //}
                //else
                //{
                //    //todo 
                //}
            }

            model.Id = id;
            return View(model);
        }

        #region 喷漆房2
        public async Task<IActionResult> PaintRoom2()
        {
            //string id = Request.Query["id"]; //2

            DeviceValueModel model = new DeviceValueModel();

            TokenResult tokenResult = GetToken(new AccessUser { client_id = "b19d14eeacb74522bd29627b79c18ab8", client_secret = "7b89e021586c43d3b79440ba6eea0b67" });
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResult.access_token);
                var requestt = new HttpRequestMessage(HttpMethod.Get, "https://fbox360.com/api/client/box/grouped");
                requestt.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var response = await client.SendAsync(requestt);
                string result = await response.Content.ReadAsStringAsync();
                if (response.StatusCode != HttpStatusCode.OK)
                {

                }
                else
                {
                    //todo 
                }
            }
            using (HttpClient client = new HttpClient())
            {
                string postData = Newtonsoft.Json.JsonConvert.SerializeObject(new
                {
                    names = new List<string> {
                        "自动油雾过滤器电子差压计D0实际值",
        "自动油雾过滤器电子差压计D1实际值",
        "\"前处理过滤箱电子差压计D3实际值\"",
        "蜂窝沸石转筒电子差压计D4实际值",
        "\"数据块_2\".运行时间记录_D",
        "\"数据块_2\".运行时间记录_H",
        "\"数据块_3\".运行时间记录_M",
        "报警2",
        "主加热器2",
        "辅助加热器2",
        "主风机2"},
                    groupnames = new List<string> {
                        "喷漆房2",
        "喷漆房2",
        "喷漆房2",
        "喷漆房2",
        "喷漆房2",
        "喷漆房2",
        "喷漆房2",
        "喷漆房2",
        "喷漆房2",
        "喷漆房2",
        "喷漆房2"},
                    timeOut = 6000
                });
                //string s = @"{\"ids\":[\"224275280344535204\"]}";


                #region ceshi
                using (var httpClient = new HttpClient())
                {
                    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResult.access_token);
                    httpClient.BaseAddress = new Uri("http://fbcs101.fbox360.com/api/v2/dmon/value/get?boxNo=300220010352");
                    httpClient.DefaultRequestHeaders.Accept.Clear();
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    var jsonString = postData;
                    HttpResponseMessage esponse = await httpClient.PostAsync(httpClient.BaseAddress, new StringContent(jsonString, Encoding.UTF8, "application/json"));

                    if (esponse.IsSuccessStatusCode)
                    {
                        string json = await esponse.Content.ReadAsStringAsync();

                        List<DeviceVlue> deviceVueList = JsonConvert.DeserializeObject<List<DeviceVlue>>(json);
                        model.Name = "自动油雾过滤器电子差压计D0实值";
                        model.Value = deviceVueList[0].value.ToString().Split('.')[0];

                        model.Name10 = deviceVueList[1].name;
                        model.Value10 = deviceVueList[1].value.ToString().Split('.')[0];

                        model.Name11 = "前处理过滤箱电子差压计D3实际值";
                        model.Value11 = deviceVueList[2].value.ToString().Split('.')[0];

                        model.Name12 = deviceVueList[3].name;
                        model.Value12 = deviceVueList[3].value.ToString().Split('.')[0];

                        model.Name13 = "运行时间"; //(天)
                        model.Value13 = deviceVueList[4].value.ToString().Split('.')[0];

                        model.Name14 = "运行时间"; //(时)
                        model.Value14 = deviceVueList[5].value.ToString().Split('.')[0];

                        model.Name15 = "运行时间";//((分)) 
                        model.Value15 = deviceVueList[6].value.ToString().Split('.')[0];

                        model.Name16 = deviceVueList[7].name;//报警
                        model.Value16 = deviceVueList[7].value.ToString().Split('.')[0];

                        model.Name17 = "主加热器";//主加热器1
                        model.Value17 = deviceVueList[8].value.ToString().Split('.')[0];

                        model.Name18 = "辅助加热器";//辅助加热器1
                        model.Value18 = deviceVueList[9].value.ToString();

                        model.Name19 = "主风机";//主风机1
                        model.Value19 = deviceVueList[10].value.ToString().Split('.')[0];


                    }
                }


                #endregion




            }

            //model.Id = id;
            return View(model);
        }
        #endregion

        #region 喷漆房3
        public async Task<IActionResult> PaintRoom3()
        {

            DeviceValueModel model = new DeviceValueModel();

            TokenResult tokenResult = GetToken(new AccessUser { client_id = "b19d14eeacb74522bd29627b79c18ab8", client_secret = "7b89e021586c43d3b79440ba6eea0b67" });
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResult.access_token);
                var requestt = new HttpRequestMessage(HttpMethod.Get, "https://fbox360.com/api/client/box/grouped");
                requestt.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var response = await client.SendAsync(requestt);
                string result = await response.Content.ReadAsStringAsync();
                if (response.StatusCode != HttpStatusCode.OK)
                {

                }
                else
                {
                    //todo 
                }
            }
            using (HttpClient client = new HttpClient())
            {
                string postData = Newtonsoft.Json.JsonConvert.SerializeObject(new
                {
                    names = new List<string> {
                        "自动油雾过滤器电子差压计D0实际值",
        "前处理过滤箱电子差压计D2实际值",
        "前处理过滤箱电子差压计D3实际值",
        "蜂窝沸石转筒电子差压计D4实际值",
        "\"数据块_3\".运行时间记录_D",
        "\"数据块_3\".运行时间记录_H",
        "\"数据块_3\".运行时间记录_M",
        "报警3",
        "主加热器3",
        "辅助加热器3",
        "主风机3"},
                    groupnames = new List<string> {
                        "喷漆房3",
        "喷漆房3",
        "喷漆房3",
        "喷漆房3",
        "喷漆房3",
        "喷漆房3",
        "喷漆房3",
        "喷漆房3",
        "喷漆房3",
        "喷漆房3",
        "喷漆房3"},
                    timeOut = 6000
                });


                #region ceshi
                using (var httpClient = new HttpClient())
                {
                    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResult.access_token);
                    httpClient.BaseAddress = new Uri("http://fbcs101.fbox360.com/api/v2/dmon/value/get?boxNo=300220010352");
                    httpClient.DefaultRequestHeaders.Accept.Clear();
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    var jsonString = postData;
                    HttpResponseMessage esponse = await httpClient.PostAsync(httpClient.BaseAddress, new StringContent(jsonString, Encoding.UTF8, "application/json"));

                    if (esponse.IsSuccessStatusCode)
                    {
                        string json = await esponse.Content.ReadAsStringAsync();

                        List<DeviceVlue> deviceVueList = JsonConvert.DeserializeObject<List<DeviceVlue>>(json);
                        model.Name = "自动油雾过滤器电子差压计D0实值";
                        model.Value = deviceVueList[0].value.ToString().Split('.')[0];

                        model.Name10 = deviceVueList[1].name;
                        model.Value10 = deviceVueList[1].value.ToString().Split('.')[0];

                        model.Name11 = deviceVueList[2].name;
                        model.Value11 = deviceVueList[2].value.ToString().Split('.')[0];

                        model.Name12 = deviceVueList[3].name;
                        model.Value12 = deviceVueList[3].value.ToString().Split('.')[0];

                        model.Name13 = "运行时间"; //(天)
                        model.Value13 = deviceVueList[4].value.ToString().Split('.')[0];

                        model.Name14 = "运行时间"; //(时)
                        model.Value14 = deviceVueList[5].value.ToString().Split('.')[0];

                        model.Name15 = "运行时间";//((分)) 
                        model.Value15 = deviceVueList[6].value.ToString().Split('.')[0];

                        model.Name16 = deviceVueList[7].name;//报警
                        model.Value16 = deviceVueList[7].value.ToString().Split('.')[0];

                        model.Name17 = "主加热器";//主加热器1
                        model.Value17 = deviceVueList[8].value.ToString().Split('.')[0];

                        model.Name18 = "辅助加热器";//辅助加热器1
                        model.Value18 = deviceVueList[9].value.ToString();

                        model.Name19 = "主风机";//主风机1
                        model.Value19 = deviceVueList[10].value.ToString().Split('.')[0];


                    }
                }


                #endregion




            }

            return View(model);
        }
        #endregion

        #region 喷漆房4
        public async Task<IActionResult> PaintRoom4()
        {

            DeviceValueModel model = new DeviceValueModel();

            TokenResult tokenResult = GetToken(new AccessUser { client_id = "b19d14eeacb74522bd29627b79c18ab8", client_secret = "7b89e021586c43d3b79440ba6eea0b67" });
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResult.access_token);
                var requestt = new HttpRequestMessage(HttpMethod.Get, "https://fbox360.com/api/client/box/grouped");
                requestt.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var response = await client.SendAsync(requestt);
                string result = await response.Content.ReadAsStringAsync();
                if (response.StatusCode != HttpStatusCode.OK)
                {

                }
                else
                {
                    //todo 
                }
            }

            using (HttpClient client = new HttpClient())
            {
                string postData = Newtonsoft.Json.JsonConvert.SerializeObject(new
                {
                    names = new List<string> {
                        "自动油雾过滤器电子差压计D0实际值",
        "前处理过滤箱电子差压计D2实际值",
        "前处理过滤箱电子差压计D3实际值",
        "蜂窝沸石转筒电子差压计D4实际值",
        "\"数据块_1\".运行时间记录_D",
        "\"数据块_1\".运行时间记录_H",
        "\"数据块_1\".运行时间记录_M",
        "报警4",
        "主加热器4",
        "辅助加热器4",
        "主风机4"},
                    groupnames = new List<string> {
                        "喷漆房4",
        "喷漆房4",
        "喷漆房4",
        "喷漆房4",
        "喷漆房4",
        "喷漆房4",
        "喷漆房4",
        "喷漆房4",
        "喷漆房4",
        "喷漆房4",
        "喷漆房4"},
                    timeOut = 6000
                });
                //string s = @"{\"ids\":[\"224275280344535204\"]}";


                #region ceshi
                using (var httpClient = new HttpClient())
                {
                    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResult.access_token);
                    httpClient.BaseAddress = new Uri("http://fbcs101.fbox360.com/api/v2/dmon/value/get?boxNo=300220010352");
                    httpClient.DefaultRequestHeaders.Accept.Clear();
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    var jsonString = postData;
                    HttpResponseMessage esponse = await httpClient.PostAsync(httpClient.BaseAddress, new StringContent(jsonString, Encoding.UTF8, "application/json"));

                    if (esponse.IsSuccessStatusCode)
                    {
                        string json = await esponse.Content.ReadAsStringAsync();

                        List<DeviceVlue> deviceVueList = JsonConvert.DeserializeObject<List<DeviceVlue>>(json);
                        model.Name = "自动油雾过滤器电子差压计D0实值";
                        model.Value = deviceVueList[0].value.ToString().Split('.')[0];

                        model.Name10 = deviceVueList[1].name;
                        model.Value10 = deviceVueList[1].value.ToString().Split('.')[0];

                        model.Name11 = deviceVueList[2].name;
                        model.Value11 = deviceVueList[2].value.ToString().Split('.')[0];

                        model.Name12 = deviceVueList[3].name;
                        model.Value12 = deviceVueList[3].value.ToString().Split('.')[0];

                        model.Name13 = "运行时间"; //(天)
                        model.Value13 = deviceVueList[4].value.ToString().Split('.')[0];

                        model.Name14 = "运行时间"; //(时)
                        model.Value14 = deviceVueList[5].value.ToString().Split('.')[0];

                        model.Name15 = "运行时间";//((分)) 
                        model.Value15 = deviceVueList[6].value.ToString().Split('.')[0];

                        model.Name16 = deviceVueList[7].name;//报警
                        model.Value16 = deviceVueList[7].value.ToString().Split('.')[0];

                        model.Name17 = "主加热器";//主加热器1
                        model.Value17 = deviceVueList[8].value.ToString().Split('.')[0];

                        model.Name18 = "辅助加热器";//辅助加热器1
                        model.Value18 = deviceVueList[9].value.ToString();

                        model.Name19 = "主风机";//主风机1
                        model.Value19 = deviceVueList[10].value.ToString().Split('.')[0];


                    }
                }


                #endregion





                //using (var httpClient = new HttpClient())
                //{
                //    httpClient.DefaultRequestHeaders.Accept.Clear();
                //    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                //    HttpResponseMessage response = await httpClient.GetAsync("https://www.ropiniot.com/DigitalEnvironmentTest/api/TdevWebScada/GetWebScadaAsync/d4f4f4ac-3248-418a-a489-498478665539", HttpCompletionOption.ResponseHeadersRead);
                //    if (response.IsSuccessStatusCode)
                //    {
                //        Console.WriteLine($"Response Status Code: {(int)response.StatusCode} " + $"{response.ReasonPhrase}");
                //        var result = await response.Content.ReadAsStringAsync();
                //        DataResult devWebScada = JsonConvert.DeserializeObject<DataResult>(result);
                //        model.Html = devWebScada.data.C_Content;
                //    }
                //}

            }

            return View(model);
        }
        #endregion

        #region 喷漆房5
        public async Task<IActionResult> PaintRoom5()
        {

            DeviceValueModel model = new DeviceValueModel();

            TokenResult tokenResult = GetToken(new AccessUser { client_id = "b19d14eeacb74522bd29627b79c18ab8", client_secret = "7b89e021586c43d3b79440ba6eea0b67" });
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResult.access_token);
                var requestt = new HttpRequestMessage(HttpMethod.Get, "https://fbox360.com/api/client/box/grouped");
                requestt.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var response = await client.SendAsync(requestt);
                string result = await response.Content.ReadAsStringAsync();
                if (response.StatusCode != HttpStatusCode.OK)
                {

                }
                else
                {
                    //todo 
                }
            }

            using (HttpClient client = new HttpClient())
            {
                string postData = Newtonsoft.Json.JsonConvert.SerializeObject(new
                {
                    names = new List<string> {
                        "非甲烷总烃",
                        "非甲烷总烃排放速率",
                        "废气温度",
                        "废气压力",
                        "废气流速",
                        "废气湿度",
                        "废气标态流量",
                        "甲烷",
                        "总烃",
                        "苯",
                        "甲苯",
                        "二甲苯",
                        "氧气"},
                    groupnames = new List<string> {
                        "Default Group",
                        "Default Group",
                        "Default Group",
                        "Default Group",
                        "Default Group",
                        "Default Group",
                        "Default Group",
                        "Default Group",
                        "Default Group",
                        "Default Group",
                        "Default Group",
                        "Default Group",
                        "Default Group"},
                    timeOut = 6000
                });
                //string s = @"{\"ids\":[\"224275280344535204\"]}";


                #region ceshi
                using (var httpClient = new HttpClient())
                {
                    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResult.access_token);
                    httpClient.BaseAddress = new Uri("http://fbcs101.fbox360.com/api/v2/dmon/value/get?boxNo=300221100748");
                    httpClient.DefaultRequestHeaders.Accept.Clear();
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    var jsonString = postData;
                    HttpResponseMessage esponse = await httpClient.PostAsync(httpClient.BaseAddress, new StringContent(jsonString, Encoding.UTF8, "application/json"));

                    if (esponse.IsSuccessStatusCode)
                    {
                        string json = await esponse.Content.ReadAsStringAsync();

                        List<DeviceVlue> deviceVueList = JsonConvert.DeserializeObject<List<DeviceVlue>>(json);
                        model.NameE = deviceVueList[0].name;
                        model.ValueE = deviceVueList[0].value.ToString().Split('.')[0];

                        model.NameE10 = deviceVueList[1].name;
                        model.ValueE10 = deviceVueList[1].value.ToString().Split('.')[0];

                        model.NameE11 = deviceVueList[2].name;
                        model.ValueE11 = deviceVueList[2].value.ToString().Split('.')[0];

                        model.NameE12 = deviceVueList[3].name;
                        model.ValueE12 = deviceVueList[3].value.ToString().Split('.')[0];

                        model.NameE13 = deviceVueList[4].name;
                        model.ValueE13 = deviceVueList[4].value.ToString().Split('.')[0];

                        model.NameE14 = deviceVueList[5].name;
                        model.ValueE14 = deviceVueList[5].value.ToString().Split('.')[0];

                        model.NameE15 = deviceVueList[6].name;
                        model.ValueE15 = deviceVueList[6].value.ToString().Split('.')[0];

                        model.NameE16 = deviceVueList[7].name;
                        model.ValueE16 = deviceVueList[7].value.ToString().Split('.')[0];

                        model.NameE17 = deviceVueList[8].name;
                        model.ValueE17 = deviceVueList[8].value.ToString().Split('.')[0];

                        model.NameE18 = deviceVueList[9].name;
                        model.ValueE18 = deviceVueList[9].value.ToString();

                        model.NameE19 = deviceVueList[10].name;
                        model.ValueE19 = deviceVueList[10].value.ToString().Split('.')[0];


                    }
                }


                #endregion





                //using (var httpClient = new HttpClient())
                //{
                //    httpClient.DefaultRequestHeaders.Accept.Clear();
                //    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                //    HttpResponseMessage response = await httpClient.GetAsync("https://www.ropiniot.com/DigitalEnvironmentTest/api/TdevWebScada/GetWebScadaAsync/d4f4f4ac-3248-418a-a489-498478665539", HttpCompletionOption.ResponseHeadersRead);
                //    if (response.IsSuccessStatusCode)
                //    {
                //        Console.WriteLine($"Response Status Code: {(int)response.StatusCode} " + $"{response.ReasonPhrase}");
                //        var result = await response.Content.ReadAsStringAsync();
                //        DataResult devWebScada = JsonConvert.DeserializeObject<DataResult>(result);
                //        model.Html = devWebScada.data.C_Content;
                //    }
                //}

            }

            return View(model);
        }
        #endregion

        /// <summary>
        /// WebScada
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> WebScada()
        {
            DeviceValueModel model = new DeviceValueModel();

            TokenResult tokenResult = GetToken(new AccessUser { client_id = "b19d14eeacb74522bd29627b79c18ab8", client_secret = "7b89e021586c43d3b79440ba6eea0b67" });
            using (HttpClient client = new HttpClient())
            {
                client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResult.access_token);
                var requestt = new HttpRequestMessage(HttpMethod.Get, "https://fbox360.com/api/client/box/grouped");
                requestt.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                var response = await client.SendAsync(requestt);
                string result = await response.Content.ReadAsStringAsync();
                if (response.StatusCode != HttpStatusCode.OK)
                {

                }
                else
                {
                    //todo 
                }
            }
            using (HttpClient client = new HttpClient())
            {
                string postData = Newtonsoft.Json.JsonConvert.SerializeObject(new
                {
                    names = new List<string> {
                        "自动油雾过滤器电子差压计D0实际值",
        "前处理过滤箱电子差压计D2实际值",
        "前处理过滤箱电子差压计D3实际值",
        "蜂窝沸石转筒电子差压计D4实际值",
        "\"数据块_1\".运行时间记录_D",
        "\"数据块_1\".运行时间记录_H",
        "\"数据块_1\".运行时间记录_M",
        "报警4",
        "主加热器4",
        "辅助加热器4",
        "主风机4"},
                    groupnames = new List<string> {
                        "喷漆房4",
        "喷漆房4",
        "喷漆房4",
        "喷漆房4",
        "喷漆房4",
        "喷漆房4",
        "喷漆房4",
        "喷漆房4",
        "喷漆房4",
        "喷漆房4",
        "喷漆房4"},
                    timeOut = 6000
                });


                #region ceshi
                using (var httpClient = new HttpClient())
                {
                    httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", tokenResult.access_token);
                    httpClient.BaseAddress = new Uri("http://fbcs101.fbox360.com/api/v2/dmon/value/get?boxNo=300220010352");
                    httpClient.DefaultRequestHeaders.Accept.Clear();
                    httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

                    var jsonString = postData;
                    HttpResponseMessage esponse = await httpClient.PostAsync(httpClient.BaseAddress, new StringContent(jsonString, Encoding.UTF8, "application/json"));

                    if (esponse.IsSuccessStatusCode)
                    {
                        string json = await esponse.Content.ReadAsStringAsync();

                        List<DeviceVlue> deviceVueList = JsonConvert.DeserializeObject<List<DeviceVlue>>(json);
                        model.Name = "自动油雾过滤器电子差压计D0实值";
                        model.Value = deviceVueList[0].value.ToString().Split('.')[0];

                        model.Name10 = deviceVueList[1].name;
                        model.Value10 = deviceVueList[1].value.ToString().Split('.')[0];

                        model.Name11 = deviceVueList[2].name;
                        model.Value11 = deviceVueList[2].value.ToString().Split('.')[0];

                        model.Name12 = deviceVueList[3].name;
                        model.Value12 = deviceVueList[3].value.ToString().Split('.')[0];

                        model.Name13 = "运行时间"; //(天)
                        model.Value13 = deviceVueList[4].value.ToString().Split('.')[0];

                        model.Name14 = "运行时间"; //(时)
                        model.Value14 = deviceVueList[5].value.ToString().Split('.')[0];

                        model.Name15 = "运行时间";//((分)) 
                        model.Value15 = deviceVueList[6].value.ToString().Split('.')[0];

                        model.Name16 = deviceVueList[7].name;//报警
                        model.Value16 = deviceVueList[7].value.ToString().Split('.')[0];

                        model.Name17 = "主加热器";//主加热器1
                        model.Value17 = deviceVueList[8].value.ToString().Split('.')[0];

                        model.Name18 = "辅助加热器";//辅助加热器1
                        model.Value18 = deviceVueList[9].value.ToString();

                        model.Name19 = "主风机";//主风机1
                        model.Value19 = deviceVueList[10].value.ToString().Split('.')[0];


                    }
                }


                #endregion

            }


            using (var httpClient = new HttpClient())
            {
                httpClient.DefaultRequestHeaders.Accept.Clear();
                httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                HttpResponseMessage response = await httpClient.GetAsync("https://www.ropiniot.com/DigitalEnvironmentTest/api/TdevWebScada/GetWebScadaAsync/d4f4f4ac-3248-418a-a489-498478665539", HttpCompletionOption.ResponseHeadersRead);
                if (response.IsSuccessStatusCode)
                {
                    var result = await response.Content.ReadAsStringAsync();
                    DataResult devWebScada = JsonConvert.DeserializeObject<DataResult>(result);
                    model.Html = devWebScada.data.C_Content;
                }
            }
            return View(model);
         }

    }

    public class DataResult
    {
        public TDEV_WebScada data { get; set; }
        public string code { get; set; }
        public string message { get; set; }
    }

    public class TDEV_WebScada
    {

        public string C_ID { get; set; }
        public string C_Name { get; set; }

        public string C_DevCode { get; set; }

        public string C_Content { get; set; }

        public string C_Remark { get; set; }

        public Guid C_CreateBy { get; set; }

        public DateTime D_CreateOn { get; set; }

        public Guid? C_LastUpdatedBy { get; set; }

        public DateTime? D_LastUpdatedOn { get; set; }

        public string C_Status { get; set; }
    }

    public class AccessUser
    {
        public string client_id { get; set; }
        public string client_secret { get; set; }
        public string refresh_token { get; set; }
    }
    public class TokenResult
    {
        public string access_token { get; set; }
        /// <summary>
        /// 有效期
        /// </summary>
        public int expires_in { get; set; }
        public string refresh_token { get; set; }
        public string token_type { get; set; }
        /// <summary>
        /// invalid_grant过期
        /// </summary>
        public string error { get; set; }

    }
    public class items
    {
        public string id { get; set; }
        public string grpId { get; set; }
        public string grpName { get; set; }
        public string name { get; set; }
        public string intDigits { get; set; }
        public string fracDigits { get; set; }
        public string privilege { get; set; }
        public string trafficSaving { get; set; }
        public string deadValue { get; set; }

    }
    public class Device
    {
        public string id { get; set; }
        public string name { get; set; }
        public List<items> items { get; set; }
    }
    public class DeviceVlue
    {
        public string id { get; set; }
        public string timestamp { get; set; }
        public int dataType { get; set; }
        public string name { get; set; }
        public double? value { get; set; }
        public string boxId { get; set; }
        public int status { get; set; }
        public int connState { get; set; }
        public string connStateTimestamp { get; set; }
    }
}