using DevExpress.XtraBars.ToolbarForm;
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using TsSFCDeivceClient.Common;
using TsSFCDeivceClient.Model;
using TsSFCDeivceClient.Model.DeviceWarrantyRequest;

namespace TsSFCDeivceClient
{
    public partial class pageDeivceView : ToolbarForm
    {
        int m_SelectedCurrentRowIndex = 0;

        public DeviceInfo CurrentDeviceInfo = null;
        System.Configuration.Configuration m_Config = System.Configuration.ConfigurationManager.OpenExeConfiguration(System.Configuration.ConfigurationUserLevel.None);
        string ServiceUrl
        {
            get
            {
                return m_Config.AppSettings.Settings["ServiceApiUrl"].Value.Trim();
            }
        }

        string FilterString
        {
            get { return txt_Filter.EditValue?.ToString()?.Trim(); }
        }

        public pageDeivceView()
        {
            InitializeComponent();
            this.Load += PageDeivceView_Load;
        }

        private void PageDeivceView_Load(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(ServiceUrl))
            {
                XtraMessageBoxHelper.Error($"缺少配置字段（设备管理软件接口地址）【ServiceApiUrl】。");
                this.Close();
            }

            InitializeGridViewStyle();
            InitializeGridDatas();
        }

        void InitializeGridDatas()
        {
            try
            {
                splashScreenManager1.ShowWaitForm();
                APIResponseData apiResponseData = Biz.HttpHelper.Instance.Get($"{ServiceUrl}{DeviceApiUrlConstValue.GetDeviceDatas}?FilterString={FilterString}");

                if (!apiResponseData.IsSuccess)
                    throw new Exception(apiResponseData.Message);

                List<DeviceInfo> lst = apiResponseData.ToDeserializeObject<List<DeviceInfo>>();

                CloseWaitForm();
                gridControl1.DataSource = lst;
                gridView1.BestFitColumns();
                if (lst.Count > 0)
                { CurrentDeviceInfo = lst[0]; gridView1.SelectRow(0); }
            }
            catch (Exception ex)
            {
                CloseWaitForm();
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        /// <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;
                        CurrentDeviceInfo = gridView1.GetRow(e.FocusedRowHandle) as DeviceInfo;

                        #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
                    {
                        CurrentDeviceInfo = null;
                    }
                }
                catch (Exception ex)
                {
                    XtraMessageBoxHelper.Error(ex.Message);
                }
            };

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

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

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

            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;
            }

        }

        private void CloseWaitForm()
        {
            try
            {
                if (splashScreenManager1.IsSplashFormVisible)
                {
                    splashScreenManager1.CloseWaitForm();
                }
                Cursor.Current = Cursors.Default;
            }
            catch (Exception ex)
            {
                //m_log.Error(ex.Message, ex);
            }
        }

        private void barButtonItem2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (CurrentDeviceInfo == null)
            {
                XtraMessageBoxHelper.Info("请选择停机的设备！");
                return;
            }

            this.DialogResult = DialogResult.OK;
        }

        private void btn_Search_Click(object sender, EventArgs e)
        {
            InitializeGridDatas();
        }
    }
}