using DeviceRepair.Models;
using DeviceRepair.Models.Device;
using DeviceRepairAndOptimization.Biz;
using DeviceRepairAndOptimization.Common;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace DeviceRepairAndOptimization.Pages.AM.DeviceTreeView
{
    public partial class pageAmDeviceTreeView : FormBase
    {
        private List<DeviceInformationInfoTree> RawData;

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

        public pageAmDeviceTreeView()
        {
            InitializeComponent();

            this.Load += PageAmDeviceTreeView_Load;
        }

        private void PageAmDeviceTreeView_Load(object sender, EventArgs e)
        {
            layoutControl1.AllowCustomization = false;
            GridDataBind();
        }

        void GridDataBind()
        {
            try
            {
                splashScreenManager1.ShowWaitForm();
                APIResponseData apiResponseData = DeviceManager.Instance.GetDeviceTreeDatas(FilterString, "OEM");
                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 EditSearch_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            GridDataBind();
        }

        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, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)ConsoleKey.Enter)
            {
                GridDataBind();
            }
        }
    }
}
