using BPASmartClient.CustomResource.UserControls;
using BPASmartClient.CustomResource.UserControls.MessageShow;
using BPASmartClient.Helper;
using BPASmartClient.IoT;
using BPASmartClient.ViewModel;
using DataVAPI.Tool.IOT;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
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.Navigation;
using System.Windows.Shapes;
using System.Windows.Threading;

namespace BPASmartClient.Control
{
    /// <summary>
    /// DataVView.xaml 的交互逻辑
    /// </summary>
    public partial class DataVView : UserControl
    {
        string OnPass=string.Empty;
        public DispatcherTimer dispatcherTimer;
        public DataVView()
        {
            InitializeComponent();
            OnPass = AESHelper.Decrypt(System.Configuration.ConfigurationManager.AppSettings["PasswordBox"].ToString());
            this.DataContext = DataVViewModel.GetInstance();
            dispatcherTimer = new DispatcherTimer();
            dispatcherTimer.Tick += delegate
            {
                System.Windows.Application.Current?.Dispatcher.Invoke((Action)(() =>
                {
                    Pass.Visibility = Visibility.Visible;
                    dispatcherTimer.Stop();
                }));
            };
            dispatcherTimer.Interval = TimeSpan.FromSeconds(120);
            
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            if (sender is Button)
            {
                bool istrue = false;
                Button button = sender as Button;
                if (button.Tag != null)
                {
                    switch (button.Tag.ToString())
                    {
                        case "Add":
                            istrue = DataVViewModel.GetInstance().Add();
                            if (istrue) NoticeDemoViewModel.OpenMsg(EnumPromptType.Success, MainViewModel.GetInstance().window, "提示", $"增加成功!");
                            else NoticeDemoViewModel.OpenMsg(EnumPromptType.Error, MainViewModel.GetInstance().window, "提示", $"增加失败!");
                            break;
                        case "Update":
                            if (string.IsNullOrEmpty(DataVViewModel.GetInstance().device.Id))
                            {
                                NoticeDemoViewModel.OpenMsg(EnumPromptType.Info, MainViewModel.GetInstance().window, "提示", $"请先“查询”或者“双击右侧表格行”，修改之后在点击“修改”!");
                                return;
                            }
                            istrue = DataVViewModel.GetInstance().Update();
                            if (istrue) NoticeDemoViewModel.OpenMsg(EnumPromptType.Success, MainViewModel.GetInstance().window, "提示", $"修改成功!");
                            else NoticeDemoViewModel.OpenMsg(EnumPromptType.Error, MainViewModel.GetInstance().window, "提示", $"修改失败!");
                            break;
                        case "Delete":
                            if (string.IsNullOrEmpty(DataVViewModel.GetInstance().device.Id))
                            {
                                NoticeDemoViewModel.OpenMsg(EnumPromptType.Info, MainViewModel.GetInstance().window, "提示", $"请先“查询”或者“双击右侧表格行”，修改之后在点击“删除”!");
                                return;
                            }
                            istrue = DataVViewModel.GetInstance().Delete();
                            if (istrue) NoticeDemoViewModel.OpenMsg(EnumPromptType.Success, MainViewModel.GetInstance().window, "提示", $"删除成功!");
                            else NoticeDemoViewModel.OpenMsg(EnumPromptType.Error, MainViewModel.GetInstance().window, "提示", $"删除失败!");
                            break;
                        case "SetUrl":
                            DataVViewModel.GetInstance().ApiURL = apiurl.Text;
                            DataVViewModel.GetInstance().Refresh();
                            NoticeDemoViewModel.OpenMsg(EnumPromptType.Success, MainViewModel.GetInstance().window, "提示", $"设置成功!");
                            //MessageBox.Show("设置成功");
                            break;
                        case "Inquire":
                            DataVViewModel.GetInstance().device = DataVViewModel.GetInstance().Inquire(chen.Text)?.FirstOrDefault();
                            break;
                        case "Save":
                            System.Windows.Forms.SaveFileDialog saveFileDialog = new System.Windows.Forms.SaveFileDialog();
                            saveFileDialog.Filter = "txt文件(*.txt)|*.txt";
                            if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                            {
                                StreamWriter sw = File.CreateText(saveFileDialog.FileName);
                                sw.Write(Tools.JsonConvertTools(DataVViewModel.GetInstance().deviceTable));  //写入文件中
                                sw.Flush();//清理缓冲区
                                sw.Close();//关闭文件
                            }
                            NoticeDemoViewModel.OpenMsg(EnumPromptType.Success, MainViewModel.GetInstance().window, "提示", $"导出设备成功,条数: {DataVViewModel.GetInstance().deviceTable.Count}!");
                            break;
                        case "Insert":
                            System.Windows.Forms.OpenFileDialog file = new System.Windows.Forms.OpenFileDialog();//定义新的文件打开位置控件
                            file.Filter = "txt文件(*.txt)|*.txt";//设置文件后缀的过滤
                            if (file.ShowDialog() == System.Windows.Forms.DialogResult.OK)//如果有选择打开文件
                            {
                                DeviceTable device = null;
                                FileStream fs = new FileStream(file.FileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                                StreamReader sr = new StreamReader(fs, System.Text.Encoding.UTF8);   //选择编码方式               
                                string str = sr.ReadToEnd();
                                if (!string.IsNullOrEmpty(str))
                                {
                                    Tools.JsonToObjectTools<List<DeviceTable>>(str)?.ForEach(par =>
                                    {
                                        DataVViewModel.GetInstance().Add(par);
                                    });
                                    NoticeDemoViewModel.OpenMsg(EnumPromptType.Success, MainViewModel.GetInstance().window, "提示", $"插入设备成功,条数: {Tools.JsonToObjectTools<List<DeviceTable>>(str)?.Count}!");
                                    DataVViewModel.GetInstance().Refresh();
                                }
                            }
                            break;
                        case "OkPass":
                            if (passbox.Password == OnPass)
                            {
                                Pass.Visibility = Visibility.Collapsed;
                                passbox.Password = "";
                                dispatcherTimer.Start();
                            }
                            else
                                NoticeDemoViewModel.OpenMsg(EnumPromptType.Warn, MainViewModel.GetInstance().window, "提示", $"密码输入错误!");
                            break;
                    }
                }
            }
        }

        private void DataGrid_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            DataVViewModel.GetInstance().device = DataVViewModel.GetInstance().deviceTableSelectedItem;
        }
    }
}
