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;

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

            this.DataContextChanged += OnDataContextChanged;
        }

        /// <summary>
        /// 是否处于初始化中
        /// </summary>
        private bool isInInited;

        private void OnDataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
        {
            DevExpress.Xpf.Grid.EditGridCellData cellData = e.NewValue as DevExpress.Xpf.Grid.EditGridCellData;

            int.TryParse(cellData?.Value?.ToString(), out int value);

            this.isInInited = true;
            this.PART_Text.EditValue = string.Format("{0:d4}", value);
            this.isInInited = false;
        }

        /// <summary>
        /// 值改变
        /// </summary>
        private void EditValueChanged(object sender, DevExpress.Xpf.Editors.EditValueChangedEventArgs e)
        {
            if (this.isInInited)
                return;

            DevExpress.Xpf.Grid.EditGridCellData cellData = this.DataContext as DevExpress.Xpf.Grid.EditGridCellData;

            PageModel page = cellData.Row as PageModel;
            if (page == null)
                return;

            int.TryParse(e.NewValue?.ToString(), out int newNum);

            if (page.PageNum == newNum)
                return;

            IPageGroupService service = ApplicationDomainEx.ServiceManager.GetService<IPageGroupService>(ViewServiceKeys.PAGE_GROUP_SERVICE);
            if (service == null)
                return;

            if (service.TryChangePageNum(page, newNum))
            {
                page.PageNum = newNum;
            }
        }
    }
}
