using System;
using System.Data;
using System.Windows;
using KGIS.Framework.DBOperator;
using KGIS.Framework.Maps;
using KGIS.Framework.Utils;
using KGIS.Framework.Utils.Helper;
using Kingo.PluginServiceInterface;
namespace Kingo.Plugin.DataDictionary.Views
{
    /// 
    /// DataDicDetailEdit.xaml 的交互逻辑
    /// 
    public partial class DataDicDetailEdit : BaseWindow
    {
        private string dbPath = null;
        /// 
        /// 父级节点ID
        /// 
        public string OWNERDIC { get; set; }
        /// 
        /// TreeNode信息
        /// 
        public DataRow DrvNode { get; set; }
        /// 
        /// 保存当前修改后节点
        /// 
        public Action ActionChecked;
        //初始化
        public DataDicDetailEdit(string parentName = null)
        {
            InitializeComponent();
            if ((MapsManager.Instance.CurrProjectInfo as ProjectInfo) is ProjectInfo)
            {
                dbPath = ((MapsManager.Instance.CurrProjectInfo as ProjectInfo) as ProjectInfo).GetDicDataPath();
            }
            if (!string.IsNullOrWhiteSpace(parentName))
            {
                ParentName.Text = parentName;
            }
        }
        //保存
        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            int tmp;
            if (!int.TryParse(txtPaixu.Text, out tmp))
            {
                MessageHelper.Show("排序文本框,请正确输入数字。");
                return;
            }
            if (string.IsNullOrWhiteSpace(dbPath))
                return;
            IRDBHelper rdbHelper = RDBFactory.CreateDbHelper("Data Source=" + dbPath, DatabaseType.SQLite);
            try
            {
                //新增数据
                if (this.DataContext == null)
                {
                    //验证Code是否已经存在,如果存在则提醒
                    string strChecksql = string.Format("select * from Sys_DicDetail where OWNERDIC='{0}' and CODE='{1}'", OWNERDIC, txtCode.Text.Trim());
                    DataTable dtCheck = rdbHelper.ExecuteDatatable("Sys_DicDetail", strChecksql, false);
                    if (dtCheck.Rows.Count > 0)
                    {
                        txtCode.Focus();
                        MessageHelper.Show("您输入的字典编码已存在,请重新填写!");
                        return;
                    }
                    string strSql = string.Format("insert into Sys_DicDetail (PID,NAME,CODE,OWNERDIC,REMARK,PAIXU)" +
                    "VALUES ('{0}','{1}','{2}','{3}','{4}',{5})", ParentID.Text, txtName.Text.Trim(), txtCode.Text.Trim(), OWNERDIC, txtRemark.Text.Trim(), Convert.ToInt32(txtPaixu.Text));
                    int res = rdbHelper.ExecuteNonQuery(strSql, CommandType.Text);
                    DataTable dtChecks = rdbHelper.ExecuteDatatable("Sys_DicD", strChecksql, false);
                    if (res > 0)
                    {
                        if (ActionChecked != null)
                        {
                            DicTreeNode treeNodes = new DicTreeNode()
                            {
                                Name = "[" + txtCode.Text.Trim() + "]" + txtName.Text,
                                IsExpanded = true,
                                IsParent = true,
                                Paixu = Convert.ToInt32(txtPaixu.Text)
                            };
                            if (dtChecks != null && dtChecks.Rows.Count > 0)
                            {
                                foreach (var item in dtChecks.Rows)
                                {
                                    treeNodes.Data = item as DataRow;
                                    break;
                                }
                            }
                            if (ParentID.Text.Trim().ToString() == "")
                            {
                                treeNodes.IsParent = false;
                                treeNodes.Icon = "pack://application:,,,/KGIS.PlatformPlugin;component/Resources/zrz.png";
                                ActionChecked(false, treeNodes, "");
                            }
                            else
                            {
                                treeNodes.IsParent = false;
                                //    treeNodes.Icon = "pack://application:,,,/KGIS.Resource;component/Images/zrz.png";
                                treeNodes.Icon = "pack://application:,,,/KGIS.PlatformPlugin;component/Resources/zrz.png";
                                ActionChecked(false, treeNodes, ParentID.Text.Trim().ToString());
                            }
                        }
                        this.Close();
                    }
                }
                if (this.DataContext != null)
                {
                    DataRow drv = this.DataContext as DataRow;
                    //验证Code是否已经存在,如果存在则提醒
                    string strChecksql = string.Format("select * from Sys_DicDetail where OWNERDIC='{0}' and CODE='{1}' and ID <>{2}", OWNERDIC, txtCode.Text.Trim(), drv["ID"]);
                    DataTable dtCheck = rdbHelper.ExecuteDatatable("Sys_DicDetail", strChecksql, false);
                    //if (dtCheck.Rows.Count > 0)
                    //{
                    //    txtCode.Focus();
                    //    MessageHelper.Show("您输入的字典编码已存在,请重新填写!");
                    //    return;
                    //}
                    string strSql = string.Format("UPDATE Sys_DicDetail set NAME='{0}',CODE='{1}',PID='{2}',REMARK='{3}',PAIXU={4} " +
                " where id={5} ", txtName.Text.Trim(), txtCode.Text.Trim(), ParentID.Text, txtRemark.Text.Trim(), Convert.ToInt32(txtPaixu.Text), drv["ID"]);
                    int res = rdbHelper.ExecuteNonQuery(strSql, CommandType.Text);
                    strChecksql = string.Format("select * from Sys_DicDetail where OWNERDIC='{0}' and CODE='{1}' and ID={2}", OWNERDIC, txtCode.Text.Trim(), drv["ID"]);
                    DataTable dtChecks = rdbHelper.ExecuteDatatable("Sys_DicDeta", strChecksql, false);
                    if (res > 0)
                    {
                        if (ActionChecked != null)
                        {
                            DicTreeNode treeNodes = new DicTreeNode()
                            {
                                Name = "[" + txtCode.Text.Trim() + "]" + txtName.Text,
                                IsExpanded = true,
                                IsParent = true,
                                Paixu = Convert.ToInt32(txtPaixu.Text)
                            };
                            if (dtChecks != null && dtChecks.Rows.Count > 0)
                            {
                                foreach (var item in dtChecks.Rows)
                                {
                                    treeNodes.Data = item as DataRow;
                                    break;
                                }
                            }
                            if (ParentID.Text.Trim().ToString() == "")
                            {
                                treeNodes.IsParent = false;
                                treeNodes.Icon = "pack://application:,,,/KGIS.PlatformPlugin;component/Resources/zrz.png";
                                ActionChecked(false, treeNodes, "");
                            }
                            else
                            {
                                treeNodes.IsParent = false;
                                treeNodes.Icon = "pack://application:,,,/KGIS.PlatformPlugin;component/Resources/zrz.png";
                                ActionChecked(false, treeNodes, ParentID.Text.Trim().ToString());
                            }
                        }
                        this.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                //记录日志
                LogAPI.Debug(ex);
                MessageHelper.Show(ex.Message);
            }
            finally
            {
                //关闭数据库连接
                rdbHelper.DisConnect();
            }
        }
        // 取消按钮,直接关闭编辑框
        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            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");
        }
        //页面数据初始
        public void InitPage(DataRow dtBGXM)
        {
            if (string.IsNullOrWhiteSpace(dbPath))
                return;
            this.Title = "编辑字典";
            DataRow drNew = dtBGXM.Table.NewRow();
            drNew.ItemArray = dtBGXM.ItemArray;
            //绑定数据源
            this.DataContext = drNew;
            #region 查询父级名称代码
            //给控件赋值
            if (string.IsNullOrWhiteSpace(drNew["PID"].ToString()))
            {
                return;
            }
            IRDBHelper rdbHelper = RDBFactory.CreateDbHelper("Data Source=" + dbPath, DatabaseType.SQLite);
            try
            {
                string strSql = string.Format("select * from Sys_DicDetail where ID={0}", drNew["PID"]);
                DataTable dt = rdbHelper.ExecuteDatatable("Sys_DicDetail", strSql, false);
                if (dt.Rows.Count > 0)
                {
                    ParentName.Text = "[" + dt.Rows[0]["CODE"].ToString() + "]" + dt.Rows[0]["NAME"].ToString();
                    ParentID.Text = drNew["PID"].ToString();
                }
            }
            catch (Exception ex)
            {
                //记录日志
                LogAPI.Debug(ex);
                MessageHelper.ShowError(ex.Message);
            }
            finally
            {
                //关闭数据库连接
                rdbHelper.DisConnect();
            }
            #endregion
        }
        //选择按钮
        private void btnSelect_Click(object sender, RoutedEventArgs e)
        {
            DicHelpTree main = new DicHelpTree();
            main.OWNERDIC = OWNERDIC;
            main.GetValueHandler += GetValue;
            main.Width = 330;
            main.Height = 500;
            main.Left = 482;
            main.Top = 266;
            //编辑数据
            if (this.DataContext != null)
            {
                DataRow drv = this.DataContext as DataRow;
                main.MINEID = drv["ID"].ToString();
            }
            main.ShowInMainWindow(true);
        }
        //委托事件方法,给控件赋值
        private void GetValue(string sName, string sID)
        {
            ParentName.Text = sName;
            ParentID.Text = sID;
        }
        //加载事件
        private void BaseWindow_Loaded(object sender, RoutedEventArgs e)
        {
            if (DrvNode != null && !string.IsNullOrWhiteSpace(dbPath))
            {
                IRDBHelper rdbHelper = RDBFactory.CreateDbHelper("Data Source=" + dbPath, DatabaseType.SQLite);
                try
                {
                    string strSql = string.Format("select * from Sys_DicDetail where ID={0}", DrvNode["ID"]);
                    DataTable dt = rdbHelper.ExecuteDatatable("Sys_DicDetail", strSql, false);
                    if (dt.Rows.Count > 0)
                    {
                        ParentName.Text = "[" + dt.Rows[0]["CODE"].ToString() + "]" + dt.Rows[0]["NAME"].ToString();
                        ParentID.Text = DrvNode["ID"].ToString();
                    }
                }
                catch (Exception ex)
                {
                    //记录日志
                    LogAPI.Debug(ex);
                    MessageHelper.ShowError(ex.Message);
                }
                finally
                {
                    //关闭数据库连接
                    rdbHelper.DisConnect();
                }
            }
        }
    }
}