using DeviceRepair.Models;
using DeviceRepair.Models.Device;
using DeviceRepairAndOptimization.Biz;
using DeviceRepairAndOptimization.Common;
using System;
using System.Collections.Generic;

namespace DeviceRepairAndOptimization.Pages.Maintenance
{
    public partial class page_DriveTypeTree : FormBase
    {
        private List<DeviceInformationInfoTree> RawData;

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

        public page_DriveTypeTree()
        {
            InitializeComponent();

            this.Load += Page_DriveTypeTree_Load;
        }

        private void Page_DriveTypeTree_Load(object sender, EventArgs e)
        {
            GridDataBind();
        }

        /// <summary>
        /// 搜索
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void EditSearch_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            GridDataBind();
        }

        void GridDataBind()
        {
            try
            {
                splashScreenManager1.ShowWaitForm();
                APIResponseData apiResponseData = DeviceManager.Instance.GetDeviceTreeDatas(FilterString, "KH");
                if (apiResponseData.Code != 1)
                    throw new Exception(apiResponseData.Message);

                RawData = apiResponseData.ToDeserializeObject<List<DeviceInformationInfoTree>>();
                tvDevices.DataSource = RawData;
                tvDevices.KeyFieldName = "RouteAutoId";
                tvDevices.ParentFieldName = "ParentRouteId";
                tvDevices.ExpandAll();
                tvDevices.BestFitColumns();
                splashScreenManager1.TryCloseWait();
            }
            catch (Exception ex)
            {
                splashScreenManager1.TryCloseWait();
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        private void tvDevices_CustomColumnDisplayText(object sender, DevExpress.XtraTreeList.CustomColumnDisplayTextEventArgs e)
        {
            if (e.Column.FieldName == "EquipmentStatus")
            {
                int status;
                if (int.TryParse(e.Value + "", out status) && status > 0)
                {
                    e.DisplayText = "启用";
                }
                else
                {
                    if ((e?.Node?.HasChildren ?? false))
                        e.DisplayText = "";
                    else
                        e.DisplayText = "停用";
                }
            }
        }

        private void EditSearch_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)ConsoleKey.Enter)
            {
                GridDataBind();
            }
        }
    }
}
