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

namespace TsSFCDevice.Client.Launch.CheckForm
{
    public partial class pageCheckFormView : DevExpress.XtraBars.Ribbon.RibbonForm
    {
        #region 属性&字段
        public EnumDeviceBelong Belong { get; set; } = EnumDeviceBelong.PM;

        private string parChkFormName { get { return baripsChkFormName.EditValue + ""; } }

        MaintenanceFormVersionInfo m_CurrentModel;

        IList<MaintenanceFormVersionInfo> Datas;

        int Counter = 0;

        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) },
        };
        #endregion

        #region 函数

        public pageCheckFormView() : this(EnumDeviceBelong.PM)
        {
        }

        public pageCheckFormView(EnumDeviceBelong belong)
        {
            this.Belong = belong;
            InitializeComponent();
        }

        #endregion

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

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

            #region 根据权限隐藏按钮

            switch (Belong)
            {
                case EnumDeviceBelong.AM:
                    AM_VisibilityControl();
                    break;
                case EnumDeviceBelong.PM:
                default:
                    PM_VisibilityControl();
                    break;
            }

            #endregion
        }

        void PM_VisibilityControl()
        {
            if (!Utility.SystemRuntimeInfo.AuthValidate(OperationAuthConstValue.PM_CheckFORM_Watch))
            {
                barSearch.Visibility = BarItemVisibility.Never;
            }


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


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


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


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

        void AM_VisibilityControl()
        {
            if (!Utility.SystemRuntimeInfo.AuthValidate(OperationAuthConstValue.AM_CheckFORM_Watch))
            {
                barSearch.Visibility = BarItemVisibility.Never;
            }


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


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


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


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

        /// <summary>
        /// 搜索
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barSearch_ItemClick(object sender, ItemClickEventArgs e)
        {
            InitializeGridData();
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barInsert_ItemClick(object sender, ItemClickEventArgs e)
        {
            string AuthCode = OperationAuthConstValue.PM_CheckFORM_Add;
            switch (Belong)
            {
                case EnumDeviceBelong.AM:
                    AuthCode = OperationAuthConstValue.AM_CheckFORM_Add;
                    break;
                case EnumDeviceBelong.PM:
                default:
                    AuthCode = OperationAuthConstValue.PM_CheckFORM_Add;
                    break;
            }
            if (!Utility.SystemRuntimeInfo.AuthValidate(AuthCode))
            {
                XtraMessageBoxHelper.Error("当前账号缺少此操作的权限！");
                return;
            }

            pageFormVersionEdit view;
            switch (Belong)
            {
                case EnumDeviceBelong.AM:
                    view = new pageFormVersionEdit(new MaintenanceFormVersionInfo { FormBelong = EnumDeviceBelong.AM.ToString() });
                    break;
                case EnumDeviceBelong.PM:
                default:
                    view = new pageFormVersionEdit();
                    break;
            }

            try
            {
                if (view.ShowDialog() == DialogResult.OK)
                {
                    splashScreenManager1.ShowWaitForm();
                    try
                    {
                        //上传到webservice
                        APIResponseData apiResponseData = CommonRepository.Instance.UploadFile(view.CurrentModel.FormPath);
                        if (!apiResponseData.IsSuccess)
                        {
                            throw new ArgumentException(apiResponseData.Message);
                        }

                        view.CurrentModel.FormPath = apiResponseData.Data + "";

                        apiResponseData = CheckFormRepository.Instance.Insert_CheckForm_Data(view.CurrentModel);
                        if (!apiResponseData.IsSuccess)
                        {
                            throw new ArgumentException(apiResponseData.Message);
                        }

                        splashScreenManager1.TryCloseWait();
                        InitializeGridData();
                        XtraMessageBoxHelper.Info("操作成功!");
                    }
                    catch (Exception ex)
                    {
                        splashScreenManager1.TryCloseWait();
                        throw new Exception(ex.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
            finally
            {
                view.Dispose();
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barEdit_ItemClick(object sender, ItemClickEventArgs e)
        {
            string AuthCode = OperationAuthConstValue.PM_CheckFORM_Edit;
            switch (Belong)
            {
                case EnumDeviceBelong.AM:
                    AuthCode = OperationAuthConstValue.AM_CheckFORM_Edit;
                    break;
                case EnumDeviceBelong.PM:
                default:
                    AuthCode = OperationAuthConstValue.PM_CheckFORM_Edit;
                    break;
            }

            if (!Utility.SystemRuntimeInfo.AuthValidate(AuthCode))
            {
                XtraMessageBoxHelper.Error("当前账号缺少此操作的权限！");
                return;
            }

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

            try
            {
                using (pageFormVersionEdit view = new pageFormVersionEdit(m_CurrentModel))
                {
                    if (view.ShowDialog() == DialogResult.OK)
                    {
                        splashScreenManager1.ShowWaitForm();
                        try
                        {
                            APIResponseData apiResponseData = CheckFormRepository.Instance.Change_CheckForm_Remark(view.CurrentModel);
                            if (!apiResponseData.IsSuccess)
                            {
                                throw new ArgumentException(apiResponseData.Message);
                            }
                            splashScreenManager1.TryCloseWait();
                            InitializeGridData();
                            XtraMessageBoxHelper.Info("操作成功!");
                        }
                        catch (Exception)
                        {
                            splashScreenManager1.TryCloseWait();
                            throw;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                splashScreenManager1.TryCloseWait();
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        /// <summary>
        /// 状态更改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barStatus_ItemClick(object sender, ItemClickEventArgs e)
        {
            string AuthCode = OperationAuthConstValue.PM_CheckFORM_Status;
            switch (Belong)
            {
                case EnumDeviceBelong.AM:
                    AuthCode = OperationAuthConstValue.AM_CheckFORM_Status;
                    break;
                case EnumDeviceBelong.PM:
                default:
                    AuthCode = OperationAuthConstValue.PM_CheckFORM_Status;
                    break;
            }

            if (!Utility.SystemRuntimeInfo.AuthValidate(AuthCode))
            {
                XtraMessageBoxHelper.Error("当前账号缺少此操作的权限！");
                return;
            }

            if (m_CurrentModel == null)
            {
                XtraMessageBoxHelper.Error("请选择要操作的数据！");
                return;
            }

            if (XtraMessageBoxHelper.Ask($"<size=16>确认<color=red><b>{(m_CurrentModel.FormStatus ? "禁用" : "启用")}<b/><color/>点检表 <color=blue><b>:{m_CurrentModel.FormName}({m_CurrentModel.VersionCode} {m_CurrentModel.VersionRev})<b/><color/> 吗？") == DialogResult.OK)
            {
                try
                {
                    splashScreenManager1.ShowWaitForm();
                    APIResponseData apiResponseData = CheckFormRepository.Instance.Change_Form_Status(m_CurrentModel.AutoID, (m_CurrentModel.FormStatus ? "G" : "A"));
                    if (!apiResponseData.IsSuccess)
                    {
                        throw new Exception(apiResponseData.Message);
                    }

                    var Item = (gvControl.DataSource as List<MaintenanceFormVersionInfo>).FirstOrDefault(x => x.AutoID == m_CurrentModel.AutoID);
                    if (Item != null)
                    {
                        Item.FormStatus = !Item.FormStatus;
                    }
                    gvControl.RefreshData();
                    gvControl_RowCellClick(this.gcControl, new DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs(new DevExpress.Utils.DXMouseEventArgs(MouseButtons.Left, 1, 1, 1, 1), gvControl.FocusedRowHandle, gcFormName));
                    splashScreenManager1.TryCloseWait();
                }
                catch (Exception ex)
                {
                    splashScreenManager1.TryCloseWait();
                    XtraMessageBoxHelper.Error(ex.Message);
                }
            }
        }

        /// <summary>
        /// 分配到设备
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barAssig_ItemClick(object sender, ItemClickEventArgs e)
        {
            string AuthCode = OperationAuthConstValue.PM_CheckFORM_Assig;
            switch (Belong)
            {
                case EnumDeviceBelong.AM:
                    AuthCode = OperationAuthConstValue.AM_CheckFORM_Assig;
                    break;
                case EnumDeviceBelong.PM:
                default:
                    AuthCode = OperationAuthConstValue.PM_CheckFORM_Assig;
                    break;
            }

            if (!Utility.SystemRuntimeInfo.AuthValidate(AuthCode))
            {
                XtraMessageBoxHelper.Error("当前账号缺少此操作的权限！");
                return;
            }

            if (m_CurrentModel == null)
            {
                XtraMessageBoxHelper.Error("请选择要操作的数据！");
                return;
            }

            try
            {
                if (m_CurrentModel.FormStatus)
                {
                    using (page_AssignDriveTree view = new page_AssignDriveTree(m_CurrentModel))
                    {
                        if (view.ShowDialog(this) == DialogResult.OK)
                        {
                            XtraMessageBoxHelper.Info("操作成功!");
                            return;
                        }
                    }
                }
                else
                {
                    XtraMessageBoxHelper.Error("点检表已锁定，不可操作！");
                    return;
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message, "出错");
            }
        }

        /// <summary>
        /// 搜索内容清空
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ipsChkFormName_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            ((sender as ButtonEdit)).EditValue = "";
        }

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

            if (m_CurrentModel != null)
            {
                barEdit.Enabled = m_CurrentModel.FormStatus;
                barStatus.Enabled = true;
                barAssig.Enabled = m_CurrentModel.FormStatus;

                barStatus.Caption = m_CurrentModel.FormStatus ? "禁用" : "启用";
                barStatus.ImageOptions.Image = m_CurrentModel.FormStatus ? Icons["Lock"] : Icons["UnLock"];
                barStatus.ImageOptions.LargeImage = m_CurrentModel.FormStatus ? Icons["Lock"] : Icons["UnLock"];
            }
        }

        /// <summary>
        /// 自增长行号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gvControl_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;
            }
        }
        #endregion

        #region 方法
        private void InitializeGridData()
        {
            try
            {
                splashScreenManager1.ShowWaitForm();
                m_CurrentModel = null;

                // 获取维修数据
                switch (Belong)
                {
                    case EnumDeviceBelong.AM:
                        Datas = CheckFormRepository.Instance.Get_AM_CheckForm_Datas(parChkFormName);
                        break;
                    case EnumDeviceBelong.PM:
                        Datas = CheckFormRepository.Instance.Get_PM_CheckForm_Datas(parChkFormName);
                        break;
                    default:
                        break;
                }

                gcControl.DataSource = Datas;

                // 设置行号列宽度
                Counter = (gvControl.DataSource as IList<MaintenanceFormVersionInfo>)?.Count ?? 0;
                if (Counter > 0)
                {
                    SizeF size = this.CreateGraphics().MeasureString(Datas.Count.ToString(), this.Font);
                    gvControl.IndicatorWidth = Convert.ToInt32(size.Width) + 20;
                    gvControl.FocusedRowHandle = 0;
                    gvControl_RowCellClick(gvControl, new RowCellClickEventArgs(new DevExpress.Utils.DXMouseEventArgs(MouseButtons.Left, 1, 1, 1, 1), 0, gcFormName));
                }

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