using System.Text.Json;
using System.Threading.Tasks;

namespace NBConfigBuilder
{
    public partial class Form1 : Form
    {
        // 配置文件路径
        private readonly string configPath =
            Path.Combine(Path.GetDirectoryName(Application.ExecutablePath) ?? string.Empty, "config.json");

        // 保存原始标题
        private string _originalTitle;

        public Form1()
        {
            InitializeComponent();
            // 设置窗口大小不可变
            this.FormBorderStyle = FormBorderStyle.FixedSingle;
            this.MaximizeBox = false;

            // 保存原始标题
            _originalTitle = this.Text;

            // 加载保存的配置
            LoadConfig();
        }

        private async void buttonRun_Click(object sender, EventArgs e)
        {
            // 禁用按钮防止重复点击
            buttonRun.Enabled = false;
            buttonRun.Text = "执行中...";

            try
            {
                // 保存当前配置
                SaveConfig();

                // 创建导出器并设置进度回调
                var exporter = new ExcelExporter(ExportType.AllExcel);
                exporter.SetProgressCallback(UpdateProgress);

                // 运行导出器
                await Task.Run(() => exporter.Run());

                // 显示成功消息
                MessageBox.Show("配置导出完成！", "成功", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            catch (Exception ex)
            {
                // 显示错误消息
                MessageBox.Show($"导出过程中发生错误：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                // 恢复按钮状态和标题
                buttonRun.Enabled = true;
                buttonRun.Text = "执行";
                this.Text = _originalTitle;
            }
        }

        /// <summary>
        /// 更新进度显示
        /// </summary>
        /// <param name="message">进度消息</param>
        private void UpdateProgress(string message)
        {
            // 确保在UI线程上更新界面
            if (InvokeRequired)
            {
                Invoke(new Action<string>(UpdateProgress), message);
                return;
            }

            // 更新标题栏显示进度
            this.Text = $"{_originalTitle} - {message}";
        }

        private void buttonSelectExcelPath_Click(object sender, EventArgs e)
        {
            using (FolderBrowserDialog folderDlg = new FolderBrowserDialog())
            {
                folderDlg.Description = "请选择配置表路径";
                if (folderDlg.ShowDialog() == DialogResult.OK)
                {
                    textBoxExcelPath.Text = folderDlg.SelectedPath;
                }
            }
        }

        private void buttonSelectClientJsonPath_Click(object sender, EventArgs e)
        {
            using (FolderBrowserDialog folderDlg = new FolderBrowserDialog())
            {
                folderDlg.Description = @"选择客户端json保存目录";
                if (folderDlg.ShowDialog() == DialogResult.OK)
                {
                    textBoxClientGenJsonPath.Text = folderDlg.SelectedPath;
                }
            }
        }

        private void buttonSelectServerJsonPath_Click(object sender, EventArgs e)
        {
            using (FolderBrowserDialog folderDlg = new FolderBrowserDialog())
            {
                folderDlg.Description = @"选择服务端json保存目录";
                if (folderDlg.ShowDialog() == DialogResult.OK)
                {
                    textBoxServerGenJsonPath.Text = folderDlg.SelectedPath;
                }
            }
        }

        private void buttonSelectClientPath_Click(object sender, EventArgs e)
        {
            using (FolderBrowserDialog folderDlg = new FolderBrowserDialog())
            {
                folderDlg.Description = @"选择客户端代码保存目录";
                if (folderDlg.ShowDialog() == DialogResult.OK)
                {
                    textBoxClientGenPath.Text = folderDlg.SelectedPath;
                }
            }
        }

        private void buttonSelectServerPath_Click(object sender, EventArgs e)
        {
            using (FolderBrowserDialog folderDlg = new FolderBrowserDialog())
            {
                folderDlg.Description = @"选择服务端代码保存目录";
                if (folderDlg.ShowDialog() == DialogResult.OK)
                {
                    textBoxServerGenPath.Text = folderDlg.SelectedPath;
                }
            }
        }

        // 添加保存和加载配置的方法
        private void SaveConfig()
        {
            var config = new AppConfig
            {
                ExcelPath = textBoxExcelPath.Text,
                ClientPath = textBoxClientGenPath.Text,
                ClientJsonPath = textBoxClientGenJsonPath.Text,
                ServerPath = textBoxServerGenPath.Text,
                ServerJsonPath = textBoxServerGenJsonPath.Text,
                GenClient = checkBoxGenClient.Checked,
                GenServer = checkBoxGenServer.Checked
            };
            App.Config = config;
            try
            {
                string json = JsonSerializer.Serialize(config, new JsonSerializerOptions { WriteIndented = true });
                File.WriteAllText(configPath, json);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存配置失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void LoadConfig()
        {
            if (!File.Exists(configPath)) return;

            try
            {
                string json = File.ReadAllText(configPath);
                var config = JsonSerializer.Deserialize<AppConfig>(json);

                if (config != null)
                {
                    App.Config = config;
                    textBoxExcelPath.Text = config.ExcelPath ?? "";
                    textBoxClientGenPath.Text = config.ClientPath ?? "";
                    textBoxServerGenPath.Text = config.ServerPath ?? "";
                    checkBoxGenClient.Checked = config.GenClient;
                    checkBoxGenServer.Checked = config.GenServer;
                    textBoxClientGenJsonPath.Text = config.ClientJsonPath ?? "";
                    textBoxServerGenJsonPath.Text = config.ServerJsonPath ?? "";
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载配置失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void checkBoxGenServer_CheckedChanged(object sender, EventArgs e)
        {

        }
    }
}