using DevExpress.XtraBars;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using DeviceRepair.Models;
using DeviceRepair.Models.Enum;
using DeviceRepair.Models.Tag;
using DeviceRepairAndOptimization.Common;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using TsSFCDevice.Control.CustomFormatProvider;
using System.Linq;
using NPOI.XSSF.UserModel;
using NPOI.SS.UserModel;
using System.Reflection;
using System.IO;
using System.ComponentModel;

namespace DeviceRepairAndOptimization.Pages.Tag
{
    public partial class TagFormView : DevExpress.XtraBars.Ribbon.RibbonForm
    {
        private TagRecordInfo m_CurrentObject;

        private TagRecordFilter _filter;
        public TagRecordFilter filter
        {
            get
            {
                if (_filter == null)
                    _filter = new TagRecordFilter();
                _filter.EquipmentDisPlayID = barIpsEquipmentID.EditValue + "";
                _filter.TagFormStatus = TagStatus;
                _filter.sDate = StartDate;
                _filter.eDate = EndDate;
                return _filter;
            }
        }

        /// <summary>
        /// 设备编号
        /// </summary>
        public string EquipmentNo { get { return barIpsEquipmentID.EditValue + ""; } }

        /// <summary>
        /// Tag 状态
        /// </summary>
        public string TagStatus
        {
            get
            {
                string status = "";
                switch (barIpsStatus.EditValue + "")
                {
                    case "已提交":
                        status = "N";
                        break;
                    case "已完成":
                        status = "C";
                        break;
                    default:
                        break;
                }
                return status;
            }
        }

        /// <summary>
        /// 开始时间
        /// </summary>
        public DateTime StartDate
        {
            get
            {
                DateTime t = DateTime.Today.AddMonths(-1);
                DateTime.TryParse(barIpsStartDate.EditValue + "", out t);
                return t;
            }
            set
            {
                barIpsStartDate.EditValue = value;
            }
        }

        /// <summary>
        /// 结束数据
        /// </summary>
        public DateTime EndDate
        {
            get
            {
                DateTime t = DateTime.Today.AddDays(1).AddMilliseconds(-1);
                DateTime.TryParse(barIpsEndDate.EditValue + "", out t);
                return t;
            }
            set
            {
                barIpsEndDate.EditValue = value;
            }
        }

        public TagFormView()
        {
            InitializeComponent();
        }

        private void TagFormView_Load(object sender, EventArgs e)
        {
            #region 控件右键菜单屏蔽

            ribbonControl1.AllowCustomization = false;
            ribbonControl1.AllowMinimizeRibbon = false;
            ribbonControl1.ShowCustomizationMenu += (ss, ee) => { ee.ShowCustomizationMenu = false; };
            gridView1.OptionsMenu.EnableColumnMenu = false;

            #endregion

            #region 初始化搜索字段

            StartDate = DateTime.Today.AddMonths(-1);
            EndDate = DateTime.Today.AddDays(1).AddMilliseconds(-1);

            #endregion

            #region 表格样式初始化

            gridView1.OptionsBehavior.Editable = false;
            gridView1.OptionsBehavior.ReadOnly = true;

            gridView1.OptionsSelection.EnableAppearanceFocusedCell = false;
            gridView1.OptionsScrollAnnotations.ShowSelectedRows = DevExpress.Utils.DefaultBoolean.False;
            gridView1.OptionsSelection.ShowCheckBoxSelectorInColumnHeader = DevExpress.Utils.DefaultBoolean.False;
            gcStatus.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom;
            gcStatus.DisplayFormat.Format = new StatusFormatter();
            gcStatus.DisplayFormat.FormatString = "tag";

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

            #endregion

        }

        /// <summary>
        /// 自增长行号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridView_CustomDrawRowIndicator(object sender, 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;
            }
        }

        List<TagRecordInfo> tags;
        /// <summary>
        /// 初始化数据
        /// </summary>
        private void InitializeDataSource()
        {
            try
            {
                if (!GlobalInfo.HasRole(AuthCodeConstValue.BIZ_TAG_01))
                {
                    XtraMessageBoxHelper.Error($"当前账号缺少此操作的权限");
                    return;
                }

                if (filter.sDate > filter.eDate)
                    throw new Exception("开始时间无法大于结束时间!");

                APIResponseData apiResponseData = Biz.TagManager.Instance.GetDatas(filter);
                if (!apiResponseData.IsSuccess)
                    throw new Exception(apiResponseData.Message);

                tags = apiResponseData.ToDeserializeObject<List<TagRecordInfo>>();

                SizeF size = this.CreateGraphics().MeasureString((tags.Count).ToString(), gridView1.Appearance.ViewCaption.Font);
                gridView1.IndicatorWidth = Convert.ToInt32(size.Width) + 25;

                gridControl1.DataSource = tags;
                gridView_RowCellClick(gridView1, new RowCellClickEventArgs(new DevExpress.Utils.DXMouseEventArgs(MouseButtons.Left, 1, 1, 1, 1), 0, gcTagNo));
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        /// <summary>
        /// 单元格点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridView_RowCellClick(object sender, RowCellClickEventArgs e)
        {
            try
            {
                if (e.Button != MouseButtons.Right)
                {
                    m_CurrentObject = gridView1.GetRow(e.RowHandle) as TagRecordInfo;
                    if (m_CurrentObject != null)
                    {
                        string status = m_CurrentObject.TagFormStatus;
                        if (status == "N")
                        {
                            btnMainte.Enabled = true;
                            btnExportXlsx.Enabled = false;
                            btnExportPdf.Enabled = false;
                            btnPrint.Enabled = false;
                            btnEdit.Enabled = true;
                        }
                        else if (status == "C")
                        {
                            btnMainte.Enabled = false;
                            btnExportXlsx.Enabled = true;
                            btnExportPdf.Enabled = true;
                            btnPrint.Enabled = true;
                            btnEdit.Enabled = false;
                        }

                        if (!xueTagForm1.Visible)
                            xueTagForm1.Visible = true;

                        xueTagForm1.CurrentData = m_CurrentObject;
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        /// <summary>
        /// 数据查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnQuery_ItemClick(object sender, ItemClickEventArgs e)
        {
            // 数据加载
            InitializeDataSource();
        }

        /// <summary>
        /// 接受/维修
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnMainte_ItemClick(object sender, ItemClickEventArgs e)
        {
            try
            {
                if (!GlobalInfo.HasRole(AuthCodeConstValue.BIZ_TAG_02))
                {
                    XtraMessageBoxHelper.Error($"当前账号缺少此操作的权限");
                    return;
                }

                if (m_CurrentObject == null)
                {
                    XtraMessageBoxHelper.Error($"请选择要操作的数据!");
                    return;
                }

                using (Common.pageSignature view = new Common.pageSignature())
                {
                    view.AuthString = "BIZ_TAG_02";
                    view.ConfirmContent = $"Tag表单接收确认";
                    view.ConfirmModel = UserConfirmModel.TagReceipt;
                    view.CanNa = false;
                    view.NeedNotes = true;
                    if (view.ShowDialog() == DialogResult.OK)
                    {
                        m_CurrentObject.ReceiptDetailsOfIssue = view.ConfirmNotes;
                        APIResponseData apiResponseData = Biz.TagManager.Instance.Receipt(m_CurrentObject, view.OperationResult.Operation, view.OperationResult.OperationName, view.OperateBy);
                        if (!apiResponseData.IsSuccess)
                            throw new Exception(apiResponseData.Message);

                        TagRecordInfo Rtn = apiResponseData.ToDeserializeObject<TagRecordInfo>();

                        m_CurrentObject.ReceiptDetailsOfIssue = Rtn.ReceiptDetailsOfIssue;
                        m_CurrentObject.ReceiptBy = Rtn.ReceiptBy;
                        m_CurrentObject.ReceiptName = Rtn.ReceiptName;
                        m_CurrentObject.ReceiptOn = Rtn.ReceiptOn;
                        m_CurrentObject.TagFormStatus = Rtn.TagFormStatus;

                        btnMainte.Enabled = false;
                        btnExportXlsx.Enabled = true;
                        btnExportPdf.Enabled = true;
                        btnPrint.Enabled = true;

                        foreach (TagRecordInfo item in tags)
                        {
                            if (item.AutoID == m_CurrentObject.AutoID)
                            {
                                item.ReceiptDetailsOfIssue = m_CurrentObject.ReceiptDetailsOfIssue;
                                item.ReceiptBy = m_CurrentObject.ReceiptBy;
                                item.ReceiptName = m_CurrentObject.ReceiptName;
                                item.ReceiptOn = m_CurrentObject.ReceiptOn;
                                item.TagFormStatus = m_CurrentObject.TagFormStatus;
                                break;
                            }
                        }

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

        DataTable GeneratePrintData(TagRecordInfo tag)
        {
            try
            {
                DataTable table = new DataTable("TagData");
                table.Columns.Add("NO", typeof(string));
                table.Columns.Add("DATE", typeof(string));
                table.Columns.Add("EquipNo", typeof(string));
                table.Columns.Add("EquipName", typeof(string));
                table.Columns.Add("TaggedBy", typeof(string));
                table.Columns.Add("Broken", typeof(bool));
                table.Columns.Add("Access", typeof(bool));
                table.Columns.Add("Clean", typeof(bool));
                table.Columns.Add("Inspect", typeof(bool));
                table.Columns.Add("Missing", typeof(bool));
                table.Columns.Add("Source", typeof(bool));
                table.Columns.Add("Notinuser", typeof(bool));
                table.Columns.Add("Notneeded", typeof(bool));
                table.Columns.Add("Unsafe", typeof(bool));
                table.Columns.Add("Details", typeof(string));
                table.Columns.Add("ReceiptDate", typeof(string));
                table.Columns.Add("Receipt", typeof(string));

                DataRow dataRow = table.NewRow();
                dataRow["NO"] = tag.AutoID;
                dataRow["DATE"] = tag.CreatOn.ToString("yyyy.MM.dd");
                dataRow["EquipNo"] = tag.EquipmentDisPlayID;
                dataRow["EquipName"] = tag.EquipmentName;
                dataRow["TaggedBy"] = tag.CreatorName;
                dataRow["Broken"] = tag.BrokenDamaged;
                dataRow["Access"] = tag.Access;
                dataRow["Clean"] = tag.Clean;
                dataRow["Inspect"] = tag.Inspect;
                dataRow["Missing"] = tag.MissingComponents;
                dataRow["Source"] = tag.SourceOfContamination;
                dataRow["Notinuser"] = tag.NotInUse;
                dataRow["Notneeded"] = tag.NotNeeded;
                dataRow["Unsafe"] = tag.UnsafeConditions;
                dataRow["Details"] = tag.DetailsOfIssue + Environment.NewLine + tag.ReceiptDetailsOfIssue;
                dataRow["ReceiptDate"] = tag.ReceiptOn.Value.ToString("yyyy.MM.dd");
                dataRow["Receipt"] = tag.ReceiptName;
                table.Rows.Add(dataRow);
                return table;
            }
            catch (Exception)
            {
                throw;
            }
        }

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

                if (m_CurrentObject == null)
                {
                    throw new Exception("请选择要打印的数据！");
                }

                DataTable dataTable = GeneratePrintData(m_CurrentObject);

                FastReport.Report report = new FastReport.Report();
                var vLabelDir = System.IO.Path.Combine(Application.StartupPath, "Labels");

                //判断文件夹是否存在
                if (!System.IO.Directory.Exists(vLabelDir))
                {
                    throw new Exception("缺少待打印的标签模板目录！");
                }

                //路径拼接模板文件名
                var vFileName = System.IO.Path.Combine(vLabelDir, "Red_Tag.frx");

                //判断模板文件是否存在
                if (!System.IO.File.Exists(vFileName))
                {
                    throw new Exception("缺少待打印的标签模板文件！");
                }

                report.Load(vFileName);
                report.DoublePass = true;
                DataSet dsDatas = new DataSet();
                dsDatas.Tables.Add(dataTable);

                report.RegisterData(dsDatas, "TagData");

                if (report.Prepare(true))
                {
                    report.ShowPrepared();
                }
                report.Dispose();
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
            btnPrint.Enabled = true;
        }

        /// <summary>
        /// 导出PDF
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnExportPdf_ItemClick(object sender, ItemClickEventArgs e)
        {
            btnExportPdf.Enabled = false;
            try
            {
                if (!GlobalInfo.HasRole(AuthCodeConstValue.BIZ_TAG_03))
                {
                    XtraMessageBoxHelper.Error($"当前账号缺少此操作的权限");
                    return;
                }

                if (m_CurrentObject == null)
                {
                    throw new Exception("请选择要打印的数据！");
                }

                using (XtraSaveFileDialog saveFileDialog = new XtraSaveFileDialog()
                {
                    Filter = "pdf（*.pdf）|*.pdf",
                    Title = "导出pdf"
                })
                {
                    if (saveFileDialog.ShowDialog(this) == DialogResult.OK)
                    {
                        string selectedPath = saveFileDialog.FileName;
                        DataTable dataTable = GeneratePrintData(m_CurrentObject);

                        FastReport.Report report = new FastReport.Report();
                        var vLabelDir = System.IO.Path.Combine(Application.StartupPath, "Labels");

                        //判断文件夹是否存在
                        if (!System.IO.Directory.Exists(vLabelDir))
                        {
                            throw new Exception("缺少待打印的标签模板目录！");
                        }

                        //路径拼接模板文件名
                        var vFileName = System.IO.Path.Combine(vLabelDir, "Red_Tag.frx");

                        //判断模板文件是否存在
                        if (!System.IO.File.Exists(vFileName))
                        {
                            throw new Exception("缺少待打印的标签模板文件！");
                        }

                        report.Load(vFileName);
                        report.DoublePass = true;
                        DataSet dsDatas = new DataSet();
                        dsDatas.Tables.Add(dataTable);

                        report.RegisterData(dsDatas, "TagData");

                        if (report.Prepare(true))
                        {
                            FastReport.Export.Pdf.PDFExport pdfExport = new FastReport.Export.Pdf.PDFExport();
                            report.Export(pdfExport, selectedPath);
                        }
                        report.Dispose();
                        XtraMessageBoxHelper.Info("导出成功！");
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
            btnExportPdf.Enabled = true;
        }

        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 btnEdit_ItemClick(object sender, ItemClickEventArgs e)
        {
            try
            {
                if (m_CurrentObject == null)
                {
                    TsSFCDevice.Control.XtraMessageBoxHelper.Error($"请选择要操作的数据!");
                    return;
                }

                if (!GlobalInfo.HasRole(AuthCodeConstValue.BIZ_TAG_04))
                {
                    XtraMessageBoxHelper.Error($"当前账号缺少此操作的权限");
                    return;
                }

                if (m_CurrentObject.TagFormStatus != "N")
                {
                    TsSFCDevice.Control.XtraMessageBoxHelper.Error($"当前状态的表单无法修改!");
                    return;
                }

                var vCtlTemp = new TsSFCDevice.Control.Tag.xueTagForm() { Dock = DockStyle.Fill, Size = new Size(480, 850) };
                vCtlTemp.HideReceipt();

                Form f = new Form() { Text = "Tag 修改", Size = new Size(530, 700), StartPosition = FormStartPosition.CenterScreen, WindowState = FormWindowState.Normal };
                DevExpress.Utils.Layout.StackPanel sp = new DevExpress.Utils.Layout.StackPanel() { Dock = DockStyle.Bottom, Height = 70, Padding = new Padding(10), LayoutDirection = DevExpress.Utils.Layout.StackPanelLayoutDirection.RightToLeft };
                SidePanel sp2 = new SidePanel() { Dock = DockStyle.Fill };

                SimpleButton add = new SimpleButton { Text = "Tag修改", Width = 120, Height = 38 };
                SimpleButton cancel = new SimpleButton { Text = "取消", Width = 120, Height = 38 };

                vCtlTemp.CurrentData = m_CurrentObject;
                vCtlTemp.TagDataSaved += VCtlTemp_DataSaved;
                cancel.Click += (ss, ee) => { f.Close(); };
                add.Click += (ss, ee) =>
                {
                    if (!vCtlTemp.CanClose())
                        return;
                    f.Close();
                };
                f.Controls.Add(sp2);
                f.Controls.Add(sp);
                sp2.Controls.Add(vCtlTemp);
                sp.Controls.Add(cancel);
                sp.Controls.Add(add);
                f.ShowDialog(this);
            }
            catch (Exception ex)
            {
                TsSFCDevice.Control.XtraMessageBoxHelper.Error(ex.Message);
                return;
            }
        }

        private void VCtlTemp_DataSaved(TagRecordInfo tag)
        {
            try
            {
                splashScreenManager1.ShowWaitForm();
                APIResponseData apiResponseData = Biz.TagManager.Instance.Edit(tag);

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

                TagRecordInfo tagRecord = apiResponseData.ToDeserializeObject<TagRecordInfo>();
                if (tags == null)
                {
                    tags = new List<TagRecordInfo>();
                    gridControl1.DataSource = tags;
                }

                TagRecordInfo item = tags.FirstOrDefault(x => x.AutoID == tagRecord.AutoID);
                if (item != null)
                {
                    item.EquipmentID = tagRecord.EquipmentID;
                    item.EquipmentDisPlayID = tagRecord.EquipmentDisPlayID;
                    item.EquipmentName = tagRecord.EquipmentName;
                    item.BrokenDamaged = tagRecord.BrokenDamaged;
                    item.Access = tagRecord.Access;
                    item.Clean = tagRecord.Clean;
                    item.Inspect = tagRecord.Inspect;
                    item.SourceOfContamination = tagRecord.SourceOfContamination;
                    item.NotInUse = tagRecord.NotInUse;
                    item.NotNeeded = tagRecord.NotNeeded;
                    item.UnsafeConditions = tagRecord.UnsafeConditions;
                    item.MissingComponents = tagRecord.MissingComponents;
                    item.DetailsOfIssue = tagRecord.DetailsOfIssue;
                    item.TagFormStatus = tagRecord.TagFormStatus;
                    item.CreateBy = tagRecord.CreateBy;
                    item.CreatOn = tagRecord.CreatOn;
                    item.CreatorName = tagRecord.CreatorName;
                    item.ModifyBy = tagRecord.ModifyBy;
                    item.ModifyOn = tagRecord.ModifyOn;
                    item.ModifyName = tagRecord.ModifyName;
                    item.ReceiptBy = tagRecord.ReceiptBy;
                    item.ReceiptOn = tagRecord.ReceiptOn;
                    item.ReceiptName = tagRecord.ReceiptName;
                    item.ReceiptDetailsOfIssue = tagRecord.ReceiptDetailsOfIssue;
                }
                else
                {
                    tags.Add(tagRecord);
                }

                gridView1.RefreshData();
                gridView1.FocusedRowHandle = gridView1.RowCount - 1;
                gridView1.SelectRow(gridView1.RowCount - 1);
                gridView_RowCellClick(gridView1, new RowCellClickEventArgs(new DevExpress.Utils.DXMouseEventArgs(MouseButtons.Left, 1, 1, 1, 1), (gridView1.RowCount - 1), gcTagNo));

                splashScreenManager1.TryCloseWait();
                TsSFCDevice.Control.XtraMessageBoxHelper.Info("操作成功!");
            }
            catch (Exception ex)
            {
                splashScreenManager1.TryCloseWait();
                TsSFCDevice.Control.XtraMessageBoxHelper.Error(ex.Message);
            }
        }

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

                FolderBrowserDialog dlg = new FolderBrowserDialog();
                if (dlg.ShowDialog(this) == DialogResult.OK)
                {
                    string path = dlg.SelectedPath.ToString();
                    try
                    {
                        splashScreenManager1.ShowWaitForm();
                        APIResponseData apiResponseData = Biz.TagManager.Instance.GetDatas(filter);
                        if (!apiResponseData.IsSuccess)
                            throw new Exception(apiResponseData.Message);

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

                        IWorkbook workbook = new XSSFWorkbook();
                        ISheet sheet = workbook.CreateSheet($"Tag");

                        // 样式获取
                        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(TagRecordInfo).GetProperties();

                        int _colIndex = 0;
                        int ColLastIndex = 0;
                        for (int i = 0; i < properties.Length; i++)
                        {
                            DisplayNameAttribute[] attrs =
                                (DisplayNameAttribute[])properties[i]
                                    .GetCustomAttributes(typeof(DisplayNameAttribute), true);
                            if (attrs == null || attrs.Length == 0)
                            {
                                continue;
                            }

                            ICell cell = headerRow.CreateCell(_colIndex);
                            cell.SetCellValue(attrs[0].DisplayName);

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

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

                        ColLastIndex = _colIndex ;
                        // 填充数据
                        for (int rowIndex = 0; rowIndex < Datas.Count; rowIndex++)
                        {
                            IRow dataRow = sheet.CreateRow(rowIndex + 1);
                            _colIndex = 0;

                            for (int i = 0; i < properties.Length; i++)
                            {
                                DisplayNameAttribute[] attrs =
                                (DisplayNameAttribute[])properties[i]
                                    .GetCustomAttributes(typeof(DisplayNameAttribute), true);
                                if (attrs == null || attrs.Length == 0)
                                {
                                    continue;
                                }

                                ICell cell = dataRow.CreateCell(_colIndex);
                                object value = properties[i].GetValue(Datas[rowIndex]);

                                if (properties[i].PropertyType == typeof(DateTime))
                                {
                                    DateTime date = ((DateTime)value);
                                    if (DateTime.MinValue == date)
                                    {
                                        value = "";
                                    }
                                    else
                                    {
                                        value = date.ToString("yyyy.MM.dd");
                                    }
                                }

                                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 == ColLastIndex)
                                {
                                    // 最后一列
                                    dataRow.GetCell(_colIndex).CellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Medium;
                                }

                                //if (rowIndex == ColLastIndex)
                                //    dataRow.GetCell(_colIndex).CellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Medium;

                                _colIndex++;
                            }
                        }

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

                        using (FileStream fs =
                               new FileStream(
                                   Path.Combine(path,
                                       $"Tag-{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);
            }
        }
    }
}
