using DevExpress.XtraEditors;
using DevExpress.XtraSplashScreen;
using DeviceRepair.Models;
using DeviceRepair.Models.Enum;
using DeviceRepairAndOptimization.Biz;
using DeviceRepairAndOptimization.Common;
using DeviceRepairAndOptimization.Pages.Plan;
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.Linq;
using System.Reflection;
using System.Threading;
using System.Windows.Forms;

namespace DeviceRepairAndOptimization.Pages
{
    public partial class page_MaintenancePlan : FormBase
    {
        public List<AnnualMaintenancePlan> Datas { get; set; }

        AnnualMaintenancePlan CurrentModel;

        #region 函数

        public page_MaintenancePlan()
        {
            InitializeComponent();

            gridView1.RowCellStyle += GridView1_RowCellStyle;
        }

        /// <summary>
        /// 单元格变色
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        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;
                }
            }
        }

        #endregion

        #region 方法

        /// <summary>
        /// 初始化加载数据
        /// </summary>
        void InitializeGridData()
        {
            Datas = PlanManager.Instance.GetDatas();
            int Years = EditYear.Text.IsNullOrWhiteSpace() ? DateTime.Today.Year : Convert.ToInt32(EditYear.Text);

            if (EditSearch.Text.IsNullOrWhiteSpace())
            {
                gridControl.DataSource = Datas.Where(x => x.MaintenanceYear == Years)?.ToList();
            }
            else
            {
                gridControl.DataSource = Datas.Where(x => x.MaintenanceYear == Years && (x.DisplayEquipmentID == EditSearch.Text || x.EquipmentName.Contains(EditSearch.Text)))?.ToList();
            }

            gridView1.RowCellClick += GridView1_RowCellClick;
        }

        private void GridView1_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                CurrentModel = gridView1.GetRow(e.RowHandle) as AnnualMaintenancePlan;
                contextMenuStrip1.Show(gridControl, e.Location);
                return;
            }
        }

        #endregion

        #region 事件

        private void page_MaintenancePlan_Load(object sender, EventArgs e)
        {
            try
            {
                splashScreenManager1.ShowWaitForm();
                //this.tb_pnl_Content.RowStyles[0].Height = 45f;
                this.EditSearch.Height = 31;
                EditYear.ToYearStyle();
                this.EditYear.Properties.NullValuePrompt = DateTime.Today.Year + "";
                //btn_Import.Size = new Size(44, 44);
                //btn_Import.Location = new Point(btn_Import.Location.X, 0);
                //btn_Export.Size = new Size(44, 44);
                //btn_Export.Location = new Point(btn_Export.Location.X, 0);
                //lb_Caption.Size = new Size(lb_Caption.Width, 44);
                //lb_Caption.Location = new Point(lb_Caption.Location.X, 0);
                InitializeGridData();
                splashScreenManager1.TryCloseWait();
            }
            catch (Exception ex)
            {
                splashScreenManager1.TryCloseWait();
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

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

                using (page_PlanExcelImport dia = new page_PlanExcelImport())
                {
                    if (dia.ShowDialog() == DialogResult.OK)
                    {
                        Invoke(new Action(() => { InitializeGridData(); }));
                        XtraMessageBoxHelper.Info("操作成功！");
                    }
                }
            }
            catch (Exception ex)
            {
                Invoke(new Action(() => { InitializeGridData(); }));
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

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

                FolderBrowserDialog dlg = new FolderBrowserDialog();
                if (dlg.ShowDialog() == DialogResult.OK)
                {
                    string path = dlg.SelectedPath.ToString();
                    SplashScreenManager.ShowDefaultWaitForm("数据加载...");

                    try
                    {
                        int Years = EditYear.Text.IsNullOrWhiteSpace() ? DateTime.Today.Year : Convert.ToInt32(EditYear.Text);
                        List<View_YearsMaintenancePlansExport> lst = PlanManager.Instance.ExportXlsxDatas(Years);

                        if (lst == null)
                        {
                            XtraMessageBox.Show("数据为空，无法导出。", "出错");
                            return;
                        }

                        SplashScreenManager.Default.SetWaitFormCaption("数据加载成功");
                        Thread.Sleep(300);
                        SplashScreenManager.Default.SetWaitFormCaption("Excel生成中");

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

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

                        SplashScreenManager.Default.SetWaitFormCaption("Sheet数据填充");
                        // 填充数据
                        for (int rowIndex = 0; rowIndex < lst.Count; rowIndex++)
                        {
                            IRow dataRow = sheet.CreateRow(rowIndex + 1);
                            for (int colIndex = 0; colIndex < properties.Length; colIndex++)
                            {
                                ICell cell = dataRow.CreateCell(colIndex);
                                object value = properties[colIndex].GetValue(lst[rowIndex]);
                                cell.SetCellValue(value + "");
                            }
                        }

                        SplashScreenManager.Default.SetWaitFormCaption("正在保存");

                        using (FileStream fs =
                               new FileStream(
                                   Path.Combine(path,
                                       $"{Years}年度OEM设备PM计划-{DateTime.Now.ToString("yyyyMMddhhmmssfff")}.xlsx"),
                                   FileMode.Create, FileAccess.Write))
                        {
                            workbook.Write(fs);
                            SplashScreenManager.Default.SetWaitFormCaption("保存成功");
                            SplashScreenManager.CloseDefaultWaitForm();
                        }
                    }
                    catch (Exception ex)
                    {
                        XtraMessageBox.Show(ex.Message, "出错");
                    }
                }
            }
            catch (Exception ex)
            {
                SplashScreenManager.CloseDefaultWaitForm();
                XtraMessageBox.Show(ex.Message, "出错");
            }
        }

        /// <summary>
        /// 搜索查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void EditSearch_TextChanged(object sender, EventArgs e)
        {
            //int Years = EditYear.Text.IsNullOrWhiteSpace() ? DateTime.Today.Year : Convert.ToInt32(EditYear.Text);
            //gridControl.DataSource = Datas.Where(x => x.MaintenanceYear == Years &&
            //                                         (x.DisplayEquipmentID.Contains(EditSearch.Text) ||
            //                                          x.EquipmentName.Contains(EditSearch.Text) ||
            //                                          x.Remarks.Contains(EditSearch.Text)))?.ToList();
        }

        private void EditYear_EditValueChanged(object sender, EventArgs e)
        {
            int Years = EditYear.Text.IsNullOrWhiteSpace() ? DateTime.Today.Year : Convert.ToInt32(EditYear.Text);
            gridControl.DataSource = Datas.Where(x => x.MaintenanceYear == Years)?.ToList();
        }

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

                AnnualMaintenancePlan model = (AnnualMaintenancePlan)gridView1.GetFocusedRow();
                if (model == null)
                {
                    throw new Exception("请先选择要编辑的行！");
                }

                if (new page_PlanEdit(model).ShowDialog() == DialogResult.OK)
                {
                    XtraMessageBox.Show("操作成功!", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                InitializeGridData();
            }
            catch (Exception ex)
            {
                InitializeGridData();
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

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

                int Years = EditYear.Text.IsNullOrWhiteSpace() ? DateTime.Today.Year : Convert.ToInt32(EditYear.Text);

                if (new page_PlanEdit(new AnnualMaintenancePlan { MaintenanceYear = Years }).ShowDialog() == DialogResult.OK)
                {
                    XtraMessageBox.Show("操作成功!", "信息", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    InitializeGridData();
                }
            }
            catch (Exception ex)
            {
                InitializeGridData();
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        private void btn_delete_Click(object sender, EventArgs e)
        {
            try
            {
                if (!GlobalInfo.HasRole("BIZ_PLAN_DELETE"))
                {
                    throw new Exception($"当前账号缺少此操作的权限");
                }

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

                if (XtraMessageBox.Show("确认删除该条数据？", "信息", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    SplashScreenManager.ShowDefaultWaitForm("提交中", "请稍等...");


                    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("当前计划下存在保养数据，无法删除。");
                        }
                    }

                    if (PlanManager.Instance.DeleteByYearAndEquipmentPk(model.MaintenanceYear, model.EquipmentID).Code > 0)
                    {
                        SplashScreenManager.Default.SetWaitFormCaption("操作成功！");
                    }
                    else
                    {
                        SplashScreenManager.Default.SetWaitFormCaption("操作失败，请重试！");
                    }

                    InitializeGridData();

                    // 关闭等待窗口
                    SplashScreenManager.CloseDefaultWaitForm();
                }
            }
            catch (Exception ex)
            {
                InitializeGridData();

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

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

        #endregion

        /// <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 pageDevicePlans(CurrentModel.EquipmentID,CurrentModel.MaintenanceYear)).ShowDialog();

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