using DbBackup.ViewModel;
using DevExpress.XtraEditors;
using Oracle11;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static DevExpress.XtraEditors.Mask.MaskSettings;

namespace DbBackup
{
    public partial class Form1 : DevExpress.XtraEditors.XtraForm
    {
        List<LogInfo> logData1 = new List<LogInfo>();
        List<LogInfo> logData2 = new List<LogInfo>();
        public Form1()
        {
            InitializeComponent();
            tabbedControlGroup1.SelectedTabPageIndex = 0;
            gcLog.UseDefault(logData1).UseClear<LogInfo>().UseRowNumber().SetLogImageColumn(nameof(LogInfo.LogType), typeof(EnumLogType));
            gvLog.Columns[nameof(ViewModel.LogInfo.LogType)].MaxWidth = 100;
            gvLog.Columns[nameof(ViewModel.LogInfo.LogTime)].MaxWidth = 150;
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }
        //备份
        private async void btnBackup_Click(object sender, EventArgs e)
        {
            if (!txtBackupAll.Checked && !txtBackupIncrement.Checked)
            {
                DxHelper.MsgBoxHelper.ShowError("请选择备份类型");
                return;
            }
            string dbAddr = txtDbAddr.Text.Trim();
            string user = txtUser.Text.Trim();
            string pwd = txtPwd.Text.Trim();
            string service = txtService.Text.Trim();
            bool backupAll = txtBackupAll.Checked;
            btnBackup.Enabled = false;
            btnRestore.Enabled = false;
            await Task.Run(() =>
              {
                  if (backupAll)
                  {
                      try
                      {
                          Info("开始全量备份...");
                          var zipFile = DbHelper.BackupDb(dbAddr, user, pwd, service);//全量备份
                          Info($"全量备份完成，文件={zipFile}");
                      }
                      catch (Exception ex)
                      {
                          Err("全量备份出错", ex);
                          ClearNoneZipFile();
                      }
                  }
                  else
                  {
                      try
                      {
                          var allFile = txtAllFile.Text.Trim();
                          Info("开始增量备份...");
                          var zipFile = DbHelper.BackupIncrementDb(allFile, dbAddr, user, pwd, service);//增量备份
                          if (zipFile == null)
                          {
                              Info($"数据未作改变，不进行增量备份");
                          }
                          else
                          {
                              Info($"增量备份完成，文件={zipFile}");
                          }

                      }
                      catch (Exception ex)
                      {
                          Err("增量备份出错", ex);
                          ClearNoneZipFile();
                      }
                  }
              });
            btnBackup.Enabled = true;
            btnRestore.Enabled = true;


        }
        //还原
        private async void btnRestore_Click(object sender, EventArgs e)
        {
            btnBackup.Enabled = false;
            btnRestore.Enabled = false;
            await Task.Run(() =>
             {
                 string file = null;
                 try
                 {
                     string dbAddr = txtDbAddr2.Text.Trim();
                     string user = txtUser2.Text.Trim();
                     string pwd = txtPwd2.Text.Trim();
                     var sysPwd = txtSysPwd.Text.Trim();
                     string service = txtService2.Text.Trim();
                     file = txtDataFile.Text.Trim();
                     var fileName = Path.GetFileNameWithoutExtension(file);
                     Info($"开始还原文件{file}...");
                     if (fileName.Contains("Increment"))
                     {
                         DbHelper.RestoreIncrementDb(file, dbAddr, user, pwd, service);//还原增量文件
                     }
                     else
                     {
                         DbHelper.RestoreDb(file, dbAddr, user, pwd, sysPwd, service);//还原全量文件
                     }
                     Info($"文件{file}还原完成");
                 }
                 catch (Exception ex)
                 {
                     Err($"文件{file}还原失败", ex);
                     ClearNoneZipFile();
                 }
             });
            btnBackup.Enabled = true;
            btnRestore.Enabled = true;
        }
        private void btnOpenDir_Click(object sender, EventArgs e)
        {
            string dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Backup");
            System.Diagnostics.Process.Start("explorer.exe", dir);
        }
        private void txtBackupIncrement_CheckedChanged(object sender, EventArgs e)
        {
            CheckEdit currentCheckBox = (CheckEdit)sender;
            if (currentCheckBox.Checked)
            {
                txtBackupAll.Checked = false;
            }

        }
        private void txtBackupAll_CheckedChanged(object sender, EventArgs e)
        {
            CheckEdit currentCheckBox = (CheckEdit)sender;
            if (currentCheckBox.Checked)
            {
                txtBackupIncrement.Checked = false;
                itemAllFile.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
            }
            else
            {
                itemAllFile.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
            }
            layoutControl1.BestFit();
        }
        private void txtChooseFile_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog() { Filter = "|*.7z" };
            if (openFileDialog.ShowDialog() == DialogResult.OK)
            {
                var ctrl = sender as ButtonEdit;
                ctrl.Text = openFileDialog.FileName;
            }
        }
        private void Info(string msg)
        {
            Serilog.Log.Information(msg);
            this.Invoke(new Action(() =>
            {
                this.logData1.Insert(0, new LogInfo() { LogType = EnumLogType.Info, LogContent = msg });
                gvLog.RefreshData();
            }));
        }
        private void Err(string msg, Exception ex = null)
        {
            Serilog.Log.Error(ex, msg);
            this.Invoke(new Action(() =>
            {
                this.logData1.Insert(0, new LogInfo() { LogType = EnumLogType.Error, LogContent = msg });
                gvLog.RefreshData();
            }));
        }

        private void btnConnectTest1_Click(object sender, EventArgs e)
        {
            try
            {
                string dbAddr = txtDbAddr.Text.Trim();
                string user = txtUser.Text.Trim();
                string pwd = txtPwd.Text.Trim();
                string service = txtService.Text.Trim();
                DbHelper.TestConnection(dbAddr, user, pwd, service);
                Info("数据库连接测试成功");
            }
            catch (Exception ex)
            {
                Err("数据库连接测试失败!", ex);
            }
        }

        private void btnConnectTest2_Click(object sender, EventArgs e)
        {
            try
            {
                string dbAddr = txtDbAddr2.Text.Trim();
                string sysPwd = txtSysPwd.Text.Trim();
                string service = txtService2.Text.Trim();
                DbHelper.TestSysConnection(dbAddr, sysPwd, service);
                Info("数据库连接测试成功");
            }
            catch (Exception ex)
            {
                Err("数据库连接测试失败!", ex);
            }
        }

        private void ClearNoneZipFile()
        {
            var files = Directory.GetFiles("Backup");
            foreach (var item in files)
            {
                if (!item.ToUpper().EndsWith("7Z"))
                {
                    try
                    {
                        File.Delete(item);
                    }
                    catch
                    { }
                }
            }
        }
    }
}
