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

namespace DeviceRepairAndOptimization.Pages.Maintenance
{
    public partial class page_MaintenanceView : FormBase
    {
        public page_MaintenanceView()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 当前勾选数据下标
        /// </summary>
        private int[] SelectedRows
        {
            get
            {
                return gridView1.GetSelectedRows();
            }
        }

        private string FilterString
        {
            get
            {
                return txt_Filter.Text.Trim();
            }
        }

        private void lb_Caption_Click(object sender, EventArgs e)
        {

        }

        /// <summary>
        /// 数据加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void page_MaintenanceView_Load(object sender, EventArgs e)
        {
            GridViewInitialize(gridView1);
            gridView1.CustomDrawRowIndicator += GridView1_CustomDrawRowIndicator;
            GetDatas();
        }

        /// <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="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>
        void GetDatas()
        {
            APIResponseData result = PreserveManager.Instance.GetPreserveDatas(FilterString);
            if (result.Code == -1)
            {
                XtraMessageBox.Show(result.Message, "出错", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            gridControl1.DataSource = result.Data;
        }

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

                if (SelectedRows.Length == 0)
                {
                    XtraMessageBox.Show("请勾选要操作的数据", "出错", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                View_MaintenanceRecordList model = JsonConvert.DeserializeObject<View_MaintenanceRecordList>(gridView1.GetRow(SelectedRows[0]) + "");
                page_MaintenancePdfView view = new page_MaintenancePdfView("详情", new int[] { model.AutoID });
                view.ShowDialog();
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

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

                if (SelectedRows.Length == 0)
                {
                    XtraMessageBox.Show("请勾选要操作的数据", "出错", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                View_MaintenanceRecordList model = JsonConvert.DeserializeObject<View_MaintenanceRecordList>(gridView1.GetRow(SelectedRows[0]) + "");
                page_MaintenancePdfView view = new page_MaintenancePdfView("打印", new int[] { model.AutoID }, true);
                view.ShowDialog();
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

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

                if (SelectedRows.Length == 0)
                {
                    throw new Exception("请勾选要操作的数据");
                }

                List<int> ids = new List<int>();
                foreach (int item in SelectedRows)
                {
                    View_MaintenanceRecordList model = JsonConvert.DeserializeObject<View_MaintenanceRecordList>(gridView1.GetRow(item) + "");
                    ids.Add(model.AutoID);
                }

                page_MaintenancePdfView view = new page_MaintenancePdfView("打印", ids.ToArray(), true);
                view.ShowDialog();
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

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

                if (SelectedRows.Length == 0)
                {
                    XtraMessageBox.Show("请勾选要操作的数据", "出错", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }

                View_MaintenanceRecordList model = JsonConvert.DeserializeObject<View_MaintenanceRecordList>(gridView1.GetRow(SelectedRows[0]) + "");

                APIResponseData apiResponseData = DeviceManager.Instance.GetModelByEquipmentID(model.EquipmentNo);
                if (!apiResponseData.IsSuccess)
                    throw new Exception(apiResponseData.Message);
                DeviceInformationInfo entity = apiResponseData.ToDeserializeObject<DeviceInformationInfo>();

                // 通过点检表主键ID获取点检表并保存到缓存目录
                page_DriveMaintenance view = new page_DriveMaintenance(entity, model.PlanPrimaryID, model.AutoID, true);
                DialogResult dr = view.ShowDialog();
                if (dr == DialogResult.OK)
                    XtraMessageBoxHelper.Info("操作成功！");

                else if (dr == DialogResult.Abort)
                {
                    XtraMessageBoxHelper.Info(view.apiResponseData.Message);
                }
            }
            catch (Exception ex)
            {
                GetDatas();
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        /// <summary>
        /// 搜索
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            GetDatas();
        }


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