using DevExpress.XtraBars;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using DeviceRepair.Models;
using DeviceRepair.Utils;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using TsSFCDevice.Client.Biz.Base.Utils;
using TsSFCDevice.Client.Biz.Impl;
using TsSFCDevice.Client.Launch.FormatProviderExtend;

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

        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<View_DriveInfomationModel> Datas { get; set; }

        private View_DriveInfomationModel m_CurrentModel;

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

        #endregion

        #region 函数
        public pageDeviceView()
        {
            InitializeComponent();
        }
        #endregion

        #region 事件
        private void pageDeviceView_Load(object sender, EventArgs e)
        {
            ribbon.AllowCustomization = false;
            ribbon.AllowMinimizeRibbon = false;

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

            #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 gridView1_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs 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;
            }
        }

        /// <summary>
        /// 单元格点击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridView1_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            m_CurrentModel = gridView1.GetRow(e.RowHandle) as View_DriveInfomationModel;

            if (m_CurrentModel != null)
            {
                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"];
            }
        }

        /// <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 = "";
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barSearch_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (!Utility.SystemRuntimeInfo.AuthValidate(OperationAuthConstValue.PM_Device_KH)
                && !Utility.SystemRuntimeInfo.AuthValidate(OperationAuthConstValue.PM_Device_OEM))
            {
                XtraMessageBoxHelper.Error("当前账号缺少此操作的权限！");
                this.DialogResult = DialogResult.Cancel;
                return;
            }

            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();
                        gridView1_RowCellClick(gridControl1, new RowCellClickEventArgs(new DevExpress.Utils.DXMouseEventArgs(MouseButtons.Left, 1, 1, 1, 1), 0, EquipmentID));
                        gridView1.FocusedRowHandle = 0;
                        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;
            }

            try
            {
                using (Page_DriveInfoEdit view = new Page_DriveInfoEdit("编辑", m_CurrentModel))
                {
                    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);

                    View_DriveInfomationModel Item = ((IList<View_DriveInfomationModel>)gridView1.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;
                    gridView1.RefreshData();
                    gridView1_RowCellClick(gridControl1, new RowCellClickEventArgs(new DevExpress.Utils.DXMouseEventArgs(MouseButtons.Left, 1, 1, 1, 1), gridView1.FocusedRowHandle, EquipmentID));
                    XtraMessageBoxHelper.Info("操作成功！");
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message, "出错");
            }
        }

        /// <summary>
        /// 导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barExport_ItemClick(object sender, ItemClickEventArgs e)
        {
            try
            {
                SaveFileDialog saveFileDialog = new SaveFileDialog();
                saveFileDialog.Title = "导出Excel";
                saveFileDialog.Filter = "Excel文件(*.xlsx)|*.xlsx";
                DialogResult dialogResult = saveFileDialog.ShowDialog();
                if (dialogResult == DialogResult.OK)
                {
                    DevExpress.XtraPrinting.XlsxExportOptionsEx options = new DevExpress.XtraPrinting.XlsxExportOptionsEx();
                    options.ExportType = DevExpress.Export.ExportType.WYSIWYG;
                    gridView1.OptionsPrint.AutoWidth = false;
                    gridControl1.ExportToXlsx(saveFileDialog.FileName, options);
                    XtraMessageBoxHelper.Info("导出成功！", "提示");
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message, "出错");
            }
        }
        #endregion

        #region 方法

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

                m_CurrentModel = null;
                List<DeviceInformationInfo> Devs;
                if (!parEquipmentID.IsNull())
                {
                    Devs = Utility.SystemRuntimeInfo.CurrentDeviceCaches.Where(x => x.EquipmentID == parEquipmentID)?.ToList();
                }
                else
                {
                    Devs = Utility.SystemRuntimeInfo.CurrentDeviceCaches.ToList();
                }

                if (Devs == null || Devs.Count == 0)
                {
                    gridControl1.DataSource = null;
                    barEdit.Enabled = false;
                    barEditStatus.Enabled = false;
                    splashScreenManager1.CloseWaitForm();
                    return;
                }

                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");

                //IList<DeviceRouteInfo> routes = DevRepository.Instance.Get_DEVICE_Route(auths)?.ToList();
                //Dictionary<int, DeviceRouteInfo> routesKeyValuePairs = routes.ToDictionary(x => x.AutoID, x => x);

                IList<MaintenanceFormVersionInfo> FormData = CheckFormRepository.Instance.GetDatas();
                Dictionary<int, MaintenanceFormVersionInfo> checkFormkeyValuePairs = FormData.ToDictionary(x => x.AutoID, x => x);

                List<View_DriveInfomationModel> ViewDatas = new List<View_DriveInfomationModel>();

                Devs.ForEach(x =>
                {
                    View_DriveInfomationModel item = new View_DriveInfomationModel(x);

                    if (item.MaintenanceFormVersion > 0 && checkFormkeyValuePairs.ContainsKey(item.MaintenanceFormVersion))
                    {
                        item.VersionCode = checkFormkeyValuePairs[item.MaintenanceFormVersion].VersionCode;
                        item.VersionRev = checkFormkeyValuePairs[item.MaintenanceFormVersion].VersionRev;
                        item.MaintenanceFormVersionName = checkFormkeyValuePairs[item.MaintenanceFormVersion].FormName;
                        item.MaintenanceFormStatus = checkFormkeyValuePairs[item.MaintenanceFormVersion].FormStatus;
                    }

                    if (item.MaintenanceAMFormVersion > 0 && checkFormkeyValuePairs.ContainsKey(item.MaintenanceAMFormVersion))
                    {
                        item.MaintenanceAMFormVersionName = checkFormkeyValuePairs[item.MaintenanceAMFormVersion].FormName;
                        item.AMVersionCode = checkFormkeyValuePairs[item.MaintenanceAMFormVersion].VersionCode;
                        item.AMVersionRev = checkFormkeyValuePairs[item.MaintenanceAMFormVersion].VersionRev;
                    }

                    ViewDatas.Add(item);
                });
                Datas = ViewDatas;

                gridControl1.DataSource = Datas;

                // 设置行号列宽度
                if (Datas.Count > 0)
                {
                    SizeF size = this.CreateGraphics().MeasureString(Datas.Count.ToString(), this.Font);
                    gridView1.IndicatorWidth = Convert.ToInt32(size.Width) + 20;
                    gridView1.FocusedRowHandle = 0;
                    gridView1_RowCellClick(gridView1, new RowCellClickEventArgs(new DevExpress.Utils.DXMouseEventArgs(MouseButtons.Left, 1, 1, 1, 1), 0, EquipmentID));
                }

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

        #endregion
    }
}