using MECF.Framework.Common.DataCenter;
using MECF.Framework.UI.Client.ClientBase;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Data;
using System.Windows.Forms;
using Aitex.Core.Common.DeviceData;
using OpenSEMI.ClientBase;
using Aitex.Core.Util;

namespace SicUI.Models.PMs
{
    public class PMMfcRorViewModel : UiViewModelBase, ISupportMultipleSystem
    {
        private PMMfcRorView view;

        public DateTime SearchBeginTime
        {
            get => view.wfTimeFrom.Value;
            set
            {
                view.wfTimeFrom.Value = value;
                NotifyOfPropertyChange(nameof(SearchBeginTime));
            }
        }

        public DateTime SearchEndTime
        {
            get => view.wfTimeTo.Value;
            set
            {
                view.wfTimeTo.Value = value;
                NotifyOfPropertyChange(nameof(SearchEndTime));
            }
        }

        //标准MFC
        [Subscription("StandardMfcRorData")]
        public MfcRorData StandardMfcRorData { get; set; }

        [Subscription("MfcNameList")]
        public List<string> MfcNameList { get; set; }

        [Subscription("MfcRorList")]
        public List<MfcRorData> MfcRorList { get; set; }

        public List<MfcRorData> DataGridMfcRorList { get; set; }

        //选中的MFC
        public string SelectedMfcRorArray { get; set; }

        public MfcRorData SelectedMfcRorData { get; set; } = new MfcRorData();

        public MfcRorData[] SelectedMfcRorDataList { get; set; }

        protected override void OnViewLoaded(object view)
        {
            base.OnViewLoaded(view);

            // 默认的查询时间设置为当天
            this.view = (PMMfcRorView)view;
            SearchBeginTime = DateTime.Today;
            SearchEndTime = DateTime.Today.AddDays(1).AddTicks(-1);
        }

        public void MfcSelectionChanged()
        {
            if (string.IsNullOrEmpty(SelectedMfcRorArray))
            {
                return;
            }

            string[] mfcRorList = SelectedMfcRorArray.Split(',');

            if (mfcRorList == null || mfcRorList.Length == 0)
            {
                return;
            }

            SelectedMfcRorData.Name = mfcRorList[mfcRorList.Length - 1];

            SelectedMfcRorData.Scale = (double)QueryDataClient.Instance.Service.GetConfig($"PM.{SystemName}.MFC.{SelectedMfcRorData.Name}.N2Scale");

            SelectedMfcRorData.Temperature = 293;

            if(SelectedMfcRorData.Interval == 0)
            {
                SelectedMfcRorData.Interval = 30;
            }

            if (SelectedMfcRorData.BasePressure == 0)
            {
                SelectedMfcRorData.BasePressure = 100;
            }

            //MFC默认的设定流量为量程的一半
            SelectedMfcRorData.SetFlow = SelectedMfcRorData.Scale / 2.0;

            SelectedMfcRorData.Volume = StandardMfcRorData != null ? StandardMfcRorData.Volume : 0;

            SelectedMfcRorData.Module = SystemName;

            Refresh();
        }

        public void StartMfcRor()
        {
            if (string.IsNullOrEmpty(SelectedMfcRorArray))
            {
                MessageBox.Show("Please Select Mfc First!");
                return;
            }

            string[] mfcRorList = SelectedMfcRorArray.Split(',');

            if (mfcRorList == null || mfcRorList.Length == 0)
            {
                MessageBox.Show("Please Select Mfc First!");
                return;
            }

            if (mfcRorList.Count() == 1)
            {
                if (StandardMfcRorData == null && !SelectedMfcRorData.IsStandardMfc)
                {
                    MessageBox.Show("Standard Mfc do not Ror!");
                    return;
                }

                if (SelectedMfcRorData.IsStandardMfc)
                {
                    SelectedMfcRorData.ActualFlow = SelectedMfcRorData.SetFlow;
                }

                InvokeClient.Instance.Service.DoOperation($"{SystemName}.MfcRor", SelectedMfcRorData);
            }
            else
            {
                if (StandardMfcRorData == null)
                {
                    MessageBox.Show("Standard Mfc do not Ror!");
                    return;
                }

                SelectedMfcRorDataList = new MfcRorData[mfcRorList.Length];

                for (int i = 0; i < SelectedMfcRorDataList.Length; i++)
                {
                    SelectedMfcRorDataList[i] = new MfcRorData();

                    SelectedMfcRorDataList[i].Name = mfcRorList[i];

                    SelectedMfcRorDataList[i].Scale = (double)QueryDataClient.Instance.Service.GetConfig($"PM.{SystemName}.MFC.{SelectedMfcRorDataList[i].Name}.N2Scale");

                    SelectedMfcRorDataList[i].Temperature = 293;

                    SelectedMfcRorDataList[i].Interval = SelectedMfcRorData.Interval;

                    //MFC默认的设定流量为量程的一半
                    SelectedMfcRorDataList[i].SetFlow = SelectedMfcRorDataList[i].Scale / 2.0;

                    SelectedMfcRorDataList[i].BasePressure = SelectedMfcRorData.BasePressure;

                    SelectedMfcRorDataList[i].Volume = StandardMfcRorData != null ? StandardMfcRorData.Volume : 0;

                    SelectedMfcRorDataList[i].Module = SystemName;
                }

                InvokeClient.Instance.Service.DoOperation($"{SystemName}.MfcRor", SelectedMfcRorDataList);
            }
        }

        public void QueryData()
        {
            if (SearchBeginTime > SearchEndTime)
            {
                MessageBox.Show("Time range invalid, start time should be early than end time");
                return;
            }

            try
            {
                string sql = $"select * from \"pm_mfcror\" where \"module\" = '{SystemName}' and \"starttime\" >='{SearchBeginTime:yyyyMMdd HHmmss}' and  \"endtime\" <='{SearchEndTime:yyyyMMdd HHmmss}' order by \"endtime\" ASC";

                DataTable dbData = QueryDataClient.Instance.Service.QueryData(sql);

                DataGridMfcRorList = TableToListModel<MfcRorData>(dbData);

                Refresh();
            }
            catch (Exception)
            {

            }
        }

        public void ClearMfcRorData()
        {
            var selection = DialogBox.ShowDialog(DialogButton.Yes | DialogButton.Cancel, DialogType.CONFIRM,
               "Are you sure clear all mfc ror data?");
            if (selection == DialogButton.Yes)
            {
                InvokeClient.Instance.Service.DoOperation($"{SystemName}.ClearMfcRorData");
            }
        }

        public List<T> TableToListModel<T>(DataTable dt) where T : new()
        {
            // 定义集合    
            List<T> ts = new List<T>();

            // 获得此模型的类型   
            Type type = typeof(T);
            string tempName = "";

            foreach (DataRow dr in dt.Rows)
            {
                T t = new T();
                // 获得此模型的公共属性      
                PropertyInfo[] propertys = t.GetType().GetProperties();
                foreach (PropertyInfo pi in propertys)
                {
                    tempName = pi.Name;  // 检查DataTable是否包含此列    

                    if (dt.Columns.Contains(tempName))
                    {
                        // 判断此属性是否有Setter      
                        if (!pi.CanWrite) continue;

                        object value = dr[tempName];
                        if (value != DBNull.Value)
                            pi.SetValue(t, value, null);
                    }
                }
                ts.Add(t);
            }
            return ts;
        }
    }
}
