using DevExpress.XtraBars.ToolbarForm;
using DevExpress.XtraEditors;
using DeviceRepair.Models;
using DeviceRepairAndOptimization.Biz;
using DeviceRepairAndOptimization.Common;
using DeviceRepairAndOptimization.Pages.CustomField;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Windows.Forms;

namespace DeviceRepairAndOptimization.Pages.Maintain
{
    public partial class dlgAccessoriesLst : ToolbarForm
    {
        FieldsInfo CurrentFieldModel = null;
        int m_SelectedCurrentRowIndex = 0;

        List<FieldsInfo> CurrentDatas = null;
        public DeviceWarrantyRequestAccessoriesInfo CurrentAccessories = null;

        string FilterString
        {
            get { return buttonEdit1.Text.Trim(); }
        }

        public dlgAccessoriesLst()
        {
            InitializeComponent();

            this.Load += DlgAccessoriesLst_Load;
        }

        /// <summary>
        /// 窗体加载完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="evt"></param>
        private void DlgAccessoriesLst_Load(object sender, EventArgs evt)
        {
            InitializeGridViewStyle();
            InitializeGridDatas();
        }

        /// <summary>
        /// 初始化表格样式
        /// </summary>
        void InitializeGridViewStyle()
        {
            /// 自增长行号
            gridView1.CustomDrawRowIndicator += (s, e) =>
            {
                if (e.Info.IsRowIndicator && e.RowHandle >= 0)
                {
                    e.Info.DisplayText = (e.RowHandle + 1).ToString();
                    e.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
                    e.Appearance.TextOptions.VAlignment = DevExpress.Utils.VertAlignment.Center;
                }
            };

            /// 修改字段标题
            gridView1.CustomDrawColumnHeader += (s, e) =>
            {
                if (e.Column != null && e.Column.Caption == "Selection")
                    e.Info.Caption = "选择";
            };

            /// 单元格点击
            gridView1.RowCellClick += (s, e) =>
            {
                if (e.Button == MouseButtons.Right)
                {
                    e.Handled = true;
                    return;
                }

                if (e.Column.Caption == "Selection")
                {
                    if (this.m_SelectedCurrentRowIndex == e.RowHandle && this.gridView1.IsRowSelected(e.RowHandle))
                        this.gridView1.UnselectRow(e.RowHandle);
                }
            };

            /// 表格选中行更改
            gridView1.FocusedRowChanged += (s, e) =>
            {
                try
                {
                    if (e.FocusedRowHandle >= 0)
                    {
                        m_SelectedCurrentRowIndex = e.FocusedRowHandle;
                        CurrentFieldModel = gridView1.GetRow(e.FocusedRowHandle) as FieldsInfo;

                        #region 修改选定状态
                        if (gridView1.SelectedRowsCount > 0)
                        {
                            for (int i = 0; i < this.gridView1.RowCount; i++)
                            {
                                if (this.gridView1.IsRowSelected(i) && this.gridView1.FocusedRowHandle.ToString().Equals(i.ToString()) == false)
                                {
                                    this.gridView1.UnselectRow(i);
                                }
                            }
                        }

                        this.gridView1.SelectRow(e.FocusedRowHandle);
                        #endregion
                    }
                    else
                    {
                        CurrentFieldModel = null;
                    }
                }
                catch (Exception ex)
                {
                    XtraMessageBoxHelper.Error(ex.Message);
                }
            };

            gridView1.OptionsBehavior.Editable = false;
            gridView1.OptionsBehavior.ReadOnly = true;

            gridView1.OptionsSelection.EnableAppearanceFocusedCell = false;
            gridView1.OptionsScrollAnnotations.ShowSelectedRows = DevExpress.Utils.DefaultBoolean.False;

            gridView1.OptionsSelection.MultiSelect = true;
            gridView1.OptionsSelection.MultiSelectMode = DevExpress.XtraGrid.Views.Grid.GridMultiSelectMode.CheckBoxRowSelect;

            foreach (DevExpress.XtraGrid.Columns.GridColumn item in gridView1.Columns)
            {
                item.OptionsColumn.AllowEdit = false;
                item.OptionsColumn.AllowGroup = DevExpress.Utils.DefaultBoolean.True;
                item.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;
                item.OptionsColumn.AllowShowHide = false;
            }

        }

        /// <summary>
        /// 数据加载
        /// </summary>
        void InitializeGridDatas()
        {
            try
            {
                splashScreenManager1.ShowWaitForm();

                APIResponseData apiResponseData = FieldsManager.Instance.GetQuery("Accessories");
                if (!apiResponseData.IsSuccess)
                    throw new Exception(apiResponseData.Message);

                CurrentDatas = apiResponseData.ToDeserializeObject<List<FieldsInfo>>();

                foreach (var item in CurrentDatas)
                {
                    //item.FieldTypeCaption = FieldsTypeCollect.FirstOrDefault(x => x.TypeValue == item.FieldType).Name;
                    item.StatusText = item.Status ? "启用" : "停用";
                    //item.CreatorName = UserMapping[item.CreatBy];
                    //if (item.ModifyBy.HasValue)
                    //    item.ModifierName = UserMapping[item.ModifyBy.Value];
                }

                gridControl1.DataSource = gridControl1.DataSource = CurrentDatas.Where(x => x.FieldText.Contains(FilterString)
|| x.FieldValue.Contains(FilterString)).ToList();
                gridView1.BestFitColumns();
                splashScreenManager1.TryCloseWait();
            }
            catch (Exception ex)
            {
                splashScreenManager1.TryCloseWait();
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }


        /// <summary>
        /// 搜索
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            InitializeGridDatas();
        }

        private void buttonEdit1_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            InitializeGridDatas();
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                CurrentAccessories = null;
                int result = XtraInputBox.Show<int>("请输入配件的数量：", "配件添加", 0);
                if (result > 0)
                {
                    CurrentAccessories = new DeviceWarrantyRequestAccessoriesInfo
                    {
                        AccessoriesCount = result,
                        FieldID = CurrentFieldModel.AutoID,
                        FieldName = CurrentFieldModel.FieldText,
                        FieldValue = CurrentFieldModel.FieldValue,
                    };
                    DialogResult = DialogResult.OK;
                }
            }
            catch (Exception ex)
            {
                string Error = ex.Message;
                if (Error.Equals("值对于 Int32 太大或太小。"))
                    Error = "输入的数量值 太大或太小，请检查！";

                XtraMessageBoxHelper.Error(Error);
            }

        }

        /// <summary>
        /// 按下回车 搜索
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonEdit1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)Keys.Enter)
            {
                InitializeGridDatas();
            }
        }

        /// <summary>
        /// 新增配件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            try
            {
                if (!GlobalInfo.HasRole("BIZ_FIELD_ACCESSORIES_ADD"))
                {
                    throw new Exception($"当前账号缺少此操作的权限");
                }

                pageFieldEdit view = new pageFieldEdit("Accessories");

                DialogResult Dr = view.ShowDialog();
                if (Dr == DialogResult.OK)
                {
                    InitializeGridDatas();
                }
                else if (Dr == DialogResult.Abort)
                {
                    throw new Exception(view.ErrorMsg);
                }
                else
                {
                    InitializeGridDatas();
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }
    }
}