using DevExpress.XtraBars.ToolbarForm;
using DeviceRepair.Models;
using DeviceRepair.Models.Common;
using DeviceRepair.Utils;
using DeviceRepairAndOptimization.Biz;
using DeviceRepairAndOptimization.Common;
using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace DeviceRepairAndOptimization.Pages.Maintain
{
    public partial class pageMaintainView : ToolbarForm
    {
        /// <summary>
        /// 设备编号
        /// </summary>
        string Filter_DeviceID
        {
            get { return txt_DeviceID.EditValue.ToString().Trim(); }
        }

        DeviceWarrantyRequestFormFilter _filter;
        DeviceWarrantyRequestFormFilter FilterInfo
        {
            get
            {
                if (_filter == null)
                    _filter = new DeviceWarrantyRequestFormFilter();

                _filter.EquipmentID = EquipmentID;

                if (Filter_Start_Date == DateTime.MinValue)
                    de_StartDate.EditValue = DateTime.Today.AddMonths(-1);
                _filter.StartTime = Filter_Start_Date;

                if (Filter_End_Date == DateTime.MinValue)
                    de_EndDate.EditValue = DateTime.Today.AddDays(1).AddMilliseconds(-1);
                _filter.EndTime = Filter_End_Date.AddDays(1).AddMilliseconds(-1);

                _filter.Status = Filter_Status;
                _filter.DownStatus = Filter_DownStatus;

                return _filter;
            }
        }

        string EquipmentID
        {
            get { return txt_DeviceID.Text.Trim(); }
        }

        /// <summary>
        /// 设备状态
        /// </summary>
        DeviceWarrantyRequestFormStatus Filter_Status
        {
            get { return (DeviceWarrantyRequestFormStatus)((int)(cb_Status.EditValue)); }
        }

        /// <summary>
        /// 设备停机状态
        /// </summary>
        DeviceRunningStatus Filter_DownStatus
        {
            get { return (DeviceRunningStatus)cbbIsDown.SelectedIndex; }
        }

        /// <summary>
        /// 开始时间
        /// </summary>
        DateTime Filter_Start_Date
        {
            get { return Convert.ToDateTime(de_StartDate.EditValue); }
        }

        /// <summary>
        /// 结束时间
        /// </summary>
        DateTime Filter_End_Date
        {
            get { return Convert.ToDateTime(de_EndDate.EditValue); }
        }

        List<LookUpItemModel> lookupMaintenanceStatus;

        int m_SelectedCurrentRowIndex = 0;

        DeviceWarrantyRequestFormView CurrentObjectInfo = null;

        Dictionary<int, string> _UserMapping;
        Dictionary<int, string> UserMapping
        {
            get
            {
                if (_UserMapping == null)
                {
                    try
                    {
                        APIResponseData apiResponseData = UserManager.Instance.GetUserMapping();
                        if (!apiResponseData.IsSuccess)
                            throw new Exception(apiResponseData.Message);
                        _UserMapping = apiResponseData.ToDeserializeObject<Dictionary<int, string>>();
                    }
                    catch (Exception ex)
                    {
                        XtraMessageBoxHelper.Error(ex.Message);
                    }
                }
                return _UserMapping;
            }
        }

        public pageMaintainView()
        {
            InitializeComponent();

            this.Load += PageMaintainView_Load;
        }

        /// <summary>
        /// 程序加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void PageMaintainView_Load(object sender, EventArgs e)
        {
            //ToDescription
            if (lookupMaintenanceStatus == null)
                lookupMaintenanceStatus = new List<LookUpItemModel>();

            foreach (DeviceWarrantyRequestFormStatus item in Enum.GetValues(typeof(DeviceWarrantyRequestFormStatus)))
            {
                lookupMaintenanceStatus.Add(new LookUpItemModel
                {
                    ValueMember = (int)item,
                    DisplayMember = item.ToDescription()
                });
            }

            cbbIsDown.Properties.Items.BeginUpdate();
            foreach (DeviceRunningStatus item in Enum.GetValues(typeof(DeviceRunningStatus)))
            {
                cbbIsDown.Properties.Items.Add(item.ToDescription());
            }
            cbbIsDown.Properties.Items.EndUpdate();
            cbbIsDown.SelectedIndex = 0;

            // 设置显示成员和值成员
            layoutControlGroup4.ViewInfo.OwnerILayoutControl.AllowCustomizationMenu = false;
            Root.ViewInfo.OwnerILayoutControl.AllowCustomizationMenu = false;

            GridViewInitialize(gridView1);

            cb_Status.Properties.DataSource = lookupMaintenanceStatus;
            cb_Status.Properties.DisplayMember = "DisplayMember";
            cb_Status.Properties.ValueMember = "ValueMember";
            cb_Status.Properties.BestFitMode = DevExpress.XtraEditors.Controls.BestFitMode.BestFitResizePopup;
            cb_Status.EditValue = (int)DeviceWarrantyRequestFormStatus.All;

            de_StartDate.EditValue = DateTime.Today.AddMonths(-1);
            de_EndDate.EditValue = DateTime.Today;
        }

        List<DeviceWarrantyRequestFormView> DataSource;

        /// <summary>
        /// 数据加载
        /// </summary>
        void LoadingGridviewDatas()
        {
            try
            {
                splashScreenManager1.ShowWaitForm();
                APIResponseData apiResponseData = MaintenanceManager.Instance.GetDatas(FilterInfo);
                if (!apiResponseData.IsSuccess)
                    throw new Exception(apiResponseData.Message);

                DataSource = apiResponseData.ToDeserializeObject<List<DeviceWarrantyRequestFormView>>();

                foreach (DeviceWarrantyRequestFormView item in DataSource)
                {
                    if (string.IsNullOrWhiteSpace(item.CreatorName))
                    {
                        item.CreatorName = UserMapping.ContainsKey(item.CreatBy.Value) ? UserMapping[item.CreatBy.Value] : "";
                    }
                }


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

                gridControl1.DataSource = null;
                gridControl1.DataSource = DataSource.ToDataTable();
                gridView1.BestFitColumns();
                splashScreenManager1.TryCloseWait();
            }
            catch (Exception ex)
            {
                gridControl1.DataSource = null;
                splashScreenManager1.TryCloseWait();
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

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

            view.BestFitColumns();
        }

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

                SizeF size = e.Graphics.MeasureString((e.RowHandle + 1).ToString(), e.Appearance.Font);
            }
        }

        /// <summary>
        /// 多选框标题修改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridView1_CustomDrawColumnHeader(object sender, DevExpress.XtraGrid.Views.Grid.ColumnHeaderCustomDrawEventArgs e)
        {
            if (e.Column != null && e.Column.Caption == "Selection")
            {
                e.Info.Caption = "选择";
            }
        }

        /// <summary>
        /// 单元格点击
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridView1_RowCellClick(object sender, DevExpress.XtraGrid.Views.Grid.RowCellClickEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                e.Handled = true;
                return;
            }

            if (e.Column.Caption == "Selection")
            {
                if (this.m_SelectedCurrentRowIndex == e.RowHandle && this.gridView1.IsRowSelected(e.RowHandle))
                    this.gridView1.UnselectRow(e.RowHandle);
            }
        }

        /// <summary>
        /// 选择行改变
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridView1_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            bool WaitIsShowBefore = splashScreenManager1.IsSplashFormVisible;

            try
            {
                if (!WaitIsShowBefore)
                    splashScreenManager1.ShowWaitForm();

                if (e.FocusedRowHandle >= 0)
                {
                    m_SelectedCurrentRowIndex = e.FocusedRowHandle;
                    DataRowView drv = gridView1.GetRow(e.FocusedRowHandle) as DataRowView;

                    string AutoID = drv.Row["AutoID"]?.ToString();
                    int intAutoID = 0;
                    if (!int.TryParse(AutoID, out intAutoID) && intAutoID <= 0)
                    {
                        throw new Exception("获取行数据出错，请重试！");
                    }

                    CurrentObjectInfo = DataSource.FirstOrDefault(x => x.AutoID == intAutoID);
                    if (CurrentObjectInfo == null)
                    {
                        throw new Exception("获取行数据出错，请重试！");
                    }

                    //CurrentObjectInfo = gridView1.GetRow(e.FocusedRowHandle) as DeviceWarrantyRequestFormView;

                    btn_Maintain.Enabled = CurrentObjectInfo.MaintaionItems == null || CurrentObjectInfo.MaintaionItems.SubmitBy == 0 ? true : false;
                    btn_ChangeDownStatus.Enabled = CurrentObjectInfo.MaintaionItems == null || CurrentObjectInfo.MaintaionItems?.SubmitBy == 0 ? true : false;

                    // 双重确认
                    btn_Validate.Enabled = false;
                    if (CurrentObjectInfo.MaintaionItems != null && CurrentObjectInfo.MaintaionItems.SubmitBy > 0)
                    {
                        // 技术人员确认
                        if ((GlobalInfo.HasRole("BIZ_FIELD_MAINTENANCE_COMFIRM1") || GlobalInfo.HasRole("BIZ_FIELD_MAINTENANCE_COMFIRM2")) && CurrentObjectInfo.MaintaionItems.ValidateBy == 0)
                        {
                            btn_Validate.Enabled = true;
                            btn_Validate.Tag = "1";
                        }//&& CurrentObjectInfo.MaintaionItems.ValidateBy != GlobalInfo.CurrentUser.AutoID
                        else if (CurrentObjectInfo.MaintaionItems.ValidateBy > 0 && (GlobalInfo.HasRole("BIZ_FIELD_MAINTENANCE_COMFIRM2") || GlobalInfo.HasRole("BIZ_FIELD_MAINTENANCE_COMFIRM3")))
                        {
                            if (CurrentObjectInfo.MaintaionItems.Validate2By == 0)
                            {
                                btn_Validate.Enabled = true;
                                btn_Validate.Tag = "2";
                            }
                        }
                    }

                    simpleButton1.Enabled = CurrentObjectInfo.RestorationConfirmationBy > 0;
                    btn_Export.Enabled = CurrentObjectInfo.RestorationConfirmationBy > 0;

                    #region 加载表单数据

                    ucMaintenance view = new ucMaintenance(CurrentObjectInfo);
                    this.splitContainerControl1.Panel2.Controls.Clear();
                    this.splitContainerControl1.Panel2.Controls.Add(view);
                    view.Show();
                    this.splitContainerControl1.Panel2.Refresh();
                    #endregion

                    #region 修改选定状态
                    if (gridView1.SelectedRowsCount > 0)
                    {
                        for (int i = 0; i < this.gridView1.RowCount; i++)
                        {
                            if (this.gridView1.IsRowSelected(i) && this.gridView1.FocusedRowHandle.ToString().Equals(i.ToString()) == false)
                            {
                                this.gridView1.UnselectRow(i);
                            }
                        }
                    }

                    this.gridView1.SelectRow(e.FocusedRowHandle);
                    #endregion
                }
                else
                {
                    CurrentObjectInfo = null;
                }
                if (!WaitIsShowBefore)
                    splashScreenManager1.CloseWaitForm();
            }
            catch (Exception ex)
            {
                if (!WaitIsShowBefore)
                    splashScreenManager1.CloseWaitForm();
                gridView1.FocusedRowChanged += gridView1_FocusedRowChanged;
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        /// <summary>
        /// 查询数据
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Query_Click(object sender, EventArgs e)
        {
            LoadingGridviewDatas();
        }

        private void splitContainerControl1_SplitterMoved(object sender, EventArgs e)
        {
            this.splitContainerControl1.Panel2.Refresh();
            this.splitContainerControl1.Panel1.Refresh();
        }

        private void pageMaintainView_SizeChanged(object sender, EventArgs e)
        {
            this.Refresh();
        }

        /// <summary>
        /// 维修
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Maintain_Click(object sender, EventArgs e)
        {
            try
            {
                if (CurrentObjectInfo == null)
                {
                    throw new Exception($"请选择要维修的停机单！");
                }

                using (pageMaintainEdit view = new pageMaintainEdit(CurrentObjectInfo))
                {
                    if (view.ShowDialog() == DialogResult.OK)
                    {

                        XtraMessageBoxHelper.Info("操作成功！");
                    }
                    LoadingGridviewDatas();
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        /// <summary>
        /// 双重恢复验证
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Validate_Click(object sender, EventArgs e)
        {
            try
            {
                if (CurrentObjectInfo == null)
                {
                    throw new Exception($"请选择要操作的停机单！");
                }

                if (XtraMessageBoxHelper.Ask($"是否确认当前设备已恢复！") == DialogResult.OK)
                {
                    int t = 0;
                    if (!int.TryParse(btn_Validate.Tag + "", out t) && (t != 1 && t != 2))
                    {
                        throw new Exception($"当前操作员类型获取出错，请重试！");
                    }

                    APIResponseData apiResponseData = MaintenanceManager.Instance.DoubleValidateMaintenance(CurrentObjectInfo.AutoID, t);
                    if (!apiResponseData.IsSuccess)
                        throw new Exception(apiResponseData.Message);
                    XtraMessageBoxHelper.Info("操作成功！");
                    LoadingGridviewDatas();
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        /// <summary>
        /// 修改停机状态
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_ChangeDownStatus_Click(object sender, EventArgs e)
        {
            try
            {
                if (CurrentObjectInfo == null)
                {
                    throw new Exception($"请选择要维修的停机单！");
                }

                if (XtraMessageBoxHelper.Ask($"是否确认将维修单：<color=red>{CurrentObjectInfo.AutoID}</color>的停机状态修改为：<color=blue>{(CurrentObjectInfo.IsDown ? "非停机" : "停机")}</color>状态！") == DialogResult.OK)
                {
                    APIResponseData apiResponseData = MaintenanceManager.Instance.ChangeDownStatus(CurrentObjectInfo.AutoID, !CurrentObjectInfo.IsDown);
                    if (!apiResponseData.IsSuccess)
                        throw new Exception(apiResponseData.Message);
                    XtraMessageBoxHelper.Info("操作成功！");
                    LoadingGridviewDatas();
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        /// <summary>
        /// 打印
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void simpleButton1_Click(object sender, EventArgs e)
        {
            try
            {
                if (CurrentObjectInfo == null)
                {
                    throw new Exception("获取对象失败，请重试！");
                }

                DataTable table = SubassembliesCurrentData();

                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, "DeviceMaintenance.frx");

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

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

                report.RegisterData(dsDatas, "MaintenanceInfo");

                //report.Design();

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

        private DataTable SubassembliesCurrentData()
        {
            DataTable table = new DataTable("MaintenanceInfo");
            table.Columns.Add("申请部门", typeof(string));
            table.Columns.Add("名称", typeof(string));
            table.Columns.Add("设备编号", typeof(string));
            table.Columns.Add("接收部门", typeof(string));
            table.Columns.Add("现象区分", typeof(string));
            table.Columns.Add("故障发生地点", typeof(string));
            table.Columns.Add("故障发生时间", typeof(string));
            table.Columns.Add("维修方式", typeof(string));
            table.Columns.Add("产品批号", typeof(string));
            table.Columns.Add("修理开始日期", typeof(string));
            table.Columns.Add("修理结束日期", typeof(string));
            table.Columns.Add("质量部评估", typeof(string));
            table.Columns.Add("工程部评估", typeof(string));
            table.Columns.Add("总修复时间", typeof(string));
            table.Columns.Add("总停机时间", typeof(string));
            table.Columns.Add("故障现象", typeof(string));
            table.Columns.Add("故障原因", typeof(string));
            table.Columns.Add("维修内容", typeof(string));
            table.Columns.Add("配件", typeof(string));
            table.Columns.Add("人员", typeof(string));
            table.Columns.Add("是否需要再验证", typeof(string));
            table.Columns.Add("验证编号", typeof(string));
            table.Columns.Add("设备恢复确认", typeof(string));
            table.Columns.Add("申请部门确认/日期", typeof(string));

            APIResponseData apiResponseData = FieldsManager.Instance.GetQuery("SymptomlDistinction,Maintenance,Accessories");
            if (!apiResponseData.IsSuccess)
                throw new Exception(apiResponseData.Message);
            List<FieldsInfo> SelectionDatas = apiResponseData.ToDeserializeObject<List<FieldsInfo>>();
            Dictionary<int, FieldsInfo> keyValuePairs = SelectionDatas.ToDictionary(x => x.AutoID, x => x);

            DataRow dr = table.NewRow();
            dr["申请部门"] = $"生产部 - {CurrentObjectInfo.CreatorName}";
            dr["名称"] = CurrentObjectInfo.EquipmentName;
            dr["设备编号"] = CurrentObjectInfo.EquipmentID;
            dr["接收部门"] = "设备实施部";
            dr["现象区分"] = keyValuePairs.ContainsKey(CurrentObjectInfo.MaintaionItems.SymptomlDistinction) ? keyValuePairs[CurrentObjectInfo.MaintaionItems.SymptomlDistinction].FieldText : "";
            dr["故障发生地点"] = CurrentObjectInfo.LocationName;
            dr["故障发生时间"] = CurrentObjectInfo.CreatOn.Value.ToString("yyyy-MM-dd HH:mm:ss");
            dr["维修方式"] = keyValuePairs.ContainsKey(CurrentObjectInfo.MaintaionItems.Maintenance) ? keyValuePairs[CurrentObjectInfo.MaintaionItems.Maintenance].FieldText : "";
            dr["产品批号"] = CurrentObjectInfo.InProduction ? $@"Yes, Product Lot/Testing Order产品批号/检测任务号{Environment.NewLine}{CurrentObjectInfo.Batch}" : "No";
            dr["修理开始日期"] = CurrentObjectInfo.MaintaionItems.MaintainStartTime.ToString("yyyy-MM-dd HH:mm:ss");
            dr["修理结束日期"] = CurrentObjectInfo.MaintaionItems.MaintainEndTime.ToString("yyyy-MM-dd HH:mm:ss");

            if (CurrentObjectInfo.EvaluatorItems != null && CurrentObjectInfo.EvaluatorItems.Count > 0)
            {
                var PEItem = CurrentObjectInfo.EvaluatorItems.Where(x => x.EvaluatorCode == "PE").FirstOrDefault();
                if (PEItem != null)
                {
                    dr["质量部评估"] = $"{PEItem.Description} - {PEItem.CreatorName}";
                }

                var QEItem = CurrentObjectInfo.EvaluatorItems.Where(x => x.EvaluatorCode == "QE").FirstOrDefault();
                if (QEItem != null)
                {
                    dr["工程部评估"] = $"{QEItem.Description} - {QEItem.CreatorName}";
                }
            }

            DateTime FormSubDate = CurrentObjectInfo.CreatOn.Value;
            TimeSpan timeDifference = CurrentObjectInfo.MaintaionItems.MaintainEndTime - CurrentObjectInfo.MaintaionItems.MaintainStartTime;
            dr["总修复时间"] = $"{timeDifference.Days}天/{(timeDifference.Hours)}小时/{(timeDifference.Minutes)}分钟/{timeDifference.Seconds}秒";
            timeDifference = CurrentObjectInfo.MaintaionItems.MaintainEndTime - FormSubDate;
            dr["总停机时间"] = $"{timeDifference.Days}天/{(timeDifference.Hours)}小时/{(timeDifference.Minutes)}分钟/{timeDifference.Seconds}秒";

            dr["故障现象"] = CurrentObjectInfo.FaultSymptoms;
            dr["故障原因"] = CurrentObjectInfo.MaintaionItems.MaintainCause;
            dr["维修内容"] = CurrentObjectInfo.MaintaionItems.MaintainContent;

            //配件
            if (CurrentObjectInfo.MaintaionItems.AccessoriesItems != null && CurrentObjectInfo.MaintaionItems.AccessoriesItems.Count > 0)
            {
                System.Text.StringBuilder builder = new System.Text.StringBuilder();
                foreach (DeviceWarrantyRequestAccessoriesInfo item in CurrentObjectInfo.MaintaionItems.AccessoriesItems)
                {
                    builder.Append($"{item.FieldName} x {item.AccessoriesCount};");
                }
                dr["配件"] = builder.ToString();
            }

            dr["人员"] = UserMapping[CurrentObjectInfo.MaintaionItems.SubmitBy];
            if (CurrentObjectInfo.MaintaionItems.BeValidate)
            {
                dr["是否需要再验证"] = $"Yes   需要，Validation ID验证编号：{CurrentObjectInfo.MaintaionItems.ValidateNo}";
            }
            else
            {
                dr["是否需要再验证"] = $"No    不需要， Rational理由：{CurrentObjectInfo.MaintaionItems.Reason}";
            }

            dr["验证编号"] = "";

            string doubleValidate = "";
            if (CurrentObjectInfo.MaintaionItems.ValidateBy == 0)
            {
                doubleValidate = "N/A";
            }
            else
            {
                doubleValidate = $"{UserMapping[CurrentObjectInfo.MaintaionItems.ValidateBy]} / {CurrentObjectInfo.MaintaionItems.ValidateOn.ToString("yyyy-MM-dd HH:mm:ss")}";

                if (CurrentObjectInfo.MaintaionItems.Validate2By == 0)
                {
                    doubleValidate += "    N/A";
                }
                else
                {
                    doubleValidate += $"    {UserMapping[CurrentObjectInfo.MaintaionItems.Validate2By]} / {CurrentObjectInfo.MaintaionItems.Validate2On.ToString("yyyy-MM-dd HH:mm:ss")}";
                }
            }

            dr["设备恢复确认"] = doubleValidate;
            dr["申请部门确认/日期"] = $"{CurrentObjectInfo.RestorationConfirmationOnName} / { CurrentObjectInfo.RestorationConfirmationOn.Value.ToString("yyyy-MM-dd HH:mm:ss")}";
            table.Rows.Add(dr);
            return table;
        }

        /// <summary>
        /// 导出Word
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Export_Click(object sender, EventArgs e)
        {
            try
            {
                using (FolderBrowserDialog folderDialog = new FolderBrowserDialog())
                {
                    folderDialog.Description = "请选择保存文件的路径：";
                    folderDialog.ShowNewFolderButton = true;

                    DialogResult result = folderDialog.ShowDialog();

                    if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(folderDialog.SelectedPath))
                    {
                        string selectedPath = folderDialog.SelectedPath;

                        if (CurrentObjectInfo == null)
                        {
                            throw new Exception("获取对象失败，请重试！");
                        }

                        DataTable table = SubassembliesCurrentData();

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

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

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

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

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

                        report.RegisterData(dsDatas, "MaintenanceInfo");
                        string filePath = Path.Combine(selectedPath, ("维修单" + CurrentObjectInfo.AutoID + ".docx"));
                        if (report.Prepare())
                        {
                            FastReport.Export.OoXML.Word2007Export export = new FastReport.Export.OoXML.Word2007Export();
                            report.MaxPages = 1;
                            export.CurPage = 1;
                            report.Export(export, filePath);
                        }
                        report.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }
    }
}