using DeviceRepair.Models;
using DeviceRepair.Models.Enum;
using DeviceRepairAndOptimization.Biz.AM;
using DeviceRepairAndOptimization.Common;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Windows.Forms;

namespace DeviceRepairAndOptimization.Pages.AM.Plan
{
    public partial class pageAmMaintenancePlanView : FormBase
    {
        AnnualMaintenancePlan CurrentModel;

        public int PlanYear
        {
            get
            {
                return teYear.DateTime.Year;
            }
        }

        public string FilterText
        {
            get
            {
                return txtFilter.EditValue + "";
            }
        }


        public pageAmMaintenancePlanView()
        {
            InitializeComponent();

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

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

            gridView1.CustomDrawRowIndicator += GridView1_CustomDrawRowIndicator;
        }

        private void pageAmMaintenancePlanView_Load(object sender, EventArgs e)
        {
            try
            {

                // 绑定行点击事件
                gridView1.RowCellClick += GridView1_RowCellClick;

                splashScreenManager1.ShowWaitForm();

                GridDataInitialize();

                splashScreenManager1.TryCloseWait();
            }
            catch (Exception ex)
            {
                splashScreenManager1.TryCloseWait();

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

        void GridDataInitialize()
        {
            try
            {
                // 获取维修数据
                APIResponseData apiResponseData = PlanManager.Instance.GetDatas(FilterText, PlanYear);

                if (!apiResponseData.IsSuccess)
                    throw new Exception(apiResponseData.Message);

                List<AnnualMaintenancePlan> Datas = apiResponseData.ToDeserializeObject<List<AnnualMaintenancePlan>>();

                gridControl1.BeginUpdate();
                gridControl1.DataSource = null;
                gridControl1.DataSource = Datas;
                gridControl1.EndUpdate();

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

                if (Datas != null && Datas.Count > 0)
                    GridView1_RowCellClick(this.gridView1, new DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs(new DevExpress.Utils.DXMouseEventArgs(MouseButtons.Left, 1, 1, 1, 1), 0, gcDisplayEquipmentID));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 单元格点击事件 - 显示右键菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void GridView1_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            CurrentModel = gridView1.GetRow(e.RowHandle) as AnnualMaintenancePlan;
            if (e.Button == MouseButtons.Right)
            {
                contextMenuStrip1.Show(gridControl1, e.Location);
                return;
            }
        }

        /// <summary>
        /// 右键菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {
            try
            {
                if (CurrentModel == null)
                    throw new Exception("请选中要操作的设备数据行！");

                (new PagePlanDetail(CurrentModel, CurrentModel.MaintenanceYear)).ShowDialog(this);

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

        /// <summary>
        /// 搜索
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtFilter_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            try
            {
                splashScreenManager1.ShowWaitForm();

                GridDataInitialize();

                splashScreenManager1.TryCloseWait();
            }
            catch (Exception ex)
            {
                splashScreenManager1.TryCloseWait();

                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

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

                AnnualMaintenancePlan model = (AnnualMaintenancePlan)gridView1.GetFocusedRow();
                if (model == null)
                {
                    XtraMessageBoxHelper.Error("请先选择要删除的行！");
                    return;
                }

                if (XtraMessageBoxHelper.AskYesNo("确认删除该条数据？") == DialogResult.Yes)
                {
                    splashScreenManager1.ShowWaitForm();

                    APIResponseData apiResponseData = PlanManager.Instance.GetPlanRecordProgress(model.EquipmentID, model.MaintenanceYear);
                    if (apiResponseData.IsSuccess)
                    {
                        List<PlanProgress> progress = apiResponseData.ToDeserializeObject<List<PlanProgress>>();
                        if (progress != null && progress.Count > 0)
                        {
                            throw new Exception("当前计划下存在保养数据，无法删除。");
                        }
                    }

                    apiResponseData = PlanManager.Instance.DeleteByYearAndEquipmentPk(model.MaintenanceYear, model.EquipmentID);

                    if (!apiResponseData.IsSuccess)
                        throw new Exception(apiResponseData.Message);

                    GridDataInitialize();
                    splashScreenManager1.TryCloseWait();
                    XtraMessageBoxHelper.Info("操作成功！");
                }
            }
            catch (Exception ex)
            {
                GridDataInitialize();

                // 关闭等待窗口
                splashScreenManager1.TryCloseWait();
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        /// <summary>
        /// 数据导出
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExport_Click(object sender, EventArgs e)
        {
            try
            {
                if (!GlobalInfo.HasRole(AuthCodeConstValue.BIZ_PLAN_AM_05))
                {
                    XtraMessageBoxHelper.Error($"当前账号缺少此操作的权限");
                    return;
                }

                FolderBrowserDialog dlg = new FolderBrowserDialog();
                if (dlg.ShowDialog(this) == DialogResult.OK)
                {
                    string path = dlg.SelectedPath.ToString();

                    try
                    {
                        splashScreenManager1.ShowWaitForm();
                        APIResponseData apiResponseData = PlanManager.Instance.ExportXlsxDatas(PlanYear);
                        if (!apiResponseData.IsSuccess)
                            throw new Exception(apiResponseData.Message);

                        List<View_YearsMaintenancePlansExport> lst = apiResponseData.ToDeserializeObject<List<View_YearsMaintenancePlansExport>>();
                        if (lst == null || lst.Count == 0)
                            throw new Exception("数据为空，无法导出。");


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

                        // 样式获取
                        ICellStyle headStyle = DeviceRepairAndOptimization.Common.NpoiExtend.StyleConst.Instance.HeadStyle(workbook);
                        ICellStyle contentStyle = DeviceRepairAndOptimization.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);
                                    if (DateTime.MinValue == date)
                                    {
                                        value = "";
                                    }
                                    else
                                    {
                                        value = date.ToString("yyyy-MM");
                                    }
                                }

                                cell.SetCellValue(value + "");

                                //int columnWidth = sheet.GetColumnWidth(colIndex) / 256;
                                //int length = System.Text.Encoding.Default.GetBytes(cell.ToString()).Length;
                                //columnWidth = columnWidth < length ? length : columnWidth;

                                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,
                                       $"OEM{PlanYear}年度设备保养计划-{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);
            }
        }

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

                if (new pageDevicePlanEdit(new AnnualMaintenancePlan { MaintenanceYear = PlanYear }).ShowDialog(this) == DialogResult.OK)
                {
                    XtraMessageBoxHelper.Info("操作成功!");
                    GridDataInitialize();
                }
            }
            catch (Exception ex)
            {
                GridDataInitialize();
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnEdit_Click(object sender, EventArgs e)
        {
            try
            {
                if (!GlobalInfo.HasRole(AuthCodeConstValue.BIZ_PLAN_AM_02))
                {
                    throw new Exception($"当前账号缺少此操作的权限");
                }

                if (CurrentModel == null)
                {
                    throw new Exception($"没有选择内容");
                }

                if (new pageDevicePlanEdit(CurrentModel).ShowDialog(this) == DialogResult.OK)
                {
                    GridDataInitialize();
                    XtraMessageBoxHelper.Info("操作成功!");
                }
            }
            catch (Exception ex)
            {
                GridDataInitialize();
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        /// <summary>
        /// 导入
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnImport_Click(object sender, EventArgs e)
        {
            try
            {
                if (!GlobalInfo.HasRole(AuthCodeConstValue.BIZ_PLAN_AM_04))
                {
                    throw new Exception($"当前账号缺少此操作的权限");
                }

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

        private void gridView1_RowCellStyle(object sender, DevExpress.XtraGrid.Views.Grid.RowCellStyleEventArgs e)
        {
            DevExpress.XtraGrid.Views.Grid.GridView view = sender as DevExpress.XtraGrid.Views.Grid.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;
                }
            }
        }
    }
}
