using DevExpress.XtraBars;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using DeviceRepair.Models;
using DeviceRepair.Models.Common;
using DeviceRepair.Models.Enum;
using DeviceRepair.Utils;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
using TsSFCDevice.Client.Biz.Base.Utils;
using TsSFCDevice.Client.Biz.Impl;

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

        private CurrentYearPlanSchedule CounterModel;

        public IList<AnnualMaintenancePlan> Datas { get; set; }

        AnnualMaintenancePlan m_CurrentModel;

        /// <summary>
        /// 计划年份
        /// </summary>
        private int parYear
        {
            get
            {
                DateTime m_CurrentYear = DateTime.Today;
                DateTime.TryParse(baripsPlanYear.EditValue + "", out m_CurrentYear);
                return m_CurrentYear.Year <= 1900 ? DateTime.Today.Year : m_CurrentYear.Year;
            }
        }

        /// <summary>
        /// 设备编号
        /// </summary>
        private string parEquipmentID { get { return baripsEquipmentID.EditValue + ""; } }

        int Counter = 0;
        #endregion

        #region 函数

        public pageDevicePlanView()
        {
            InitializeComponent();
        }

        #endregion

        #region 事件

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

            baripsPlanYear.EditValue = DateTime.Today;

            // 关闭列头右键菜单
            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_PLAN_Watch))
            {
                barSearch.Visibility = BarItemVisibility.Never;
            }


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


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


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


            if (!Utility.SystemRuntimeInfo.AuthValidate(OperationAuthConstValue.PM_PLAN_DELETE))
            {
                barRemove.Visibility = BarItemVisibility.Never;
            }
            #endregion
        }

        /// <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 gridView_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
            GridView view = sender as GridView;

            if (e.RowHandle >= 0)
            {
                string fileName = e.Column.FieldName + "Status";
                AnnualMaintenancePlan item = view.GetRow(e.RowHandle) as AnnualMaintenancePlan;

                if (item.GetType().GetProperty(fileName) == null)
                    return;

                EnumPlanCompleteStatus value = (EnumPlanCompleteStatus)item.GetType().GetProperty(fileName).GetValue(item, null);
                switch (value)
                {
                    case EnumPlanCompleteStatus.None:
                        break;
                    case EnumPlanCompleteStatus.TimeOut:
                        e.Appearance.BackColor = Color.FromArgb(255, 126, 126);
                        break;
                    case EnumPlanCompleteStatus.Complete:
                        e.Appearance.BackColor = Color.FromArgb(192, 255, 192);
                        break;
                    case EnumPlanCompleteStatus.Current:
                        e.Appearance.BackColor = Color.FromArgb(255, 255, 129);
                        break;
                    case EnumPlanCompleteStatus.Future:
                        break;
                    default:
                        break;
                }
            }
        }

        /// <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 AnnualMaintenancePlan;
            if (e.Button == MouseButtons.Right)
            {
                contextMenuStrip1.Show(gridControl, e.Location);
                return;
            }

            if (m_CurrentModel != null)
            {
                barEdit.Enabled = true;
                barRemove.Enabled = true;
            }
        }

        /// <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 ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                if (m_CurrentModel == null)
                    throw new Exception("请选中要操作的设备数据行！");

                using (PagePlanDetail view = new PagePlanDetail(m_CurrentModel, m_CurrentModel.MaintenanceYear, EnumDeviceBelong.PM))
                {
                    view.ShowDialog();
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        /// <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 barExport_ItemClick(object sender, ItemClickEventArgs e)
        {
            barExport.Enabled = false;
            try
            {
                FolderBrowserDialog dlg = new FolderBrowserDialog();
                if (dlg.ShowDialog(this) == DialogResult.OK)
                {
                    string path = dlg.SelectedPath.ToString();

                    try
                    {
                        splashScreenManager1.ShowWaitForm();
                        PlanRepository planDa = new PlanRepository();
                        List<View_YearsMaintenancePlansExport> lst = PlanRepository.Instance.Get_PM_PLAN_Xlsx(parYear)?.ToList();// PlanManager.Instance.ExportXlsxDatas(parYear);
                        if (lst == null)
                        {
                            throw new Exception("数据为空，无法导出。");
                        }

                        if (!parEquipmentID.IsNull())
                        {
                            lst = lst.Where(x => x.EquipmentID == parEquipmentID).ToList();
                        }

                        IWorkbook workbook = new XSSFWorkbook();
                        ISheet sheet = workbook.CreateSheet($"{parYear}年度设备PM计划");

                        // 样式获取
                        ICellStyle headStyle = Common.NpoiExtend.StyleConst.Instance.HeadStyle(workbook);
                        ICellStyle contentStyle = Common.NpoiExtend.StyleConst.Instance.ContentStyle(workbook);

                        // 创建表头
                        IRow headerRow = sheet.CreateRow(0);
                        PropertyInfo[] properties = typeof(View_YearsMaintenancePlansExport).GetProperties();
                        for (int i = 0; i < properties.Length; i++)
                        {
                            DisplayNameAttribute[] attrs =
                                (DisplayNameAttribute[])properties[i]
                                    .GetCustomAttributes(typeof(DisplayNameAttribute), true);
                            if (attrs[0].DisplayName.Equals("RootName", StringComparison.CurrentCultureIgnoreCase))
                            {
                                continue;
                            }
                            ICell cell = headerRow.CreateCell(i);
                            cell.SetCellValue(attrs[0].DisplayName);

                            ICellStyle styleContent = workbook.CreateCellStyle();
                            styleContent.CloneStyleFrom(headStyle);

                            headerRow.GetCell(i).CellStyle = styleContent;
                            headerRow.GetCell(i).CellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Medium;
                            headerRow.GetCell(i).CellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Medium;
                            headerRow.GetCell(i).CellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Medium;
                            headerRow.GetCell(i).CellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Medium;
                        }

                        // 填充数据
                        for (int rowIndex = 0; rowIndex < lst.Count; rowIndex++)
                        {
                            IRow dataRow = sheet.CreateRow(rowIndex + 1);
                            for (int colIndex = 0; colIndex < properties.Length; colIndex++)
                            {
                                DisplayNameAttribute[] attrs =
                                (DisplayNameAttribute[])properties[colIndex]
                                    .GetCustomAttributes(typeof(DisplayNameAttribute), true);
                                if (attrs[0].DisplayName.Equals("RootName", StringComparison.CurrentCultureIgnoreCase))
                                {
                                    continue;
                                }

                                ICell cell = dataRow.CreateCell(colIndex);
                                object value = properties[colIndex].GetValue(lst[rowIndex]);

                                if (properties[colIndex].PropertyType == typeof(DateTime))
                                {
                                    DateTime date = ((DateTime)value);
                                    value = DateTime.MinValue == date ? "" : date.ToString("yyyy-MM");
                                }

                                cell.SetCellValue(value + "");

                                ICellStyle styleContent = workbook.CreateCellStyle();
                                styleContent.CloneStyleFrom(contentStyle);
                                dataRow.GetCell(colIndex).CellStyle = styleContent;

                                // 第一列
                                if (colIndex == 0)
                                    dataRow.GetCell(colIndex).CellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Medium;
                                else if (colIndex == properties.Length - 2)
                                {
                                    // 最后一列
                                    dataRow.GetCell(colIndex).CellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Medium;
                                }

                                if (rowIndex == properties.Length - 2)
                                    dataRow.GetCell(colIndex).CellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Medium;
                            }
                        }

                        for (int i = 0; i < properties.Length; i++)
                        {
                            sheet.AutoSizeColumn(i);
                        }

                        using (FileStream fs = new FileStream(Path.Combine(path, $"KH{parYear}年度设备保养计划-{DateTime.Now.ToString("yyyyMMddhhmmssfff")}.xlsx"),
                                   FileMode.Create, FileAccess.Write))
                        {
                            workbook.Write(fs);
                        }
                        splashScreenManager1.TryCloseWait();
                        XtraMessageBoxHelper.Info("操作成功！");
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
            catch (Exception ex)
            {
                splashScreenManager1.TryCloseWait();
                XtraMessageBoxHelper.Error(ex.Message, "出错");
            }

            barExport.Enabled = true;
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barInsert_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (!Utility.SystemRuntimeInfo.AuthValidate(OperationAuthConstValue.PM_PLAN_Edit))
            {
                XtraMessageBoxHelper.Error("当前账号缺少此操作的权限！");
                return;
            }

            try
            {
                if (new pageDevicePlanEdit(EnumDeviceBelong.PM, new AnnualMaintenancePlan { MaintenanceYear = parYear }).ShowDialog(this) == DialogResult.OK)
                {
                    InitializeGridData();
                    if (Counter > 0)
                    {
                        gridView1_RowCellClick(gridControl, new RowCellClickEventArgs(new DevExpress.Utils.DXMouseEventArgs(MouseButtons.Left, 1, 1, 1, 1), (Counter - 1), titleEquipmentID));
                        gridView1.FocusedRowHandle = (Counter - 1);
                    }
                    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_PLAN_Edit))
            {
                XtraMessageBoxHelper.Error("当前账号缺少此操作的权限！");
                return;
            }

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

            try
            {
                if (new pageDevicePlanEdit(EnumDeviceBelong.PM, m_CurrentModel).ShowDialog(this) == DialogResult.OK)
                {
                    InitializeGridData();
                    if (Counter > 0)
                    {
                        gridView1_RowCellClick(gridControl, new RowCellClickEventArgs(new DevExpress.Utils.DXMouseEventArgs(MouseButtons.Left, 1, 1, 1, 1), 0, titleEquipmentID));
                        gridView1.FocusedRowHandle = 0;
                    }
                    XtraMessageBoxHelper.Info("操作成功!");
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message, "出错");
            }
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barRemove_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (!Utility.SystemRuntimeInfo.AuthValidate(OperationAuthConstValue.PM_PLAN_DELETE))
            {
                XtraMessageBoxHelper.Error("当前账号缺少此操作的权限！");
                return;
            }

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

            try
            {
                if (XtraMessageBoxHelper.Ask($"<size=16>确认删除{m_CurrentModel.MaintenanceYear}年度计划 <color=blue><b>设备:{m_CurrentModel.EquipmentName}({m_CurrentModel.DisplayEquipmentID})<b/><color/> 吗？") == DialogResult.OK)
                {
                    APIResponseData apiResponseData = PlanRepository.Instance.Del_PM_PLAN(m_CurrentModel.EquipmentID, m_CurrentModel.MaintenanceYear, EnumDeviceBelong.PM.ToString());
                    if (!apiResponseData.IsSuccess)
                    {
                        throw new Exception(apiResponseData.Message);
                    }

                    var Item = (gridView1.DataSource as List<AnnualMaintenancePlan>).FirstOrDefault(x => x.EquipmentID == m_CurrentModel.EquipmentID && x.MaintenanceYear == m_CurrentModel.MaintenanceYear);
                    if (Item != null)
                    {
                        (gridView1.DataSource as List<AnnualMaintenancePlan>).Remove(Item);
                    }
                    gridView1.RefreshData();

                    if (((gridView1.DataSource as List<AnnualMaintenancePlan>)?.Count ?? 0) > 0)
                    {
                        gridView1_RowCellClick(this.gridView1, new RowCellClickEventArgs(new DevExpress.Utils.DXMouseEventArgs(MouseButtons.Left, 1, 1, 1, 1), 0, titleEquipmentID));
                    }

                    XtraMessageBoxHelper.Info(apiResponseData.Message);
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message, "出错");
            }
        }

        /// <summary>
        /// 模板导入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barImport_ItemClick(object sender, ItemClickEventArgs e)
        {
            try
            {
                if (!Utility.SystemRuntimeInfo.AuthValidate(OperationAuthConstValue.PM_PLAN_Import))
                {
                    XtraMessageBoxHelper.Error("当前账号缺少此操作的权限！");
                    return;
                }

                using (pagePlanImport view = new pagePlanImport())
                {
                    if (view.ShowDialog(this) == DialogResult.OK)
                    {
                        XtraMessageBoxHelper.Info("操作成功！");
                        InitializeGridData();
                    }
                }
            }
            catch (Exception ex)
            {
                InitializeGridData();
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }
        #endregion

        #region 方法

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

                m_CurrentModel = null;
                CounterModel = new CurrentYearPlanSchedule();

                // 获取维修数据
                Datas = PlanRepository.Instance.Get_PM_PLAN_Datas(parEquipmentID, parYear);

                // 如果搜索框为空，则将数据源设置为当前年份的维修数据
                if (!parEquipmentID.IsNull())
                {
                    gridControl.DataSource = Datas.Where(x => x.DisplayEquipmentID == parEquipmentID)?.ToList();
                }
                else
                {
                    gridControl.DataSource = Datas?.ToList();
                }


                // 设置行号列宽度
                IList<AnnualMaintenancePlan> ViewData = (gridView1.DataSource as IList<AnnualMaintenancePlan>);

                Counter = ViewData?.Count ?? 0;
                if (Counter > 0)
                {
                    SizeF size = this.CreateGraphics().MeasureString(Datas.Count.ToString(), this.Font);
                    gridView1.IndicatorWidth = Convert.ToInt32(size.Width) + 20;
                    CounterModel = new CurrentYearPlanSchedule(ViewData);
                    gridView1.FocusedRowHandle = 0;
                    gridView1_RowCellClick(gridView1, new RowCellClickEventArgs(new DevExpress.Utils.DXMouseEventArgs(MouseButtons.Left, 1, 1, 1, 1), 0, titleEquipmentID));
                }

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

        void ShowScheduler()
        {
            CounterModel.CalcTotal();
            barScheduler.Caption = CounterModel.ToString();
        }

        #endregion

    }
}