using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using VIZ.Package.Domain;
using VIZ.Package.Service;

namespace VIZ.Package.Module
{
    /// <summary>
    /// IntegerListCellEdit.xaml 的交互逻辑
    /// </summary>
    public partial class IntegerListCellEdit : ListCellEditBase
    {
        public IntegerListCellEdit()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 数据上下文改变时触发
        /// </summary>
        /// <param name="e">事件参数</param>
        protected override void OnDataContextChanged(DependencyPropertyChangedEventArgs e)
        {
            DevExpress.Xpf.Grid.EditGridCellData cellData = e.NewValue as DevExpress.Xpf.Grid.EditGridCellData;

            this.IsSendToPreview = false;
            int.TryParse(cellData?.Value?.ToString(), out int value);
            this.PART_Text.EditValue = value;
            this.IsSendToPreview = true;
        }

        /// <summary>
        /// 值改变时触发
        /// </summary>
        private void EditValueChanged(object sender, DevExpress.Xpf.Editors.EditValueChangedEventArgs e)
        {
            // 是否需要发送至预览
            if (!this.IsSendToPreview)
                return;

            // 预览连接不存在
            if (ApplicationDomainEx.PreviewConn == null)
                return;

            DevExpress.Xpf.Grid.EditGridCellData cellData = this.DataContext as DevExpress.Xpf.Grid.EditGridCellData;
            if (cellData == null)
                return;

            GridColumnControlFieldDefinition columnDefinition = cellData.Column.DataContext as GridColumnControlFieldDefinition;
            if (columnDefinition == null)
                return;

            // 设置值
            IDictionary<string, object> dic = cellData.Row as IDictionary<string, object>;
            dic[columnDefinition.FieldName] = e.NewValue?.ToString() ?? string.Empty;

            // 向Viz发送指令
            this.VizCommandControlObjectService.SetControlObjectListValue(
                ApplicationDomainEx.PreviewConn,
                columnDefinition.ControlObject.TreeNodePath,
                columnDefinition.ControlField.FieldIdentifier,
                cellData.RowData.RowHandle.Value,
                columnDefinition.FieldName,
                e.NewValue?.ToString());
        }
    }
}
