using KGIS.Framework.DBOperator;
using KGIS.Framework.Maps;
using KGIS.Framework.Utils;
using KGIS.Framework.Utils.Helper;
using Kingo.PluginServiceInterface;
using System;
using System.Data;
using System.Windows;
using System.Windows.Input;
namespace Kingo.Plugin.DataDictionary.Views
{
    /// 
    /// DataDicEdit.xaml 的交互逻辑
    /// 
    public partial class DataDicEdit : BaseWindow
    {
        //判断是父节点还是子节点的编辑
        public bool IsParent { get; set; }
        /// 
        /// 保存当前选择节点
        /// 
        int IndesStrs = 0;//父节点编辑0
        //DataTable MpTable = null;
        /// 
        /// 父节点新增节点后保存状态
        /// 
        public Action actionUpdate;
        /// 
        /// 
        /// 
        /// 
        /// true:编辑  false:新增
        public DataDicEdit(int IndesStr = 0, bool IsEdit = false)
        {
            InitializeComponent();
            IRDBHelper rdbHelper = null;
            try
            {
                IndesStrs = IndesStr;
                string dbPath = null;
                if ((MapsManager.Instance.CurrProjectInfo as ProjectInfo) is ProjectInfo)
                {
                    dbPath = ((MapsManager.Instance.CurrProjectInfo as ProjectInfo) as ProjectInfo).GetDicDataPath();
                }
                if (string.IsNullOrWhiteSpace(dbPath))
                {
                    throw new Exception("数据库连接字符串为空!");
                }
                rdbHelper = RDBFactory.CreateDbHelper("Data Source=" + dbPath, DatabaseType.SQLite);
                if (rdbHelper == null)
                {
                    throw new Exception("数据库连接打开失败!");
                }
                DataTable dtCat = rdbHelper.ExecuteDatatable("Sys_DicType", "select * from Sys_DicType  order by paixu", true);
                if (dtCat == null || dtCat.Rows.Count <= 0)
                {
                    return;
                }
                if (!IsEdit)
                {
                    DataRow dr = dtCat.NewRow();
                    dr["ID"] = "0";
                    dr["NAME"] = "请选择";
                    dtCat.Rows.InsertAt(dr, 0);
                }
                ddlType.DisplayMemberPath = "NAME";
                ddlType.SelectedValuePath = "ID";
                ddlType.ItemsSource = dtCat.DefaultView;
                ddlType.SelectedIndex = 0;
                //判断当前选择节点,未选中则默认选择请选择项
                if (IndesStrs > 0)
                {
                    ddlType.SelectedIndex = IndesStrs;
                }
                //if (IndesStrs != 0)
                //{
                //    ddlType.SelectedIndex = IndesStrs;
                //}
                //else
                //{
                //    ddlType.SelectedIndex = 0;
                //}
            }
            catch (Exception ex)
            {
                //记录日志
                LogAPI.Debug(ex);
                MessageHelper.ShowError(ex.Message);
            }
            finally
            {
                if (rdbHelper != null)
                {
                    rdbHelper.DisConnect();
                }
            }
        }
        //页面数据初始
        public void InitPage(DataRow dtBGXM)
        {
            this.Title = "编辑字典";
            //绑定数据源
            this.DataContext = dtBGXM;
            if (IsParent)
            {
                ddlType.SelectedValue = 0;
                ddlType.IsEnabled = false;
            }
            else
            {
                //给控件赋值
                ddlType.SelectedValue = dtBGXM["TYPE"];
            }
        }
        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            IRDBHelper rdbHelper = null;
            try
            {
                string dbPath = (MapsManager.Instance.CurrProjectInfo as ProjectInfo).GetDicDataPath();
                if (string.IsNullOrWhiteSpace(dbPath))
                {
                    throw new Exception("数据库连接字符串为空!");
                }
                rdbHelper = RDBFactory.CreateDbHelper("Data Source=" + dbPath, DatabaseType.SQLite);
                if (rdbHelper == null)
                {
                    throw new Exception("数据库连接打开失败!");
                }
                int tmp;
                if (!int.TryParse(txtPaixu.Text, out tmp))
                {
                    throw new Exception("排序文本框,请正确输入数字!");
                }
                DataTable NewlyAdded = null;
                //新增数据
                if (this.DataContext == null)
                {
                    string strType = ddlType.SelectedValue.ToString();
                    string strSql = string.Format("insert into Sys_DicManage (NAME,ALIASNAME,TYPE,REMARK,PAIXU) VALUES ('{0}','{1}','{2}','{3}',{4})", txtName.Text, txtAliasName.Text, ddlType.SelectedValue, txtRemark.Text, Convert.ToInt32(txtPaixu.Text));
                    string NewLyAddSql = string.Format("SELECT * FROM Sys_DicManage WHERE NAME ='{0}' AND  ALIASNAME='{1}' AND  TYPE ={2} AND REMARK='{3}'", txtName.Text, txtAliasName.Text, ddlType.SelectedValue, txtRemark.Text);
                    if (strType == "0")
                    {
                        strSql = string.Format("insert into Sys_DicType (NAME,ALIASNAME,REMARK,PAIXU) VALUES ('{0}','{1}','{2}',{3})", txtName.Text, txtAliasName.Text, txtRemark.Text, Convert.ToInt32(txtPaixu.Text));
                        NewLyAddSql = string.Format("SELECT * FROM Sys_DicType WHERE NAME='{0}' AND ALIASNAME='{1}' AND  REMARK='{2}'", txtName.Text, txtAliasName.Text, txtRemark.Text);
                    }
                    int res = rdbHelper.ExecuteNonQuery(strSql, CommandType.Text);
                    if (res <= 0)
                    {
                        return;
                    }
                    NewlyAdded = rdbHelper.ExecuteDatatable("NewAdded", NewLyAddSql, false);
                    if (actionUpdate == null)
                    {
                        return;
                    }
                    DicTreeNode treeNodes = new DicTreeNode()
                    {
                        Name = txtName.Text,
                        IsExpanded = true,
                        Paixu = Convert.ToInt32(txtPaixu.Text)
                    };
                    if (NewlyAdded != null && NewlyAdded.Rows.Count > 0)
                    {
                        foreach (var item in NewlyAdded.Rows)
                        {
                            treeNodes.Data = item as DataRow;
                            break;
                        }
                    }
                    if (ddlType.SelectedIndex > 0)
                    {
                        treeNodes.IsParent = false;
                        treeNodes.Icon = "pack://application:,,,/KGIS.PlatformPlugin;component/Resources/zrz.png";
                        actionUpdate(false, treeNodes, ddlType.SelectedValue.ToString());
                    }
                    else
                    {
                        treeNodes.IsParent = true;
                        treeNodes.Icon = "pack://application:,,,/KGIS.PlatformPlugin;component/Resources/zrz.png";
                        actionUpdate(true, treeNodes, ddlType.SelectedValue.ToString());
                    }
                }
                else if (this.DataContext != null)//修改数据
                {
                    DataRow drv = this.DataContext as DataRow;
                    if (drv == null)
                    {
                        return;
                    }
                    drv["NAME"] = txtName.Text;
                    drv["ALIASNAME"] = txtAliasName.Text;
                    drv["REMARK"] = txtRemark.Text;
                    string strSql = string.Empty;
                    string NewLyAddSql = string.Empty;
                    //主窗体
                    if (IndesStrs == 0)//父节点编辑
                    {
                        if (IsParent)
                        {
                            strSql = string.Format("UPDATE Sys_DicType set NAME='{0}',ALIASNAME='{1}',REMARK='{2}' ,paixu={3} where id={4} ", txtName.Text, txtAliasName.Text, txtRemark.Text, Convert.ToInt32(txtPaixu.Text), drv["ID"]);
                            NewLyAddSql = string.Format("SELECT * FROM Sys_DicType WHERE NAME='{0}' AND ALIASNAME='{1}' AND  id={2} ", txtName.Text, txtAliasName.Text, drv["ID"]);
                        }
                        else
                        {
                            strSql = string.Format("UPDATE Sys_DicManage set NAME='{0}',ALIASNAME='{1}',TYPE='{2}',REMARK='{3}',paixu={4}  where id={5} ", txtName.Text, txtAliasName.Text, ddlType.SelectedValue, txtRemark.Text, Convert.ToInt32(txtPaixu.Text), drv["ID"]);
                            NewLyAddSql = string.Format("SELECT * FROM Sys_DicManage WHERE NAME ='{0}' AND  ALIASNAME='{1}' AND  TYPE ={2} AND REMARK='{3}' AND  id={4}", txtName.Text, txtAliasName.Text, ddlType.SelectedValue, txtRemark.Text, drv["ID"]);
                        }
                    }
                    else if (IndesStrs == 1)
                    {
                        if (IsParent)
                        {
                            strSql = string.Format("UPDATE Sys_DicManage set NAME='{0}',ALIASNAME='{1}',TYPE='{2}',REMARK='{3}'  where id={4} ", txtName.Text, txtAliasName.Text, ddlType.SelectedValue, txtRemark.Text, drv["ID"]);
                            NewLyAddSql = string.Format("SELECT * FROM Sys_DicManage WHERE NAME ='{0}' AND  ALIASNAME='{1}' AND  TYPE ={2} AND REMARK='{3}' AND  id={4}", txtName.Text, txtAliasName.Text, ddlType.SelectedValue, txtRemark.Text, drv["ID"]);
                        }
                        else
                        {
                            strSql = string.Format("UPDATE Sys_DicManage set NAME='{0}',ALIASNAME='{1}',TYPE='{2}',REMARK='{3}' where id={4} ", txtName.Text, txtAliasName.Text, ddlType.SelectedValue, txtRemark.Text, drv["ID"]);
                            NewLyAddSql = string.Format("SELECT * FROM Sys_DicManage WHERE NAME ='{0}' AND  ALIASNAME='{1}' AND  TYPE ={2} AND REMARK='{3}' AND  id={4}", txtName.Text, txtAliasName.Text, ddlType.SelectedValue, txtRemark.Text, drv["ID"]);
                        }
                    }
                    int res = rdbHelper.ExecuteNonQuery(strSql, CommandType.Text);
                    if (res < 0)
                    {
                        return;
                    }
                    NewlyAdded = rdbHelper.ExecuteDatatable("NewAdded", NewLyAddSql, false);
                    if (actionUpdate == null)
                    {
                        return;
                    }
                    DicTreeNode treeNodes = new DicTreeNode()
                    {
                        Name = txtName.Text,
                        IsExpanded = true,
                        Paixu = Convert.ToInt32(txtPaixu.Text)
                    };
                    if (NewlyAdded != null && NewlyAdded.Rows.Count > 0)
                    {
                        foreach (var item in NewlyAdded.Rows)
                        {
                            treeNodes.Data = item as DataRow;
                            break;
                        }
                    }
                    if (ddlType.SelectedIndex >= 0)
                    {
                        treeNodes.IsParent = false;
                        treeNodes.Icon = "pack://application:,,,/KGIS.PlatformPlugin;component/Resources/zrz.png";
                        actionUpdate(false, treeNodes, ddlType.SelectedValue.ToString());
                    }
                    else
                    {
                        treeNodes.IsParent = true;
                        treeNodes.Icon = "pack://application:,,,/KGIS.PlatformPlugin;component/Resources/zrz.png";
                        actionUpdate(true, treeNodes, ddlType.SelectedValue.ToString());
                    }
                }
                this.Close();
            }
            catch (Exception ex)
            {
                //记录日志
                LogAPI.Debug(ex);
                MessageHelper.ShowError(ex.Message);
            }
            finally
            {
                if (rdbHelper != null)
                {
                    rdbHelper.DisConnect();
                }
            }
        }
        // 取消按钮,直接关闭编辑框
        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = true;
            this.Close();
        }
        // 验证事件,非空验证   
        private void Validate(object sender, DevExpress.Xpf.Editors.ValidationEventArgs e)
        {
            if (e.Value != null)
            {
                if (e.Value is string)
                {
                    if (string.IsNullOrWhiteSpace(e.Value as string))
                    {
                        e.IsValid = false;
                        e.ErrorContent = "值不能为空";
                    }
                }
                else if (e.Value is float || e.Value is double || e.Value is Int32 || e.Value is decimal)
                {
                    double db = Convert.ToDouble(e.Value);
                    if (db == 0)
                    {
                        e.IsValid = false;
                        e.ErrorContent = "值不能为0";
                    }
                }
            }
            else
            {
                e.IsValid = false;
                e.ErrorContent = "值不能为空";
            }
            // MessageBox.Show("我是验证事件ain");
        }
        //private void btnAddMapping_ClickEvent(object sender, MouseButtonEventArgs e)
        //{
        //    if (MpTable != null)
        //    {
        //        FrmAddDicMapping AddDicMapping = new FrmAddDicMapping();
        //        if (AddDicMapping.ShowInMainWindow(true) == true)
        //        {
        //            DicMappingTable DMT = AddDicMapping.GetData();
        //            DataRow dr = MpTable.NewRow();
        //            dr["FieldName"] = DMT.FieldName;
        //            dr["TableName"] = DMT.TableName;
        //            dr["DicName"] = (this.DataContext as DataRow)["ALIASNAME"];
        //            MpTable.Rows.Add(dr);
        //            dgMapping.ItemsSource = MpTable.DefaultView;
        //        }
        //    }
        //}
        //private void btnDelMapping_ClickEvent(object sender, MouseButtonEventArgs e)
        //{
        //    if (MpTable != null)
        //    {
        //        if (dgMapping.SelectedIndex == -1)
        //        {
        //            MessageHelper.Show("请选择要删除的项!");
        //        }
        //        else
        //        {
        //            DataRow dr = MpTable.Rows[dgMapping.SelectedIndex];
        //            CommonAPI.SetFieldDomainToNull(dr["TABLENAME"].ToString(), dr["FIELDNAME"].ToString());
        //            dr.Delete();
        //        }
        //    }
        //}
    }
}