using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
using DevExpress.XtraBars;
using DeviceRepair.Models.Device;
using TsSFCDevice.Client.Biz.Base.Utils;
using DevExpress.XtraEditors;
using TsSFCDevice.Client.Biz.Impl;
using TsSFCDevice.Client.Launch.FormatProviderExtend;
using DeviceRepair.Models;

namespace TsSFCDevice.Client.Launch.Device
{
    public partial class pageDeviceTreeView : DevExpress.XtraBars.Ribbon.RibbonForm
    {
        #region 属性&字段

        /// <summary>
        /// 按钮图标
        /// </summary>
        Dictionary<string, Image> Icons = new Dictionary<string, Image>
        {
            { "Lock",DevExpress.Images.ImageResourceCache.Default.GetImageById(DevExpress.Images.DXImages.Cancel,DevExpress.Utils.Design.ImageSize.Size32x32,DevExpress.Utils.Design.ImageType.Colored) },
            { "UnLock",DevExpress.Images.ImageResourceCache.Default.GetImageById(DevExpress.Images.DXImages.Apply,DevExpress.Utils.Design.ImageSize.Size32x32,DevExpress.Utils.Design.ImageType.Colored) },
        };

        public IList<DeviceInformationInfoTree> Datas { get; set; }

        private DeviceInformationInfoTree m_CurrentModel;

        private string parEquipmentID { get { return baripsEquipmentID.EditValue + ""; } }


        #endregion

        #region 函数

        public pageDeviceTreeView()
        {
            InitializeComponent();
        }

        #endregion

        #region 事件

        /// <summary>
        /// 窗体加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pageDeviceTreeView_Load(object sender, EventArgs e)
        {
            ribbon.AllowCustomization = false;
            ribbon.AllowMinimizeRibbon = false;

            // 关闭列头右键菜单
            treeList1.OptionsMenu.EnableColumnMenu = false;
            treeList1.OptionsBehavior.Editable = false;
            treeList1.OptionsBehavior.ReadOnly = true;
            treeList1.OptionsSelection.EnableAppearanceFocusedCell = false;
            treeList1.OptionsScrollAnnotations.ShowSelectedRows = DevExpress.Utils.DefaultBoolean.False;

            #region 状态格式化
            gcEquipmentStatus.Format.FormatType = DevExpress.Utils.FormatType.Custom;
            gcEquipmentStatus.Format.Format = new StatusFormatter();
            gcEquipmentStatus.Format.FormatString = "device";
            #endregion

            #region 根据权限隐藏按钮
            if (!Utility.SystemRuntimeInfo.AuthValidate(OperationAuthConstValue.PM_Device_KH)
                && !Utility.SystemRuntimeInfo.AuthValidate(OperationAuthConstValue.PM_Device_OEM)
                )
            {
                barSearch.Visibility = BarItemVisibility.Never;
                barRefresh.Visibility = BarItemVisibility.Never;
            }


            if (!Utility.SystemRuntimeInfo.AuthValidate(OperationAuthConstValue.PM_Device_ADD))
            {
                barInsert.Visibility = BarItemVisibility.Never;
            }


            if (!Utility.SystemRuntimeInfo.AuthValidate(OperationAuthConstValue.PM_Device_Edit))
            {
                barEdit.Visibility = BarItemVisibility.Never;
            }


            if (!Utility.SystemRuntimeInfo.AuthValidate(OperationAuthConstValue.PM_Device_Status))
            {
                barEditStatus.Visibility = BarItemVisibility.Never;
            }
            #endregion
        }

        /// <summary>
        /// 搜索
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barSearch_ItemClick(object sender, ItemClickEventArgs e)
        {
            try
            {
                InitializeGridData();
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message, "出错");
            }
        }

        /// <summary>
        /// 刷新
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barRefresh_ItemClick(object sender, ItemClickEventArgs e)
        {
            try
            {
                Utility.SystemRuntimeInfo.CurrentDeviceCaches = null;
                Utility.SystemRuntimeInfo.CurrentUsersCaches = null;
                InitializeGridData();
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message, "出错");
            }
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barInsert_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (!Utility.SystemRuntimeInfo.AuthValidate(OperationAuthConstValue.PM_Device_ADD))
            {
                XtraMessageBoxHelper.Error("当前账号缺少此操作的权限！");
                return;
            }

            try
            {
                using (Page_DriveInfoEdit view = new Page_DriveInfoEdit())
                {
                    if (view.ShowDialog(this) == DialogResult.OK)
                    {
                        DeviceInformationInfo nItem = view.OperationObject;

                        Utility.SystemRuntimeInfo.CurrentDeviceCaches = null;
                        InitializeGridData();
                        XtraMessageBoxHelper.Info("操作成功！");
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message, "出错");
            }
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barEdit_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (!Utility.SystemRuntimeInfo.AuthValidate(OperationAuthConstValue.PM_Device_Edit))
            {
                XtraMessageBoxHelper.Error("当前账号缺少此操作的权限！");
                return;
            }

            if (m_CurrentModel == null || m_CurrentModel.AutoID == 0)
            {
                XtraMessageBoxHelper.Error("请先选择要修改的数据行！");
                return;
            }

            try
            {
                using (Page_DriveInfoEdit view = new Page_DriveInfoEdit("编辑", new View_DriveInfomationModel
                {
                    AutoID = m_CurrentModel.AutoID,
                    EquipmentName = m_CurrentModel.EquipmentName,
                    ChangeDate = m_CurrentModel.ChangeDate.HasValue ? m_CurrentModel.ChangeDate.Value : DateTime.MinValue,
                    ChangeUser = m_CurrentModel.ChangeUser,
                    CreatDate = m_CurrentModel.CreatDate.HasValue ? m_CurrentModel.CreatDate.Value : DateTime.MinValue,
                    CreatUser = m_CurrentModel.CreatUser,
                    EquipmentCategory = m_CurrentModel.EquipmentCategory,
                    EquipmentID = m_CurrentModel.EquipmentID,
                    EquipmentOriginalvalue = m_CurrentModel.EquipmentOriginalvalue,
                    EquipmentStatus = m_CurrentModel.EquipmentStatus,
                    GUID = m_CurrentModel.GUID,
                    InstallationLocation = m_CurrentModel.InstallationLocation,
                    MaintenanceAMFormVersion = m_CurrentModel.MaintenanceAMFormVersion,
                    MaintenanceAMFormVersionName = m_CurrentModel.MaintenanceAMFormVersionName,
                    MaintenanceFormStatus = true,
                    MaintenanceFormVersion = m_CurrentModel.MaintenanceFormVersion,
                    MaintenanceFormVersionName = m_CurrentModel.MaintenanceFormVersionName,
                    Manufacturer = m_CurrentModel.Manufacturer,
                    OperatingParameters = m_CurrentModel.OperatingParameters,
                    OwningUnit = m_CurrentModel.OwningUnit,
                    Remarks = m_CurrentModel.Remarks,
                    Route = Utility.SystemRuntimeInfo.CurrentDeviceCaches.FirstOrDefault(x => x.AutoID == m_CurrentModel.AutoID)?.Route ?? 0,
                    Weight = m_CurrentModel.Weight,
                    SerialNumber = m_CurrentModel.SerialNumber,
                    Specification = m_CurrentModel.Specification,
                    Totalcapacity = m_CurrentModel.Totalcapacity,
                    UsingDate = m_CurrentModel.UsingDate,
                    VersionCode = m_CurrentModel.VersionCode,
                    VersionRev = m_CurrentModel.VersionRev,
                    AMVersionCode = m_CurrentModel.AMVersionCode,
                    AMVersionRev = m_CurrentModel.AMVersionRev,
                    WarrantyPeriod = m_CurrentModel.WarrantyPeriod,
                    RouteText = m_CurrentModel.RouteName
                }))
                {
                    if (view.ShowDialog(this) == DialogResult.OK)
                    {
                        DeviceInformationInfo nItem = view.OperationObject;
                        Utility.SystemRuntimeInfo.CurrentDeviceCaches = null;
                        InitializeGridData();
                        XtraMessageBoxHelper.Info("操作成功！");
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message, "出错");
            }
        }

        /// <summary>
        /// 修改状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barEditStatus_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (!Utility.SystemRuntimeInfo.AuthValidate(OperationAuthConstValue.PM_Device_Status))
            {
                XtraMessageBoxHelper.Error("当前账号缺少此操作的权限！");
                return;
            }

            try
            {
                if (XtraMessageBoxHelper.Ask($"<size=16>确认操作{(m_CurrentModel.EquipmentStatus == 1 ? "禁用" : "启用")} <color=blue><b>设备:{m_CurrentModel.EquipmentName}({m_CurrentModel.EquipmentID})<b/><color/> 吗？") == DialogResult.OK)
                {
                    DateTime dateTime;
                    APIResponseData apiResponseData = DevRepository.Instance.ChangeStatus(m_CurrentModel.AutoID, out dateTime);
                    if (!apiResponseData.IsSuccess)
                        throw new Exception(apiResponseData.Message);

                    DeviceInformationInfoTree Item = ((IList<DeviceInformationInfoTree>)treeList1.DataSource).FirstOrDefault(x => x.AutoID == m_CurrentModel.AutoID);
                    Item.EquipmentStatus = m_CurrentModel.EquipmentStatus == 1 ? 0 : 1;

                    var cache = Utility.SystemRuntimeInfo.CurrentDeviceCaches?.FirstOrDefault(x => x.AutoID == m_CurrentModel.AutoID);
                    cache.EquipmentStatus = m_CurrentModel.EquipmentStatus == 1 ? 0 : 1;
                    treeList1.Refresh();
                    treeList1_RowCellClick(treeList1, new DevExpress.XtraTreeList.RowCellClickEventArgs(new DevExpress.Utils.DXMouseEventArgs(MouseButtons.Left, 1, 1, 1, 1), treeList1.FocusedNode, gcEquipmentID));
                    XtraMessageBoxHelper.Info("操作成功！");
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message, "出错");
            }
        }

        /// <summary>
        /// 点击清空
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ipsEquipmentID_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            ((sender as ButtonEdit)).EditValue = "";
        }

        #endregion

        #region 方法

        /// <summary>
        /// 数据查询
        /// </summary>
        public void InitializeGridData()
        {
            try
            {
                splashScreenManager1.ShowWaitForm();
                m_CurrentModel = null;

                List<string> auths = new List<string>();
                if (Utility.SystemRuntimeInfo.AuthValidate(Utility.SystemRuntimeInfo.DEVICE_OEM))
                    auths.Add("OEM");
                if (Utility.SystemRuntimeInfo.AuthValidate(Utility.SystemRuntimeInfo.DEVICE_KH))
                    auths.Add("KH");

                DevRepository devDa = new DevRepository();
                IList<DeviceInformationInfoTree> Datas = devDa.GetTreeDatas(auths, parEquipmentID);
                Datas = Datas.ToList();

                treeList1.DataSource = Datas;
                treeList1.KeyFieldName = "RouteAutoId";
                treeList1.ParentFieldName = "ParentRouteId";
                treeList1.ExpandAll();
                treeList1.BestFitColumns();

                if (Datas.Count > 0)
                {
                    treeList1_RowCellClick(treeList1, new DevExpress.XtraTreeList.RowCellClickEventArgs(new DevExpress.Utils.DXMouseEventArgs(MouseButtons.Left, 1, 1, 1, 1), treeList1.GetNodeByVisibleIndex(0), gcEquipmentID));
                }

                splashScreenManager1.CloseWaitForm();
            }
            catch (Exception ex)
            {
                splashScreenManager1.CloseWaitForm();
                throw new Exception(ex.Message);
            }
        }

        #endregion

        private void treeList1_RowCellClick(object sender, DevExpress.XtraTreeList.RowCellClickEventArgs e)
        {
            m_CurrentModel = treeList1.GetRow(e.Node.Id) as DeviceInformationInfoTree;

            if (m_CurrentModel != null && m_CurrentModel.AutoID != 0)
            {
                barEdit.Enabled = m_CurrentModel.EquipmentStatus > 0;
                barEditStatus.Enabled = true;

                barEditStatus.Caption = m_CurrentModel.EquipmentStatus > 0 ? "禁用" : "启用";
                barEditStatus.ImageOptions.Image = m_CurrentModel.EquipmentStatus > 0 ? Icons["Lock"] : Icons["UnLock"];
                barEditStatus.ImageOptions.LargeImage = m_CurrentModel.EquipmentStatus > 0 ? Icons["Lock"] : Icons["UnLock"];
            }
            else
            {
                barEditStatus.Enabled = false;
                barEdit.Enabled = false;
            }
        }
    }
}