using KGIS.Framework.DBOperator;
using KGIS.Framework.Maps;
using KGIS.Framework.Utils;
using KGIS.Framework.Utils.Helper;
using Kingo.Plugin.DataDictionary.Helper;
using Kingo.PluginServiceInterface;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SQLite;
using System.IO;
using System.Windows;
namespace Kingo.Plugin.DataDictionary.Views
{
    /// 
    /// FrmDicManagerExport.xaml 的交互逻辑
    /// 
    public partial class FrmDicManageExport : BaseWindow
    {
        public FrmDicManageExport()
        {
            InitializeComponent();
        }
        private void btnBrowse_Click_1(object sender, RoutedEventArgs e)
        {
            System.Windows.Forms.SaveFileDialog dialog = new System.Windows.Forms.SaveFileDialog();
            dialog.DefaultExt = "kzd";
            dialog.Filter = "字典文件|*.kzd|Excel文件|*.xlsx";
            //dialog.Filter = "kzd文件(*.kzd)|*.kzd;Excel Files(*.xlsx)|*.xlsx";
            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                this.txtPath.Text = dialog.FileName;
            }
        }
        private void btnExport_Click_1(object sender, RoutedEventArgs e)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(txtPath.Text))
                {
                    MessageHelper.Show("未获取到文件路径!");
                    return;
                }
                string path = txtPath.Text;
                if (File.Exists(path))
                {
                    var result = MessageHelper.ShowYesNoAndTips("文件已存在,是否覆盖?");
                    if (result == System.Windows.Forms.DialogResult.No)
                    {
                        return;
                    }
                }
                if (path.Contains(".xlsx"))
                {
                    ExportOwnerUnitCode exportOwnerUnitCode = new ExportOwnerUnitCode();
                    exportOwnerUnitCode.OutPath = path;
                    exportOwnerUnitCode.Export();
                }
                else if (path.Contains(".kzd"))
                {
                    string dbPath = null;
                    if ((MapsManager.Instance.CurrProjectInfo as ProjectInfo) is ProjectInfo)
                    {
                        dbPath = ((MapsManager.Instance.CurrProjectInfo as ProjectInfo) as ProjectInfo).GetDicDataPath();
                    }
                    File.Copy(dbPath, path, true);
                    //创建数据库连接
                    IRDBHelper dbHelper = RDBFactory.CreateDbHelper(path, DatabaseType.SQLite);
                    List tables = GetTableNames(path);
                    List views = GetViewNames(path);
                    try
                    {
                        //表
                        for (int i = 0; i < tables.Count; i++)
                        {
                            if (tables[i].Contains("Sys_DicDetail") || tables[i].Contains("Sys_DicManage") || tables[i].Contains("Sys_DicMappingTable") || tables[i].Contains("Sys_DicType") || tables[i].Contains("sqlite_sequence")/*系统自动增量键的表*/)
                            {
                                dbHelper.ExecuteDatatable(tables[i], $"delete from  {tables[i]}", false);
                                continue;
                            }
                            dbHelper.ExecuteDatatable(tables[i], $"Drop table {tables[i]}", false);
                        }
                        //视图文件
                        for (int j = 0; j < views.Count; j++)
                        {
                            dbHelper.ExecuteDatatable(views[j], $"Drop view {views[j]}", false);
                        }
                        //DropSQLiteView(path, views);
                    }
                    catch
                    {
                    }
                    finally
                    {
                        if (dbHelper != null && dbHelper.State != System.Data.ConnectionState.Closed)
                            dbHelper.DisConnect();
                    }
                    UpdateTable(dbPath, path);
                }
                MessageHelper.Show("字典导出已完成!");
                this.Close();
            }
            catch (Exception ex)
            {
                MessageHelper.ShowError("导出数据字典异常:" + ex.Message);
            }
        }
        private List GetTableNames(string path)
        {
            // 获取指定数据库中的所有表名
            List tables = new List();
            //string connectionString = @"Data Source='" + path + "';Version=3;";
            using (SQLiteConnection conn = new SQLiteConnection("Data Source=" + path))
            {
                conn.Open();
                // 获取数据库中的所有表名
                string sqlTableNames = "select name from sqlite_master where type='table' order by name;";
                // 创建命令对象
                SQLiteCommand cmd = new SQLiteCommand(sqlTableNames, conn);
                using (SQLiteDataReader dr = cmd.ExecuteReader())
                {
                    while (dr.Read())
                    {
                        // 表名
                        tables.Add(dr["Name"].ToString());
                    }
                }
            }
            return tables;
        }
        private void UpdateTable(string path, string tagrtPath)
        {
            List tableName = new List();
            tableName.Add("Sys_DicDetail");
            tableName.Add("Sys_DicManage");
            tableName.Add("Sys_DicMappingTable");
            tableName.Add("Sys_DicType");
            IRDBHelper kzdHelper = RDBFactory.CreateDbHelper(path, DatabaseType.SQLite);
            try
            {
                for (int i = 0; i < tableName.Count; i++)
                {
                    DataTable dtRST = kzdHelper.ExecuteDatatable(tableName[i], $"SELECT * FROM {tableName[i]}", false);
                    DataTableToSQLite myTabInfo1 = new DataTableToSQLite(dtRST, path, false);
                    myTabInfo1.ImportToSqliteBatch(dtRST, tagrtPath);
                }
            }
            catch (Exception ex)
            {
                LogAPI.Debug(ex);
                return;
            }
            finally
            {
                if (kzdHelper != null && kzdHelper.State != System.Data.ConnectionState.Closed)
                    kzdHelper.DisConnect();
            }
        }
        private List GetViewNames(string path)
        {
            // 获取指定数据库中的所有视图名
            List views = new List();
            //string connectionString = @"Data Source='" + path + "';Version=3;";
            using (SQLiteConnection conn = new SQLiteConnection("Data Source=" + path))
            {
                conn.Open();
                // 获取数据库中的所有视图名
                string sqlViewNames = "select name from sqlite_master where type='view' order by name";
                // 创建命令对象
                SQLiteCommand cmd = new SQLiteCommand(sqlViewNames, conn);
                using (SQLiteDataReader dr = cmd.ExecuteReader())
                {
                    while (dr.Read())
                    {
                        // 表名
                        views.Add(dr["Name"].ToString());
                    }
                }
            }
            return views;
        }
        private void DropSQLiteView(string dbPath, List viewsSql)
        {
            try
            {
                using (System.Data.SQLite.SQLiteConnection conn = new System.Data.SQLite.SQLiteConnection("Data Source=" + dbPath))
                {
                    conn.Open();
                    using (System.Data.SQLite.SQLiteTransaction pTrans = conn.BeginTransaction())
                    {
                        using (System.Data.SQLite.SQLiteCommand cmd = new System.Data.SQLite.SQLiteCommand(conn))
                        {
                            for (int i = 0; i < viewsSql.Count; i++)
                            {
                                cmd.CommandText = $"drop view {viewsSql[i]};";
                                cmd.ExecuteNonQuery();
                            }
                            pTrans.Commit();
                        }
                    }
                    conn.Close();
                }
            }
            catch (Exception ex)
            {
                LogAPI.Debug("删除视图文件(地址:" + dbPath + ") 执行失败,异常原因: " + ex + " ; ");
                return;
            }
        }
    }
}