using DevExpress.XtraGrid.Views.Grid;
using DeviceRepair.Models;
using DeviceRepairAndOptimization.Common;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;

namespace DeviceRepairAndOptimization.Pages.AM.FormVersion
{
    public partial class pageFormVersionView : FormBase
    {
        #region Field

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

        private MaintenanceFormVersionInfo _CurrentData;
        public MaintenanceFormVersionInfo CurrentData
        {
            get { return _CurrentData; }
            set
            {
                _CurrentData = value;
                if (value == null)
                {
                    btnEdit.Enabled = false;
                    btnChangeStatus.Enabled = false;
                    btnBind.Enabled = false;
                    return;
                }

                btnEdit.Enabled = value.FormStatus;
                btnChangeStatus.Enabled = true;
                btnBind.Enabled = value.FormStatus;

                btnChangeStatus.Text = value.FormStatus ? "禁用" : "启用";
                btnChangeStatus.ImageOptions.Image = value.FormStatus ? Icons["Lock"] : Icons["UnLock"];
            }
        }

        private MaintenanceFormFilter _filter;
        public MaintenanceFormFilter Fitler
        {
            get
            {
                if (_filter == null)
                    _filter = new MaintenanceFormFilter();

                _filter.FilterText = btnFIlter.EditValue + "";
                _filter.FormBelong = DeviceRepair.Models.Enum.EnumDeviceBelong.AM;

                return _filter;
            }
        }

        List<MaintenanceFormVersionInfo> Datas;

        #endregion

        public pageFormVersionView()
        {
            InitializeComponent();
            InitializeGridConvert();
        }

        /// <summary>
        /// 窗体加载完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void pageFormVersionView_Load(object sender, EventArgs e)
        {
            try
            {
                this.layoutControl1.AllowCustomization = false;
                gvControl.OptionsMenu.EnableColumnMenu = false;

                gvControl.OptionsBehavior.Editable = false;
                gvControl.OptionsBehavior.ReadOnly = true;

                gvControl.OptionsSelection.MultiSelect = true;
                gvControl.OptionsSelection.MultiSelectMode = GridMultiSelectMode.CheckBoxRowSelect;

                gvControl.OptionsSelection.EnableAppearanceFocusedCell = false;
                gvControl.OptionsScrollAnnotations.ShowSelectedRows = DevExpress.Utils.DefaultBoolean.False;

                foreach (DevExpress.XtraGrid.Columns.GridColumn item in gvControl.Columns)
                {
                    item.OptionsColumn.AllowEdit = false;
                    item.OptionsColumn.AllowGroup = DevExpress.Utils.DefaultBoolean.True;
                    item.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;
                    item.OptionsColumn.AllowShowHide = false;
                }

                InitiaLizeGridData();
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }

        }

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

        /// <summary>
        /// 选择框标题
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gvControl_CustomDrawColumnHeader(object sender, DevExpress.XtraGrid.Views.Grid.ColumnHeaderCustomDrawEventArgs e)
        {
            if (e.Column != null && (e.Column.Caption == "Selection" || e.Column.FieldName == "DX$CheckboxSelectorColumn"))
                e.Info.Caption = "选择";
        }

        /// <summary>
        /// 单元格点击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gvControl_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            if (e.Button != MouseButtons.Right)
            {
                gvControl.SelectRow(e.RowHandle);
                CurrentData = gvControl.GetRow(e.RowHandle) as MaintenanceFormVersionInfo;
                btnChangeStatus.ImageOptions.Image = CurrentData.FormStatus ? Icons["Lock"] : Icons["UnLock"];
            }
        }

        #region Method

        /// <summary>
        /// 初始化表格控件
        /// </summary>
        private void InitializeGridConvert()
        {
            gvControl.OptionsSelection.ShowCheckBoxSelectorInColumnHeader = DevExpress.Utils.DefaultBoolean.False;
            gcFormStatus.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom;
            gcFormStatus.DisplayFormat.Format = new TsSFCDevice.Control.CustomFormatProvider.StatusFormatter();
            gcFormStatus.DisplayFormat.FormatString = "status";
        }

        private void InitiaLizeGridData()
        {
            try
            {
                if (!GlobalInfo.HasRole(AuthCodeConstValue.BIZ_FormVersion_AM_01))
                {
                    XtraMessageBoxHelper.Error($"当前账号缺少此操作的权限");
                    return;
                }

                splashScreenManager1.ShowWaitForm();
                APIResponseData apiResponseData = Biz.FormManager.Instance.GetQuery(Fitler);
                if (!apiResponseData.IsSuccess)
                    throw new Exception(apiResponseData.Message);

                Datas = apiResponseData.ToDeserializeObject<List<MaintenanceFormVersionInfo>>();
                gcControl.DataSource = Datas;

                // 设置行号列宽度
                SizeF size = this.CreateGraphics().MeasureString(Datas.Count.ToString(), this.Font);
                gvControl.IndicatorWidth = Convert.ToInt32(size.Width) + 30;

                CurrentData = null;
                splashScreenManager1.TryCloseWait();
            }
            catch (Exception ex)
            {
                splashScreenManager1.TryCloseWait();
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        #endregion

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void btnAdd_Click(object sender, EventArgs e)
        {
            try
            {
                if (!GlobalInfo.HasRole(AuthCodeConstValue.BIZ_FormVersion_AM_02))
                {
                    XtraMessageBoxHelper.Error($"当前账号缺少此操作的权限");
                    return;
                }

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

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

                            apiResponseData = Biz.FormManager.Instance.InsertSingle(view.CurrentModel);
                            if (!apiResponseData.IsSuccess)
                            {
                                throw new ArgumentException(apiResponseData.Message);
                            }

                            MaintenanceFormVersionInfo Rtn = apiResponseData.ToDeserializeObject<MaintenanceFormVersionInfo>();
                            if (Rtn != null)
                            {
                                Datas.Add(Rtn);
                                gvControl.RefreshData();
                                gvControl.FocusedRowHandle = gvControl.RowCount - 1;
                                gvControl.SelectRow(gvControl.RowCount - 1);
                                gvControl_RowCellClick(gvControl, new RowCellClickEventArgs(new DevExpress.Utils.DXMouseEventArgs(MouseButtons.Left, 1, 1, 1, 1), (gvControl.RowCount - 1), gcFormName));
                            }

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

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnEdit_Click(object sender, EventArgs e)
        {
            if (!GlobalInfo.HasRole(AuthCodeConstValue.BIZ_FormVersion_AM_03))
            {
                XtraMessageBoxHelper.Error($"当前账号缺少此操作的权限");
                return;
            }

            if (CurrentData == null)
            {
                XtraMessageBoxHelper.Error($"请选择要操作的内容！");
                return;
            }

            using (pageFormVersionEdit view = new pageFormVersionEdit(CurrentData))
            {
                if (view.ShowDialog() == DialogResult.OK)
                {
                    splashScreenManager1.ShowWaitForm();
                    try
                    {
                        APIResponseData apiResponseData = Biz.FormManager.Instance.ChangeRemark(view.CurrentModel);
                        if (!apiResponseData.IsSuccess)
                        {
                            throw new ArgumentException(apiResponseData.Message);
                        }

                        CurrentData.Remarks = view.CurrentModel.Remarks;
                        MaintenanceFormVersionInfo Item = Datas.FirstOrDefault(x => x.AutoID == view.CurrentModel.AutoID);
                        Item.Remarks = view.CurrentModel.Remarks;

                        gvControl.RefreshData();
                        splashScreenManager1.TryCloseWait();
                        XtraMessageBoxHelper.Info("操作成功!");
                    }
                    catch (Exception)
                    {
                        splashScreenManager1.TryCloseWait();
                        throw;
                    }
                }
            }
        }

        /// <summary>
        /// 查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnFIlter_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Clear)
            {
                btnFIlter.EditValue = "";
            }
            else
            {
                InitiaLizeGridData();
            }
        }

        private void gvControl_SelectionChanged(object sender, DevExpress.Data.SelectionChangedEventArgs e)
        {
            gvControl.SelectionChanged -= gvControl_SelectionChanged;

            //清除所有选择
            gvControl.ClearSelection();
            gvControl.SelectRow(e.ControllerRow);

            gvControl.SelectionChanged += gvControl_SelectionChanged;
        }

        private void btnFIlter_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == (char)ConsoleKey.Enter)
            {
                InitiaLizeGridData();
            }
        }

        /// <summary>
        /// 修改状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnChangeStatus_Click(object sender, EventArgs e)
        {
            if (!GlobalInfo.HasRole(AuthCodeConstValue.BIZ_FormVersion_AM_05))
            {
                XtraMessageBoxHelper.Error($"当前账号缺少此操作的权限");
                return;
            }

            if (CurrentData == null)
            {
                XtraMessageBoxHelper.Error($"请选择要操作的内容！");
                return;
            }

            try
            {
                if (XtraMessageBoxHelper.Ask($"<size=16>确认<b>{(CurrentData.FormStatus ? "<color=red>禁用<color/>" : "<color=LimeGreen>启用<color/>")}<b/>点检表{CurrentData.FormName}-{CurrentData.VersionRev}?<size/>") == DialogResult.Cancel)
                {
                    return;
                }

                splashScreenManager1.ShowWaitForm();

                bool ChangeStatus = !CurrentData.FormStatus;
                APIResponseData apiResponseData = Biz.FormManager.Instance.DataStatusChange(new MaintenanceFormFilter
                {
                    PrimaryKey = CurrentData.AutoID,
                    FormStatus = ChangeStatus
                });
                if (!apiResponseData.IsSuccess)
                {
                    throw new ArgumentException(apiResponseData.Message);
                }

                foreach (MaintenanceFormVersionInfo item in Datas)
                {
                    if (item.AutoID == CurrentData.AutoID)
                    {
                        item.FormStatus = ChangeStatus;
                        CurrentData = null;
                        CurrentData = item;
                        break;
                    }
                }

                gvControl.RefreshData();
                splashScreenManager1.TryCloseWait();
            }
            catch (Exception ex)
            {
                splashScreenManager1.TryCloseWait();
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        /// <summary>
        /// 点检表维护设备绑定
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnBind_Click(object sender, EventArgs e)
        {
            try
            {
                if (!GlobalInfo.HasRole(AuthCodeConstValue.BIZ_FormVersion_AM_04))
                {
                    XtraMessageBoxHelper.Error($"当前账号缺少此操作的权限");
                    return;
                }

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

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