using FluentFTP;
using Tiobon.Core.OPS.Tool.OPS.Tool.Helper;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Windows.Forms;

namespace Tiobon.Core.OPS.Tool.OPS.Tool.View
{
    public partial class Frm_Backup : Form
    {
        public Frm_Backup()
        {
            InitializeComponent();
        }

        private void Frm_Backup_Load(object sender, EventArgs e)
        {
            if (Const.config.system == "Linux")
            {
                cb_type.Items.RemoveAt(1);
                rad_local.Enabled = false;
            }
        }

        private void Rad_week_CheckedChanged(object sender, EventArgs e)
        {
            if (rad_week.Checked)
            {
                label9.Text = "周发生一次：";
                foreach (var item in groupBox4.Controls)
                {
                    var cb = item as CheckBox;
                    if (cb != null)
                    {
                        cb.Visible = true;
                    }
                }
            }
        }

        private void Rad_day_CheckedChanged(object sender, EventArgs e)
        {
            if (rad_day.Checked)
            {
                label9.Text = "天发生一次：";
                foreach (var item in groupBox4.Controls)
                {
                    var cb = item as CheckBox;
                    if (cb != null)
                    {
                        cb.Visible = false;
                    }
                }
            }
        }

        private void Btn_save_Click(object sender, EventArgs e)
        {
            build_Savebat();
        }

        private void build_Savebat()
        {
            try
            {
                if (Const.config.system == "Windows")
                {
                    string command = $"set filename={Const.config.install_dir}/back/mysql/ihdis_back_%date:~0,4%%date:~5,2%%date:~8,2%.sql\r\n" +
    $"sudo docker-compose exec -T mysql mysql  -uroot -pjlmed@2020  " +
    //$"{Const.config.install_dir}/app/mysql/bin/mysqldump.exe --set-gtid-purged=OFF -h127.0.0.1 -u{Const.config.db_user} -p{Const.config.db_passwd} -P{Const.config.db_port} " +
    $"--single-transaction ";
                    command += $"--databases ihdis ihdis_ts > %filename% \r\n";
                    if (!Directory.Exists(Const.config.install_dir + "/back/mysql"))
                    {
                        Directory.CreateDirectory(Const.config.install_dir + "/back/mysql");
                    }
                    if (rad_local.Checked)
                    {
                        command += $"xcopy /y \"%filename%\"  \"{txt_dir.Text.Trim()}\"";
                    }
                    else
                    {
                        if (cb_type.Text=="FTP")
                        {
                            command += $"Echo open {txt_ip.Text.Trim()}>ftp.up\r\n" +
                                $"Echo {txt_user.Text.Trim()}>>ftp.up\r\n" +
                                $"Echo {txt_passwd.Text.Trim()}>>ftp.up\r\n" +
                                $"Echo cd \\{txt_dir.Text.Trim()} >>ftp.up\r\n" +
                                $"Echo put \"%filename%\">>ftp.up\r\n" +
                                $"Echo bye>>ftp.up\r\n" +
                                $"FTP -s:ftp.up >> ftpup.log\r\n" +
                                $"del ftp.up /q\r\n";
                        }
                        else
                        {
                            command += $"net use \\\\{txt_ip.Text.Trim()}\\{txt_dir.Text.Trim()} {txt_passwd.Text}  /user:{txt_user.Text} \r\n";
                            command += $"xcopy /y \"%filename%\"  \"\\\\{txt_ip.Text.Trim()}\\{txt_dir.Text.Trim()}\"";
                        }
                    }
                    File.WriteAllText($"{Const.config.install_dir}/back/mysql_backup.bat", command);


                    string task = $"schtasks /create /tn \"iHDIS_Mysql_Backup\" /tr \"{Const.config.install_item_dir}/back/mysql_backup.bat\" /F /RU SYSTEM";
                    if (rad_day.Checked)
                    {
                        task += $" /sc DAILY  /NP /ST {date_time.Value.ToString("HH:mm")}";
                    }
                    else
                    {
                        task += $" /sc WEEKLY /D ";
                        if (cb_one.Checked)
                            task += "MON,";
                        if (cb_two.Checked)
                            task += "TUE,";
                        if (cb_three.Checked)
                            task += "WED,";
                        if (cb_four.Checked)
                            task += "THU,";
                        if (cb_five.Checked)
                            task += "FRI,";
                        if (cb_six.Checked)
                            task += "SAT,";
                        if (cb_seven.Checked)
                            task += "SUN,";
                        if (!cb_one.Checked && !cb_two.Checked && !cb_three.Checked && !cb_four.Checked && !cb_five.Checked && !cb_six.Checked && !cb_seven.Checked)
                        {
                            task += " * ";
                        }
                        if (task[task.Length - 1] == ',')
                        {
                            task = task.Remove(task.Length - 1, 1);
                        }
                        task += $" /NP /ST {date_time.Value.ToString("HH:mm")}";
                    }
                    CmdHelper.RunCmd(task, out string output);
                }
                else
                {
                    string command = $"sudo docker-compose -f {Const.config.install_dir}/docker-compose.yml exec -T mysql mysqldump --set-gtid-purged=OFF -uroot -pjlmed@2020 --single-transaction ";
                    //if (!cb_saveiot.Checked)
                    //{
                    //    command += "--ignore-table=ihdis.iot_treatment_data";
                    //}
                    //if (!cb_savelog.Checked)
                    //{
                    //    command += "--ignore-table=ihdis.sys_log";
                    //}
                    SFTPHelper sftp = new SFTPHelper(Const.config.ip, Const.config.ssh_port, Const.config.ssh_user, Const.config.ssh_passwd);
                    if (!sftp.Exists($"{Const.config.install_dir}/back/mysql/"))
                    {
                        try
                        {
                            sftp.Connect();
                            sftp.CreateDirectory($"{Const.config.install_dir}/back/mysql/");
                            sftp.Disconnect();
                        }
                        catch (Exception ex)
                        {
                            MessageBox.Show(ex.Message);
                        }
                    }
                    command += $" --databases ihdis ihdis_ts > {Const.config.install_dir}/back/mysql/\\$filename && sed -i \\'1d\\' {Const.config.install_dir}/back/mysql/\\$filename";

                    string task = "";
                    if (rad_day.Checked)
                    {
                        task += $"{date_time.Value.ToString("mm")} {date_time.Value.ToString("HH")} \\* \\* \\* jianlianmed /bin/bash {Const.config.install_dir}/back/mysql_backup.sh";
                    }
                    else
                    {
                        task += $"{date_time.Value.ToString("mm")} {date_time.Value.ToString("HH")} \\* \\* ";
                        if (cb_one.Checked)
                            task += "1,";
                        if (cb_two.Checked)
                            task += "2,";
                        if (cb_three.Checked)
                            task += "3,";
                        if (cb_four.Checked)
                            task += "4,";
                        if (cb_five.Checked)
                            task += "5,";
                        if (cb_six.Checked)
                            task += "6,";
                        if (cb_seven.Checked)
                            task += "7,";
                        if (!cb_one.Checked && !cb_two.Checked && !cb_three.Checked && !cb_four.Checked && !cb_five.Checked && !cb_six.Checked && !cb_seven.Checked)
                        {
                            task += " \\* ";
                        }
                        if (task[task.Length - 1] == ',')
                        {
                            task = task.Remove(task.Length - 1, 1);
                        }
                        task += $" jianlianmed /bin/bash {Const.config.install_dir}/back/mysql_backup.sh";
                    }
                    string sh = $"filename=\\\"ihdis_back_\\`date +\\\"%Y%m%d\\\"\\`.sql\\\" \n" +
                        $"{command} \n" +
                        $"ftp -n<<!\n" +
                        $"open {txt_ip.Text.Trim()}\n" +
                        $"user {txt_user.Text.Trim()} {txt_passwd.Text.Trim()}\n" +
                        $"binary\n" +
                        $"cd {txt_dir.Text.Trim()}\n" +
                        $"prompt\n" +
                        $"put {Const.config.install_dir}/back/mysql/\\$filename \\$filename\n" +
                        $"close\n" +
                        $"!";
                    SSHHelper ssh = new SSHHelper(Const.config.ip, Const.config.ssh_port, Const.config.ssh_user, Const.config.ssh_passwd);
                    ssh.Excute_cmd($"sudo sh -c \"echo {task} >> /etc/crontab\"", out _);
                    var cmd = $"sudo sh -c \"echo -e {sh} >> {Const.config.install_dir}/back/mysql_backup.sh\"";
                    ssh.Excute_cmd($"sudo sh -c 'echo -e \"{sh}\" > {Const.config.install_dir}/back/mysql_backup.sh'", out _);
                }
                MessageBox.Show("创建定时备份成功！");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"创建定时任务失败！{ex.Message}");
            }

        }



        private void Cb_type_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void Rad_local_CheckedChanged(object sender, EventArgs e)
        {
            label1.Enabled = !rad_local.Checked;
            label2.Enabled = !rad_local.Checked;
            label4.Enabled = !rad_local.Checked;
            label5.Enabled = !rad_local.Checked;

            txt_ip.Enabled = !rad_local.Checked;
            cb_type.Enabled = !rad_local.Checked;
            txt_user.Enabled = !rad_local.Checked;
            txt_passwd.Enabled = !rad_local.Checked;
        }

        private void btn_test_Click(object sender, EventArgs e)
        {
            if (cb_type.Text == "共享目录")
            {
                string path = $@"\\{txt_ip.Text}\{txt_dir.Text}";
                //连接共享目录
                bool status = ShareDirHelper.connectState(path, txt_user.Text.Trim(), txt_passwd.Text.Trim());
                if (status)
                {
                    MessageBox.Show($"连接成功，备份目录为：\r\n{path}", "提示");
                }
                else
                {
                    MessageBox.Show("连接不到指定目录");
                }
            }
            else
            {
                //ftp客户端
                FtpClient client = new FtpClient(txt_ip.Text);
                //是否填写用户名，有则添加认证，否则使用匿名用户
                if (!string.IsNullOrEmpty(txt_user.Text.Trim()))
                {
                    client.Credentials = new NetworkCredential(txt_user.Text.Trim(), txt_passwd.Text.Trim());
                }
                try
                {
                    client.Connect();
                    if (!client.DirectoryExists(txt_dir.Text.Trim()))
                    {
                        if (MessageBox.Show("目录不存在，是否自动创建？", "提示", MessageBoxButtons.YesNo) == DialogResult.Yes)
                        {
                            client.CreateDirectory(txt_dir.Text, true);
                        }
                        return;
                    }
                    client.Disconnect();
                    MessageBox.Show($"连接成功，备份目录为：\r\nftp://{txt_ip.Text}/{txt_dir.Text}/", "提示");
                }
                catch (Exception ex)
                {
                    MessageBox.Show("测试连接失败！\r\n" + ex.Message);
                }
            }
        }

        private void txt_dir_MouseClick(object sender, MouseEventArgs e)
        {
            if (rad_local.Checked)
            {
                if (folderBrowserDialog1.ShowDialog() == DialogResult.Cancel)
                {
                    return;
                }
                txt_dir.Text = folderBrowserDialog1.SelectedPath;
            }
        }
    }
}
