using MeterVision.db;
using MeterVision.FreeAi;
using MeterVision.Util;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace MeterVision.Patch
{
    /// <summary>
    /// AddPatchDlg.xaml 的交互逻辑
    /// </summary>
    public partial class AddPatchDlg : Window, INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        public TPatch NewPatch { get; set; }

        //下拉框绑定的数据
        public ObservableCollection<VStand> StandList { get; set; }

        private SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);


        public AddPatchDlg()
        {
            InitializeComponent();

            StandList = new ObservableCollection<VStand>();
            cmbStand.ItemsSource = StandList;
          
            this.DataContext = this;
            LoadStandList();
        }

        private async void LoadStandList()
        {
            try
            {
               var stands = await Task.Run(() => DBStand.GetAllVStands());
                StandList.Clear();
                foreach (VStand stand in stands)
                {
                    StandList.Add(stand);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载数据失败：{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        private async void BtnOK_Click(object sender, RoutedEventArgs e)
        {
            if (!_semaphore.Wait(0)) return; // 如果信号量已被占用，直接返回

            this.IsEnabled = false;
            try
            {
                string patchName = txtPatchName.Text.ToString();
                if (string.IsNullOrWhiteSpace(patchName))
                {
                    MessageBox.Show("请填写批量任务的名称！");
                    return;
                }

                var standItem = cmbStand.SelectedItem as VStand;
                if (standItem == null)
                {
                    MessageBox.Show("请选择一个标准模板！");
                    return;
                }

                NewPatch = new TPatch
                {
                    PatchId = Guid.NewGuid().ToString(),
                    CreateTime = ThisApp.GetNowTime_yyyyMMddHHmmss(),
                    PatchName = patchName,
                    StandId = standItem.StandId,
                    StandName = standItem.StandName
                };
                string standId = standItem.StandId;

                bool result = await InsertTPatchAndDetailAsync(NewPatch, standId);
                if (result)
                {
                    this.DialogResult = true;
                    this.Close();
                }
                else
                {
                    MessageBox.Show("保存批量任务失败，请重试！", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch { }
            finally
            {
                _semaphore.Release();
                this.IsEnabled = true;
            }
        }

        
        //最好能异步(要不会阻塞主线程)
        private async Task<bool> InsertTPatchAndDetailAsync(TPatch patch,string standId)
        {
            //插入t_patch表与插入t_patch_detail表应该在一个事务中，还需要优化
            //插入t_patch表
            return await Task.Run(() =>
            {
                return InsertTPatchAndDetail(patch, standId);
            });
        }


        private bool InsertTPatchAndDetail(TPatch patch,string standId)
        {
            try
            {
                //1. 从指定stand_id的t_station表中查询配置了数据的站点，
                //要求,meter_type > 0,meter_region,feature_region,last_time !=""


                // 查询 t_stand_detail 表
                var patchDetails = new List<TPatchDetail>();
                //var stations = DBStation.GetAllStation(standId);
                var stations = DBStation.GetAllVStation(standId);

                //TStandDetail validStandDetail = null;   //有效的模板明细

                foreach(var station in stations)
                {
                    TStandDetail validStandDetail = null;       ////有效的模板明细
                    var standDetails = DBStand.GetAllStandDetails(standId, station.StationId);

                    for(int i = 0; i < standDetails.Count; i++)
                    {
                        var standDetail = standDetails[i];

                        if(standDetail.MeterType > 0)
                        {
                            //有有效配置
                            validStandDetail = new TStandDetail();
                            ObjectHelper.CopyMatchingFields(standDetail, validStandDetail);
                        }
                        
                        if(validStandDetail == null)
                        {
                            continue;   //无有效的数据则继续循环
                        }

                        var patchDetail = new TPatchDetail();
                        patchDetail.PatchId = patch.PatchId;
                        patchDetail.PatchDetailId = Guid.NewGuid().ToString();
                        patchDetail.CreateTime = ThisApp.GetNowTime_yyyyMMddHHmmss();
                        patchDetail.StandDetailId = standDetail.StandDetailId;
                        patchDetail.StandValue = standDetail.StandValue;
                        patchDetail.SrcImage = standDetail.SrcImage;
                        patchDetail.SampleTime = standDetail.SampleTime;
                        patchDetail.StationKey = station.Id;
                        patchDetail.StationId = station.StationId;
                        //用有效的配置
                        patchDetail.MeterType = validStandDetail.MeterType;
                        patchDetail.BrightVal = validStandDetail.BrightVal;
                        patchDetail.FlowRate = validStandDetail.FlowRate;
                        patchDetail.DigitCount = validStandDetail.NumCount;
                        patchDetail.PointerCount = validStandDetail.IndCount;
                        patchDetail.LastUnit = validStandDetail.LastUnit;
                        patchDetail.MeterRegion = validStandDetail.DialRegion;
                        patchDetail.FeatureRegion = validStandDetail.FeatureRegion;                      
                        if (standDetail.MeterType > 0)
                        {
                            //第一条有效的数据
                            patchDetail.LastCompress = 100;
                            patchDetail.LatestValue = (long)(validStandDetail.LastValue * FaConstant.CUBE_VALUE);
                            patchDetail.LatestTime = validStandDetail.LastTime;
                        }
                        patchDetails.Add(patchDetail);
                    }
                }

                if (patchDetails.Count > 0)
                {
                    bool blInsert = DBPatch.InsertPatchAndDetails(patch, patchDetails);
                    return blInsert;
                }
                return false;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"插入数据失败：{ex.Message}");
                return false;
            }
        }


        private void BtnClose_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
            this.Close() ;
        }

        //private void CmbStand_Selected(object sender, RoutedEventArgs e)
        //{
        //    var standItem = cmbStand.SelectedItem as VStand;
        //    if(standItem != null)
        //    {
        //        string patchName = txtPatchName.Text.Trim();
        //        if (string.IsNullOrWhiteSpace(patchName))
        //        {
        //            txtPatchName.Text = $"任务-{standItem.StandName}";
        //        }
        //    }
        //}

        private void CmbStand_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var standItem = cmbStand.SelectedItem as VStand;
            if (standItem != null)
            {
                string patchName = txtPatchName.Text.Trim();
                if (string.IsNullOrWhiteSpace(patchName))
                {
                    txtPatchName.Text = $"任务-{standItem.StandName}";
                }
            }
        }
        //----------------------------------------------------------
    }
}
