using DevExpress.XtraEditors;
using DeviceRepairAndOptimization.Pages.FormVersion;
using DeviceRepairAndOptimization.Pages.DriveMaintenance;
using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Drawing;
using DeviceRepair.Models;
using DeviceRepairAndOptimization.Biz;
using Newtonsoft.Json;
using DeviceRepairAndOptimization.Common;
using System.Linq;

namespace DeviceRepairAndOptimization.Pages
{
    public partial class page_FormVersion : FormBase
    {
        Dictionary<string, Image> Icons = new Dictionary<string, Image>
        {
            { "Lock",DevExpress.Images.ImageResourceCache.Default.GetImageById(DevExpress.Images.DXImages.Cancel,DevExpress.Utils.Design.ImageSize.Size16x16,DevExpress.Utils.Design.ImageType.Colored) },
            { "UnLock",DevExpress.Images.ImageResourceCache.Default.GetImageById(DevExpress.Images.DXImages.Apply,DevExpress.Utils.Design.ImageSize.Size16x16,DevExpress.Utils.Design.ImageType.Colored) },
        };

        /// <summary>
        /// 当前选中行对象
        /// </summary>
        private MaintenanceFormVersionInfo CurrentItem
        {
            get
            {
                if (gridView1.FocusedRowHandle >= 0)
                    return (MaintenanceFormVersionInfo)gridView1.GetRow(gridView1.FocusedRowHandle);
                return null;
            }
        }

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

        /// <summary>
        /// 数据加载
        /// </summary>
        /// <returns></returns>
        List<MaintenanceFormVersionInfo> GetDatas()
        {
            List<MaintenanceFormVersionInfo> Datas = new List<MaintenanceFormVersionInfo>();
            try
            {
                APIResponseData apiResponseData = FormManager.Instance.GetQuery(FilterString);
                if (apiResponseData.Code == 1)
                {
                    Datas = JsonConvert.DeserializeObject<List<MaintenanceFormVersionInfo>>(apiResponseData.Data + "");
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
            return Datas;
        }

        public page_FormVersion()
        {
            InitializeComponent();

            gridView1.CustomDrawRowIndicator += GridView1_CustomDrawRowIndicator;
            // gridView1.RowStyle += GridView1_RowStyle;

            this.Load += (s, e) =>
            {
                GridViewInitialize(gridView1);
            };
        }

        private void GridView1_RowStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowStyleEventArgs e)
        {
            DevExpress.XtraGrid.Views.Grid.GridView view = sender as DevExpress.XtraGrid.Views.Grid.GridView;

            if (e.RowHandle >= 0)
            {
                MaintenanceFormVersionInfo item = view.GetRow(e.RowHandle) as MaintenanceFormVersionInfo;
                if (!item.FormStatus)
                    e.Appearance.BackColor = Color.FromArgb(255, 126, 126);
            }
        }

        /// <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.Info.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
                e.Info.Appearance.TextOptions.VAlignment = DevExpress.Utils.VertAlignment.Center;
            }
        }

        void BindData()
        {
            List<MaintenanceFormVersionInfo> lst = GetDatas();
            gridControl1.DataSource = lst;
        }

        private void EditSearch_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
        }

        private void EditSearch_TextChanged(object sender, EventArgs e)
        {
            string aa = EditSearch.Text;
        }

        private void page_FormVersion_Load(object sender, EventArgs e)
        {
            try
            {
                splashScreenManager1.ShowWaitForm();
                BindData();

                MaintenanceFormVersionInfo item = (MaintenanceFormVersionInfo)gridView1.GetRow(0);
                if (item != null)
                {
                    btn_ChangeStatus.ImageOptions.Image = item.FormStatus ? Icons["Lock"] : Icons["UnLock"];
                    btn_ChangeStatus.Text = item.FormStatus ? "禁用" : "启用";
                    btn_ChangeStatus.Refresh();
                }

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

        /// <summary>
        /// 新增导入点检表
        /// ps.当前点检表数据写入到数据库, 后续需添加接口到sfc,文档文件需上传到webservice。
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Add_Click(object sender, EventArgs e)
        {
            try
            {
                if (!GlobalInfo.HasRole("BIZ_MAINTENANCEFORMREV_ADD"))
                {
                    XtraMessageBoxHelper.Error($"当前账号缺少此操作的权限");
                    return;
                }

                Page_FormVersionAdd _form = new Page_FormVersionAdd("点检表新增");
                if (_form.ShowDialog() == DialogResult.OK)
                    BindData();
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        private void btn_Filter_Click(object sender, EventArgs e)
        {
            BindData();
        }

        private void gridView1_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)
        {
            if (e.IsGetData && e.Column.FieldName == "Number")
            {
                e.Value = e.ListSourceRowIndex + 1; // 设置序号值
            }
        }

        /// <summary>
        /// 行选择模式，且全部只读
        /// </summary>
        /// <param name="view"></param>
        void GridViewInitialize(DevExpress.XtraGrid.Views.Grid.GridView view)
        {
            view.OptionsBehavior.Editable = false;
            view.OptionsBehavior.ReadOnly = true;

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

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

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

                if (CurrentItem != null && CurrentItem.FormStatus)
                {
                    Page_FormVersionAdd _form = new Page_FormVersionAdd("点检表编辑", CurrentItem.AutoID);
                    if (_form.ShowDialog() == DialogResult.OK)
                        BindData();
                }
                else if (CurrentItem == null)
                {
                    XtraMessageBoxHelper.Error("请选择要操作的点检表数据！");
                    return;
                }
                else if (!CurrentItem.FormStatus)
                {
                    XtraMessageBoxHelper.Error("点检表已锁定，不可操作！");
                    return;
                }

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

        /// <summary>
        /// 启用/禁用
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_ChangeStatus_Click(object sender, EventArgs e)
        {
            try
            {
                if (!GlobalInfo.HasRole("BIZ_MAINTENANCEFORMREV_LOCK"))
                {
                    XtraMessageBoxHelper.Error($"当前账号缺少此操作的权限");
                    return;
                }

                DialogResult result = XtraMessageBox.Show("你确定要执行此操作吗？", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (result == DialogResult.Yes)
                {
                    APIResponseData apiResponseData = FormManager.Instance.ChangeStauts(CurrentItem.AutoID);

                    if (apiResponseData.Code == 1)
                    {
                        XtraMessageBox.Show("操作成功!", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        BindData();
                    }
                    else
                    {
                        throw new Exception(apiResponseData.Message);
                    }
                }
            }
            catch (Exception ex)
            {
                BindData();
                XtraMessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

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

                if (CurrentItem.FormStatus)
                {
                    // Page_AssignDrives view = new Page_AssignDrives(CurrentItem);
                    page_AssignDriveTree view = new page_AssignDriveTree(CurrentItem);
                    if (view.ShowDialog() == DialogResult.OK)
                    {
                        XtraMessageBox.Show("操作成功!", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        BindData();
                    }
                }
                else
                {
                    XtraMessageBoxHelper.Error("点检表已锁定，不可操作！");
                }
            }
            catch (Exception ex)
            {
                BindData();
                XtraMessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 选中行更改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            try
            {
                if (CurrentItem != null)
                {
                    btn_ChangeStatus.ImageOptions.Image = CurrentItem.FormStatus ? Icons["Lock"] : Icons["UnLock"];
                    btn_ChangeStatus.Text = CurrentItem.FormStatus ? "禁用" : "启用";
                    btn_ChangeStatus.Refresh();
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }
    }
}