using System;
using System.Collections.Generic;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using System.IO;
using DevExpress.XtraSpreadsheet;
using DevExpress.Spreadsheet;
using DevExpress.Utils.Menu;
using DevExpress.XtraSpreadsheet.Menu;
using Newtonsoft.Json;
using DeviceRepair.Models;
using DeviceRepairAndOptimization.Biz.PreserveTemplate;
using DeviceRepairAndOptimization.Common;
using DeviceRepairAndOptimization.Biz;
using DeviceRepair.Utils;
using DeviceRepairAndOptimization.Pages.Maintenance;

namespace DeviceRepairAndOptimization.Pages.DriveMaintenance
{
    [System.Runtime.InteropServices.Guid("CC3F4BA1-1721-48A0-B4DF-184A5BBC9401")]
    public partial class page_DriveMaintenance : XtraForm
    {
        #region 属性

        /// <summary>
        /// 设备对象
        /// </summary>
        private DeviceInformationInfo CurrentDrive;

        /// <summary>
        /// 保养的历史记录
        /// </summary>
        private MaintenanceRecordInfo CurrentModel;

        /// <summary>
        /// 当前表单对象
        /// </summary>
        private MaintenanceFormVersionInfo CurrentFormModel;

        /// <summary>
        /// 当前计划对象
        /// </summary>
        private DriveMaintencePlanInfo CurrentPlanModel;

        /// <summary>
        /// 当前excel格式处理
        /// </summary>
        private TemplateIndexV1 template;

        /// <summary>
        /// 处理的结果
        /// </summary>
        public APIResponseData apiResponseData;

        /// <summary>
        /// 当前的保养类型 - (年、月、日、季度)
        /// </summary>
        private EnumMaintenanceType CurrentType;

        private string CurrentTypeValue = string.Empty;

        /// <summary>
        /// 当前计划表主键ID
        /// </summary>
        private int CurrentPlanID = 0;

        /// <summary>
        /// sheet
        /// </summary>
        public Worksheet worksheet
        {
            get
            {
                return spreadsheetControl1.Document.Worksheets.ActiveWorksheet;
            }
        }

        /// <summary>
        /// 最大行下标
        /// </summary>
        private int LastUsedRowIndex
        {
            get
            {
                return worksheet.Rows.LastUsedIndex;
            }
        }

        /// <summary>
        /// 最大列下标
        /// </summary>
        private int LastUsedColumnIndex
        {
            get
            {
                return worksheet.GetUsedRange().ColumnCount - 1;
            }
        }

        /// <summary>
        /// 当前编辑的单元格
        /// </summary>
        private Cell CurrentCell;

        /// <summary>
        /// 服务器时间
        /// </summary>
        DateTime CurrentDate;

        int MaintenanceAutoID = 0;
        bool isAdmin = false;
        int FileAutoID = 0;
        bool MustPic = false;

        #endregion

        #region 右键菜单

        /// <summary>
        ///  签名
        /// </summary>
        private SpreadsheetPopupMenu _popupOperation;
        SpreadsheetPopupMenu popupOperation
        {
            get
            {
                if (_popupOperation == null)
                {
                    _popupOperation = new SpreadsheetPopupMenu()
                    {
                        Caption = "签名",
                        Items =
                        {
                             new DXMenuItem("签名",(s,e)=> { CurrentCell.Value = GlobalInfo.CurrentUser.RealName; template.Operation.WriteValue(CurrentCell); } ),
                             new DXMenuItem("清空",(s,e)=> { CurrentCell.Value = "";template.Operation.WriteValue(CurrentCell);} ),
                        }
                    };
                }
                return _popupOperation;
            }
        }

        /// <summary>
        /// 正文
        /// </summary>
        private SpreadsheetPopupMenu _popupContent;
        SpreadsheetPopupMenu popupContent
        {
            get
            {
                if (_popupContent == null)
                {
                    _popupContent = new SpreadsheetPopupMenu()
                    {
                        Caption = "正文",
                        Items =
                        {
                            new DXMenuItem("正常",(s,e)=>{CurrentCell.Value = "√"; template.Content.WriteValue(CurrentCell);} ),
                            new DXMenuItem("紧固",(s,e)=>{CurrentCell.Value = "N"; template.Content.WriteValue(CurrentCell);} ),
                            new DXMenuItem("给油",(s,e)=>{CurrentCell.Value = "U"; template.Content.WriteValue(CurrentCell);} ),
                            new DXMenuItem("清洁",(s,e)=>{CurrentCell.Value = "C"; template.Content.WriteValue(CurrentCell);} ),
                            new DXMenuItem("修理",(s,e)=>{CurrentCell.Value = "R"; template.Content.WriteValue(CurrentCell);} ),
                            new DXMenuItem("调整",(s,e)=>{CurrentCell.Value = "T"; template.Content.WriteValue(CurrentCell);} ),
                            new DXMenuItem("替换",(s,e)=>{CurrentCell.Value = "H"; template.Content.WriteValue(CurrentCell);} ),
                            new DXMenuItem("有问题/异常",(s,e)=>{CurrentCell.Value = (CurrentFormModel.VersionCode == "FM-P0079.02" ? "X":"△");  template.Content.WriteValue(CurrentCell);} ),
                            new DXMenuItem("不适用或无生产",(s,e)=>{CurrentCell.Value = "N/A";  template.Content.WriteValue(CurrentCell);} ),
                            new DXMenuItem("清空",(s,e)=>{CurrentCell.Value = "";  template.Content.WriteValue(CurrentCell);} ),
                        }
                    };
                }
                return _popupContent;
            }
        }

        /// <summary>
        /// 其他异常处理
        /// </summary>
        private SpreadsheetPopupMenu _popupException;
        SpreadsheetPopupMenu popupException
        {
            get
            {
                if (_popupException == null)
                {
                    _popupException = new SpreadsheetPopupMenu()
                    {
                        Caption = "其他异常处理",
                        Items =
                        {
                             new DXMenuItem("编辑",(a,aa)=>
                             {
                                // 显示输入框
                                string result = XtraInputBox.Show("其它异常处理:", "输入框", "");

                                 // 设置单元格的文本格式
                                CurrentCell.BeginUpdate();
                                CurrentCell.Alignment.Vertical = SpreadsheetVerticalAlignment.Top;
                                CurrentCell.Alignment.Horizontal = SpreadsheetHorizontalAlignment.Left;
                                CurrentCell.EndUpdate();
                                CurrentCell.Value += result;

                                template.ExceptionDescription.WriteValue(CurrentCell);
                             } ),
                        }
                    };
                }
                return _popupException;
            }
        }

        /// <summary>
        /// 操作时间
        /// </summary>
        private SpreadsheetPopupMenu _popupDate;
        SpreadsheetPopupMenu popupDate
        {
            get
            {
                if (_popupDate == null)
                {
                    _popupDate = new SpreadsheetPopupMenu()
                    {
                        Caption = "操作时间",
                        Items =
                        {
                              //new DXMenuItem("时间",(a,aa)=>
                              //{
                              //    // 创建 DateEdit 控件
                              //   DateEdit dateEdit = new DateEdit(){ Width = 800,Height = 320 };
                              //   dateEdit.Properties.CalendarView = DevExpress.XtraEditors.Repository.CalendarView.Fluent;
                              
                              //   // 弹出式日期选择框
                              //   if (XtraDialog.Show(dateEdit, "选择日期", MessageBoxButtons.OKCancel) == DialogResult.OK)
                              //   {
                              //       // 用户点击了确定按钮，获取选定的日期
                              //       DateTime selectedDate = dateEdit.DateTime;
                              //       CurrentCell.Value = selectedDate.ToString("yyyy年MM月dd日");
                              //       template.OperationDate.WriteValue(CurrentCell);
                              //   }
                              //} ),
                              new DXMenuItem("时间",(a,aa)=> {
                                  CurrentCell.Value = DateTime.Now.ToString("yyyy-MM-dd");
                                  template.OperationDate.WriteValue(CurrentCell);
                              }),
                               new DXMenuItem("清空",(a,aa)=>
                              {
                                  CurrentCell.Value = "";
                                  template.OperationDate.WriteValue(CurrentCell);
                              } ),
                        }
                    };
                }
                return _popupDate;
            }
        }

        Dictionary<EnumMaintenanceCellType, Func<SheetDataItem, bool>> EditCondition = new Dictionary<EnumMaintenanceCellType, Func<SheetDataItem, bool>>();

        #endregion

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="PlanAutoID"></param>
        public page_DriveMaintenance(DeviceInformationInfo entity, int PlanAutoID = 0, int RecordID = 0, bool isAdminEdit = false)
        {
            InitializeComponent();
            CurrentDrive = entity;
            if (PlanAutoID != 0)
                CurrentPlanID = PlanAutoID;

            if (CurrentDrive == null)
            {
                XtraMessageBoxHelper.Error("设备对象获取出错！");
                DialogResult = DialogResult.Cancel;
            }
            MaintenanceAutoID = RecordID;
            isAdmin = isAdminEdit;
        }

        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Cancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }

        /// <summary>
        /// 提交
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btn_Submit_Click(object sender, EventArgs e)
        {
            // PM内容 验证
            List<SheetDataItem> verifyData = template.Content.Where(x => IsEditor(CurrentType).Contains(x.MaintenanceType) && IsEditorColumns(CurrentType) == x.MaintenanceTypeValue && x.Value == null)?.ToList();
            if (verifyData != null && verifyData.Count > 0)
            {
                // 选定指定单元格
                SheetDataItem item = verifyData[0];
                ScrollToCellRow(item);
                XtraMessageBoxHelper.Error($"存在未填写PM内容！");
                return;
            }

            // 操作人 验证
            verifyData = template.Operation.Where(x => IsEditor(CurrentType, false).Contains(x.MaintenanceType) && IsEditorColumns(x.MaintenanceType) == x.MaintenanceTypeValue && string.IsNullOrWhiteSpace(x.Value + ""))?.ToList();
            if (verifyData != null && verifyData.Count > 0)
            {
                // 选定指定单元格
                SheetDataItem item = verifyData[0];
                ScrollToCellRow(item);
                XtraMessageBoxHelper.Error($"操作人是必填的！");
                return;
            }

            // 操作时间 验证
            verifyData = template.OperationDate.Where(x => IsEditor(CurrentType, false).Contains(x.MaintenanceType) && IsEditorColumns(x.MaintenanceType) == x.MaintenanceTypeValue && string.IsNullOrWhiteSpace(x.Value + ""))?.ToList();
            if (verifyData != null && verifyData.Count > 0)
            {
                // 选定指定单元格
                SheetDataItem item = verifyData[0];
                ScrollToCellRow(item);
                XtraMessageBoxHelper.Error($"操作时间是必填的！");
                return;
            }

            if (MaintenanceAutoID == 0)
            {
                foreach (var item in template.DeviceSpecification)
                {
                    item.Value = CurrentDrive.Specification;
                }

                foreach (var item in template.EquipmentID)
                {
                    item.Value = CurrentDrive.EquipmentID;
                }

                foreach (var item in template.Year)
                {
                    item.Value = CurrentPlanModel.MaintenanceYear;
                }
            }

            MaintenanceRecordInfo mrm = new MaintenanceRecordInfo
            {
                AutoID = MaintenanceAutoID,
                ContentData = JsonConvert.SerializeObject(template),
                CreateBy = GlobalInfo.CurrentUser.AutoID,
                EquipmentID = CurrentDrive.EquipmentID,
                EquipmentPrimaryID = CurrentDrive.AutoID,
                EquipmentName = CurrentDrive.EquipmentName,
                FormPrimaryID = CurrentDrive.MaintenanceFormVersion,
                FormName = CurrentFormModel.FormName,
                FormVersionCode = CurrentFormModel.VersionCode,
                FormVersionRev = CurrentFormModel.VersionRev,
                MYear = DateTime.Today.Year,
                Specification = CurrentDrive.Specification,
                PlanPrimaryID = CurrentPlanModel.AutoID,
                PlanType = CurrentPlanModel.MaintenanceType
            };

            MaintenanceRecordSubmit subData = new MaintenanceRecordSubmit { Record = mrm };

            // 添加图片
            foreach (Control item in imgs_Content.Controls)
            {
                if (item.GetType() == typeof(PictureEdit))
                {
                    byte[] img = ((PictureEdit)item).Image.ImageToByteArray();
                    subData.Imgs.Add(new AttachmentSubmitModel
                    {
                        AutoID = item.Tag == null ? 0 : (int)item.Tag,
                        Datas = img
                    });
                }
            }

            // 添加附件
            if (!string.IsNullOrEmpty(txt_Attr.Text))
            {
                string filePath = txt_Attr.Text;
                byte[] f = File.ReadAllBytes(filePath);
                AttachmentSubmitModel att = new AttachmentSubmitModel();
                att.AutoID = FileAutoID;
                att.Datas = f;
                att.FileName = Path.GetFileName(filePath);
                att.Extension = Path.GetExtension(filePath);
                subData.Files.Add(att);
            }

            if (MustPic && (subData?.Imgs?.Count ?? 0) == 0)
            {
                XtraMessageBoxHelper.Error("缺少保养的照片，请先拍照！");
                return;
            }

            apiResponseData = PreserveManager.Instance.Insertable(subData);
            if (apiResponseData.Code == 1)
                this.DialogResult = DialogResult.OK;
            else
                this.DialogResult = DialogResult.Abort;
        }

        /// <summary>
        /// 窗体加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void page_DriveMaintenance_Load(object sender, EventArgs e)
        {
            this.splashScreenManager1.ShowWaitForm();
            try
            {
                CurrentDate = Convert.ToDateTime(ApiHelper.Instance.GetServiceTime());
                if (MaintenanceAutoID != 0)
                {
                    APIResponseData hisRecord = PreserveManager.Instance.GetPreserveRecordItemByPrimaryKey(MaintenanceAutoID);
                    if (hisRecord.Code == -1)
                        throw new Exception(hisRecord.Message);
                    string hisJson = JsonConvert.SerializeObject(hisRecord.Data);
                    CurrentModel = JsonConvert.DeserializeObject<MaintenanceRecordInfo>(hisJson);

                    apiResponseData = CommonManager.Instance.GetAttachments("MaintenanceRecord", "AutoID", CurrentModel.AutoID + "");
                    if (apiResponseData.IsSuccess)
                    {
                        List<AttachmentInfo> atts = apiResponseData.ToDeserializeObject<List<AttachmentInfo>>();

                        foreach (AttachmentInfo item in atts)
                        {
                            if (item.Module.Equals("Image", StringComparison.CurrentCultureIgnoreCase))
                            {
                                Image img = CommonManager.Instance.GetAttaImg(item.AutoID);
                                if (img != null)
                                {
                                    PictureEdit pe = new PictureEdit
                                    {
                                        Tag = item.AutoID,
                                        Image = img,
                                        Width = 45,
                                        Height = 45,
                                    };
                                    pe.Properties.SizeMode = DevExpress.XtraEditors.Controls.PictureSizeMode.Zoom;
                                    pe.PopupMenuShowing += Pe_PopupMenuShowing; ;
                                    Control btn = imgs_Content.Controls.Find("btn_takePhotos", false)?.First();
                                    imgs_Content.Controls.RemoveByKey("btn_takePhotos");
                                    imgs_Content.Controls.Add(pe);
                                    imgs_Content.Controls.Add(btn);
                                }
                            }
                            else
                            {
                                pnl_Atta.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
                                be_atta.Text = item.FileName;
                                layoutControlItem2.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                                FileAutoID = item.AutoID;
                            }
                        }
                    }
                }
                else
                {
                    // 加载历史记录
                    APIResponseData apiResponseData = PreserveManager.Instance.GetPreserveRecordItem(CurrentDrive.AutoID, CurrentDrive.MaintenanceFormVersion);

                    if (apiResponseData.IsSuccess && apiResponseData.Data != null)
                    {
                        //当年存在历史信息
                        string hisJson = JsonConvert.SerializeObject(apiResponseData.Data);
                        CurrentModel = JsonConvert.DeserializeObject<MaintenanceRecordInfo>(hisJson);
                    }
                }

                LoadingTemplate();

                CurrentType = EnumMaintenanceTypeHelper.MatchToEnum(CurrentPlanModel.MaintenanceType);

                if (CurrentFormModel.VersionCode == "FM-P0079.02")
                {
                    template = new TemplateIndexV2(worksheet);
                }
                else
                {
                    template = new TemplateIndexV1(worksheet);
                }


                if (CurrentModel != null)
                    template = JsonConvert.DeserializeObject<TemplateIndexV1>(CurrentModel.ContentData);

                List<EnumMaintenanceCellType> enums = new List<EnumMaintenanceCellType>()
                {
                    // 数据
                    EnumMaintenanceCellType.Content,
                    // 操作人
                    EnumMaintenanceCellType.Operation,
                    // 操作时间
                    EnumMaintenanceCellType.OperationDate,
                    // 其他异常处理
                    EnumMaintenanceCellType.ExceptionDescription
                };

                if (!isAdmin)
                {
                    if (!template.Content.Any(x => x.MaintenanceType == CurrentType))
                    {
                        throw new Exception("当前保养计划与保养表单不匹配！");
                    }

                    List<EnumMaintenanceType> ts = IsEditor(CurrentType);
                    List<string> CurrentTypeValues = new List<string>();
                    foreach (var item in ts)
                    {
                        string ctv = string.Empty;
                        switch (item)
                        {
                            case EnumMaintenanceType.Annual:
                                ctv = "年";
                                break;
                            case EnumMaintenanceType.Monthly:
                                ctv = CurrentDate.Month + "";
                                break;
                            case EnumMaintenanceType.Quarterly:
                                ctv = ((CurrentDate.Month - 1) / 3 + 1) + "";
                                break;
                            case EnumMaintenanceType.Semian:
                                ctv = ((CurrentDate.Month - 1) / 6 + 1) + "";
                                break;
                            case EnumMaintenanceType.None:
                                break;
                            default:
                                break;
                        }
                        if (!string.IsNullOrWhiteSpace(ctv))
                            CurrentTypeValues.Add(ctv);

                    }

                    #region 取值 第几列能编辑

                    switch (CurrentType)
                    {
                        case EnumMaintenanceType.Annual:
                            CurrentTypeValue = "年";
                            break;
                        case EnumMaintenanceType.Monthly:
                            CurrentTypeValue = CurrentDate.Month + "";
                            break;
                        case EnumMaintenanceType.Quarterly:
                            CurrentTypeValue = ((CurrentDate.Month - 1) / 3 + 1) + "";
                            break;
                        case EnumMaintenanceType.Semian:
                            CurrentTypeValue = ((CurrentDate.Month - 1) / 6 + 1) + "";
                            break;
                        case EnumMaintenanceType.None:
                            break;
                        default:
                            break;
                    }

                    if (CurrentTypeValue == string.Empty)
                    {
                        throw new Exception("频次列的值匹配失败！");
                    }

                    #endregion

                    #region 右键弹出菜单规则




                    foreach (EnumMaintenanceCellType item in enums)
                    {
                        if (item == EnumMaintenanceCellType.ExceptionDescription)
                        {
                            EditCondition.Add(item,
                               x => x.ColumnIndex == CurrentCell.ColumnIndex
                               && x.RowIndex == CurrentCell.RowIndex
                               && (x.MaintenanceType == EnumMaintenanceType.None || IsEditor(CurrentType, false).Contains(x.MaintenanceType))
                            );
                            continue;
                        }

                        if (item == EnumMaintenanceCellType.Content)
                        {
                            EditCondition.Add(item,
                            x => x.ColumnIndex == CurrentCell.ColumnIndex
                            && x.RowIndex == CurrentCell.RowIndex
                            && ts.Contains(x.MaintenanceType)
                            && (template.Year.Count == 0 || IsEditorColumns(x.MaintenanceType) == x.MaintenanceTypeValue)
                        );
                        }
                        else
                        {
                            EditCondition.Add(item,
                            x => x.ColumnIndex == CurrentCell.ColumnIndex
                            && x.RowIndex == CurrentCell.RowIndex
                            && IsEditor(CurrentType, false).Contains(x.MaintenanceType)
                            && (template.Year.Count == 0 || IsEditorColumns(x.MaintenanceType) == x.MaintenanceTypeValue)
                        );
                        }
                    }

                    #endregion
                }
                else
                {
                    foreach (EnumMaintenanceCellType item in enums)
                    {
                        if (item == EnumMaintenanceCellType.ExceptionDescription)
                        {
                            EditCondition.Add(item,
                               x => x.ColumnIndex == CurrentCell.ColumnIndex
                               && x.RowIndex == CurrentCell.RowIndex
                            );
                            continue;
                        }

                        EditCondition.Add(item,
                            x => x.ColumnIndex == CurrentCell.ColumnIndex
                            && x.RowIndex == CurrentCell.RowIndex
                        );
                    }
                }


                #region 是否必须照片信息
                apiResponseData = Biz.CommonManager.Instance.GetAllConfigs();
                if (!apiResponseData.IsSuccess)
                    throw new Exception("加载配置信息失败！");
                List<SysConfigInfo> sysConfigs = apiResponseData.ToDeserializeObject<List<SysConfigInfo>>();
                string sMustPic = sysConfigs.FirstOrDefault(x => x.Code == "PRESERVE_PICMUST")?.Value ?? "false";

                if (sMustPic.ToLower() == "true")
                {
                    MustPic = true;
                }
                #endregion
            }
            catch (Exception ex)
            {
                splashScreenManager1.TryCloseWait();
                apiResponseData = new APIResponseData { Code = -1, Message = ex.Message };
                this.DialogResult = DialogResult.Abort;
            }

            spreadsheetControl1.Document.DocumentLoaded += (s, ee) =>
            {
                try
                {
                    //当年不存在历史信息
                    if (CurrentModel == null)
                    {
                        #region 设备型号赋值
                        //设备型号赋值
                        foreach (SheetDataItem item in template.DeviceSpecification)
                        {
                            Cell cell = worksheet.Cells[item.RowIndex, item.ColumnIndex];
                            cell.Value = CurrentDrive.Specification;
                        }
                        #endregion

                        #region 设备编号赋值
                        //设备编号赋值
                        foreach (SheetDataItem item in template.EquipmentID)
                        {
                            Cell cell = worksheet.Cells[item.RowIndex, item.ColumnIndex];
                            cell.Value = CurrentDrive.EquipmentID;
                        }
                        #endregion

                        #region 年份赋值

                        //年份赋值
                        foreach (SheetDataItem item in template.Year)
                        {
                            Cell cell = worksheet.Cells[item.RowIndex, item.ColumnIndex];

                            // 获取单元格的内容
                            RichTextString value = cell.GetRichText();

                            //字符串 分割 -6是为了年份数值的占位
                            int index = value.Text.IndexOf("年");
                            string left = value.Text.Substring(0, index - 6);
                            string right = value.Text.Substring(index);

                            RichTextString nvalue = new RichTextString();
                            string content = $"{DateTime.Today.Year}";
                            nvalue.AddTextRun(left, new RichTextRunFont(cell.Font));
                            nvalue.AddTextRun(content, new RichTextRunFont(cell.Font) { UnderlineType = UnderlineType.Single });
                            nvalue.AddTextRun(right, new RichTextRunFont(cell.Font));

                            cell.BeginUpdate();
                            cell.SetRichText(nvalue);
                            cell.EndUpdate();
                        }

                        #endregion

                        #region 设置右键菜单

                        spreadsheetControl1.MouseDown += (s1, e1) =>
                        {
                            if (e1.Button == MouseButtons.Right)
                            {
                                // 获取鼠标位置对应的单元格
                                Cell cell = spreadsheetControl1.GetCellFromPoint(new PointF(e1.X, e1.Y));

                                // 判断是否为合并单元格
                                if (cell.IsMerged)
                                {
                                    //获取主单元格位置
                                    int top = (cell.GetMergedRanges()[0]).TopRowIndex;
                                    int left = (cell.GetMergedRanges()[0]).LeftColumnIndex;

                                    CurrentCell = worksheet.Cells[top, left];
                                }
                                else
                                {
                                    CurrentCell = cell;
                                }

                                if (EditCondition.ContainsKey(EnumMaintenanceCellType.Operation) && template.Operation.Any(EditCondition[EnumMaintenanceCellType.Operation]))
                                {
                                    // 操作人
                                    popupOperation.ShowPopup(spreadsheetControl1, new Point(e1.X, e1.Y));
                                }
                                else if (EditCondition.ContainsKey(EnumMaintenanceCellType.OperationDate) && template.OperationDate.Any(EditCondition[EnumMaintenanceCellType.OperationDate]))
                                {
                                    // 保养日期
                                    popupDate.ShowPopup(spreadsheetControl1, new Point(e1.X, e1.Y));
                                }
                                else if (EditCondition.ContainsKey(EnumMaintenanceCellType.Content) && template.Content.Any(EditCondition[EnumMaintenanceCellType.Content]))
                                {
                                    // 保养正文
                                    popupContent.ShowPopup(spreadsheetControl1, new Point(e1.X, e1.Y));
                                }
                                else if (EditCondition.ContainsKey(EnumMaintenanceCellType.ExceptionDescription) && template.ExceptionDescription.Any(EditCondition[EnumMaintenanceCellType.ExceptionDescription]))
                                {
                                    // 保养 - 其他异常
                                    popupException.ShowPopup(spreadsheetControl1, new Point(e1.X, e1.Y));
                                }
                            }
                        };

                        #endregion
                    }
                    else
                    {
                        #region 设备型号赋值
                        //设备型号赋值
                        foreach (SheetDataItem item in template.DeviceSpecification)
                        {
                            Cell cell = worksheet.Cells[item.RowIndex, item.ColumnIndex];
                            cell.Value = CurrentModel.Specification;
                        }
                        #endregion

                        #region 设备编号赋值
                        //设备编号赋值
                        foreach (SheetDataItem item in template.EquipmentID)
                        {
                            Cell cell = worksheet.Cells[item.RowIndex, item.ColumnIndex];
                            cell.Value = CurrentModel.EquipmentID;
                        }
                        #endregion

                        #region 年份赋值

                        //年份赋值
                        foreach (SheetDataItem item in template.Year)
                        {
                            Cell cell = worksheet.Cells[item.RowIndex, item.ColumnIndex];

                            // 获取单元格的内容
                            RichTextString value = cell.GetRichText();

                            //字符串 分割 -6是为了年份数值的占位
                            int index = value.Text.IndexOf("年");
                            string left = value.Text.Substring(0, index - 6);
                            string right = value.Text.Substring(index);

                            RichTextString nvalue = new RichTextString();
                            string content = CurrentModel.MYear + "";
                            nvalue.AddTextRun(left, new RichTextRunFont(cell.Font));
                            nvalue.AddTextRun(content, new RichTextRunFont(cell.Font) { UnderlineType = UnderlineType.Single });
                            nvalue.AddTextRun(right, new RichTextRunFont(cell.Font));

                            cell.BeginUpdate();
                            cell.SetRichText(nvalue);
                            cell.EndUpdate();
                        }

                        #endregion

                        #region 正文赋值
                        List<SheetDataItem> datas = template.Content.Where(x => x.Value != null)?.ToList();
                        foreach (SheetDataItem item in datas)
                        {
                            Cell cell = worksheet.Cells[item.RowIndex, item.ColumnIndex];
                            cell.Value = item.Value + "";
                        }
                        #endregion

                        #region 异常赋值
                        datas = template.ExceptionDescription.Where(x => x.Value != null)?.ToList();
                        foreach (SheetDataItem item in datas)
                        {
                            Cell cell = worksheet.Cells[item.RowIndex, item.ColumnIndex];
                            cell.Value = item.Value + "";
                        }
                        #endregion

                        #region 操作人赋值
                        datas = template.Operation.Where(x => x.Value != null)?.ToList();
                        foreach (SheetDataItem item in datas)
                        {
                            Cell cell = worksheet.Cells[item.RowIndex, item.ColumnIndex];
                            cell.Value = item.Value + "";
                        }
                        #endregion

                        #region 操作时间赋值
                        datas = template.OperationDate.Where(x => x.Value != null)?.ToList();
                        foreach (SheetDataItem item in datas)
                        {
                            Cell cell = worksheet.Cells[item.RowIndex, item.ColumnIndex];
                            cell.Value = item.Value + "";
                        }
                        #endregion

                        #region 设置右键菜单

                        spreadsheetControl1.MouseDown += (s1, e1) =>
                        {
                            if (e1.Button == MouseButtons.Right)
                            {
                                // 获取鼠标位置对应的单元格
                                Cell cell = spreadsheetControl1.GetCellFromPoint(new PointF(e1.X, e1.Y));
                                if (cell == null)
                                    return;

                                // 判断是否为合并单元格
                                if (cell.IsMerged)
                                {
                                    //获取主单元格位置
                                    int top = (cell.GetMergedRanges()[0]).TopRowIndex;
                                    int left = (cell.GetMergedRanges()[0]).LeftColumnIndex;

                                    CurrentCell = worksheet.Cells[top, left];
                                }
                                else
                                {
                                    CurrentCell = cell;
                                }

                                if (EditCondition.ContainsKey(EnumMaintenanceCellType.Operation) && template.Operation.Where(EditCondition[EnumMaintenanceCellType.Operation]).Any(x => x.Value == null || isAdmin))
                                {
                                    // 操作人
                                    popupOperation.ShowPopup(spreadsheetControl1, new Point(e1.X, e1.Y));
                                }
                                else if (EditCondition.ContainsKey(EnumMaintenanceCellType.OperationDate) && template.OperationDate.Where(EditCondition[EnumMaintenanceCellType.OperationDate]).Any(x => x.Value == null || isAdmin))
                                {
                                    // 保养日期
                                    popupDate.ShowPopup(spreadsheetControl1, new Point(e1.X, e1.Y));
                                }
                                else if (EditCondition.ContainsKey(EnumMaintenanceCellType.Content) && template.Content.Where(EditCondition[EnumMaintenanceCellType.Content]).Any(x => x.Value == null || isAdmin))
                                {
                                    // 保养正文
                                    popupContent.ShowPopup(spreadsheetControl1, new Point(e1.X, e1.Y));
                                }
                                else if (EditCondition.ContainsKey(EnumMaintenanceCellType.ExceptionDescription) && template.ExceptionDescription.Where(EditCondition[EnumMaintenanceCellType.ExceptionDescription]).Any(x => x.Value == null || isAdmin))
                                {
                                    // 保养 - 其他异常
                                    popupException.ShowPopup(spreadsheetControl1, new Point(e1.X, e1.Y));
                                }
                            }
                        };

                        #endregion
                    }

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

        #region 方法

        /// <summary>
        /// 加载模板
        /// </summary>
        /// <exception cref="Exception"></exception>
        void LoadingTemplate()
        {
            //获取当前计划信息 y
            APIResponseData planData = PreserveManager.Instance.GetPlanAndFormInfo(CurrentPlanID);
            if (planData.Code == -1)
                throw new Exception(planData.Message);

            // 设备保养表单信息
            CurrentFormModel = ((Newtonsoft.Json.Linq.JObject)planData.Data)["form"].ToObject<MaintenanceFormVersionInfo>();

            if (!CurrentFormModel.FormStatus)
                throw new Exception("该设备绑定的点检表已被禁用，不可进入设备保养！");

            // 设备计划表单信息
            CurrentPlanModel = ((Newtonsoft.Json.Linq.JObject)planData.Data)["maintencePlan"].ToObject<DriveMaintencePlanInfo>();

            // 通过点检表主键ID获取点检表并保存到缓存目录
            int @FormVersion = CurrentModel == null ? CurrentDrive.MaintenanceFormVersion : CurrentModel.FormPrimaryID;
            string templatePath = PreserveManager.Instance.GetFileSingle(@FormVersion);
            if (string.IsNullOrWhiteSpace(templatePath))
            {
                throw new Exception("获取点检表文件失败,请联系管理员处理！");
            }


            spreadsheetControl1.LoadDocument(IOExtend.FileToByteArray(templatePath));
            if (spreadsheetControl1.Document.Worksheets.Contains("正文"))
                spreadsheetControl1.Document.Worksheets.ActiveWorksheet = spreadsheetControl1.Document.Worksheets["正文"];
            else
            {
                XtraMessageBox.Show("非标准设备保养表单！", "出错", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.DialogResult = DialogResult.Cancel;
            }

            if (worksheet != null)
            {
                spreadsheetControl1.WorksheetDisplayArea.SetSize(worksheet.Index, LastUsedColumnIndex + 1, LastUsedRowIndex + 1);
            }

            this.spreadsheetControl1.ActiveWorksheet.ActiveView.Zoom = (int)(100 * ComputerHelper.ScaleX);
            //获取Windows显示的缩放比例
            this.Width = (int)(ComputerHelper.WorkingArea.Width * 0.9);
            this.Height = (int)(ComputerHelper.WorkingArea.Height * 0.9) - 200;

            this.Left = (ComputerHelper.WorkingArea.Width - this.Width) / 2;
            this.Top = (ComputerHelper.WorkingArea.Height - this.Height) / 2;

            if (ComputerHelper.ScaleX > 1 || ComputerHelper.ScaleX > 1)
            {
                //开启横向滚动条
                spreadsheetControl1.Options.HorizontalScrollbar.Visibility = SpreadsheetScrollbarVisibility.Visible;
            }
        }

        /// <summary>
        /// 滚动到指定位置
        /// </summary>
        /// <param name="item"></param>
        private void ScrollToCellRow(SheetDataItem item)
        {
            Cell selectedCell = worksheet.Cells[item.RowIndex, item.ColumnIndex];
            spreadsheetControl1.SelectedCell = selectedCell;

            // 将选定的单元格定位到视图中心
            worksheet.ScrollToRow(selectedCell.RowIndex);
        }

        #endregion

        private void btn_takePhotos_Click(object sender, EventArgs e)
        {
            try
            {
                using (DialogControl.CameraDialog d = new DialogControl.CameraDialog())
                {
                    if (d.ShowDialog() == DialogResult.OK)
                    {
                        using (Graphics graphics = Graphics.FromImage(d.CameraImage))
                        {
                            string watermarkText = ApiHelper.Instance.GetServiceTime();
                            if (string.IsNullOrWhiteSpace(watermarkText))
                            {
                                XtraMessageBox.Show("未能获取到服务器时间。", "出错", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                return;
                            }

                            Font watermarkFont = new Font("Arial", 12, FontStyle.Bold);
                            SizeF size = graphics.MeasureString(watermarkText, watermarkFont);
                            Brush watermarkBrush = new SolidBrush(Color.Red);

                            int l = d.CameraImage.Size.Width - (int)size.Width - 30;
                            int h = d.CameraImage.Size.Height - (int)size.Height - 10;
                            graphics.DrawString(watermarkText, watermarkFont, watermarkBrush, new PointF(l, h));
                        }

                        PictureEdit pe = new PictureEdit
                        {
                            Image = d.CameraImage,
                            Width = 45,
                            Height = 45,
                        };
                        pe.Properties.SizeMode = DevExpress.XtraEditors.Controls.PictureSizeMode.Zoom;
                        pe.PopupMenuShowing += Pe_PopupMenuShowing; ;
                        Control btn = imgs_Content.Controls.Find("btn_takePhotos", false)?.First();
                        imgs_Content.Controls.RemoveByKey("btn_takePhotos");
                        imgs_Content.Controls.Add(pe);
                        imgs_Content.Controls.Add(btn);
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "出错", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 图片控件自定义右键菜单
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Pe_PopupMenuShowing(object sender, DevExpress.XtraEditors.Events.PopupMenuShowingEventArgs e)
        {
            // 创建一个新的菜单项
            DXMenuItem customItem = new DXMenuItem("删除", (s, ee) =>
            {
                RemovePictureButton_Click(sender, ee);
            });

            // 将菜单项全部清除,并添加自定义菜单到默认右键菜单中
            e.PopupMenu.Items.Clear();
            e.PopupMenu.Items.Add(customItem);
        }

        /// <summary>
        /// 移除当前照片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void RemovePictureButton_Click(object sender, EventArgs e)
        {
            // 移除当前照片
            imgs_Content.Controls.Remove((Control)sender);
        }

        /// <summary>
        /// 选择上传的PDF文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txt_Attr_Click(object sender, EventArgs e)
        {
            try
            {
                //扩展 - 自定义待选择文件类型
                OpenFileDialog ofd = new OpenFileDialog();
                //自定义待选择文件类型
                ofd.Filter = "PDF|*.pdf;";
                if (ofd.ShowDialog() == DialogResult.OK)
                {
                    txt_Attr.Text = ofd.FileName;
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "出错", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 菜单弹窗控制
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void spreadsheetControl1_PopupMenuShowing(object sender, PopupMenuShowingEventArgs e)
        {
            if (e.MenuType == SpreadsheetMenuType.Cell && string.IsNullOrEmpty(e.Menu.Caption))
                e.Menu = null;

            string tips = string.Empty;
            if (isAdmin)
            {
                tips = "模板数据不可编辑。";
            }
            else if (CurrentType == EnumMaintenanceType.Annual)
            {
                tips = "当前属于年度保养，当前单元格不可填。";
            }
            else if (CurrentType == EnumMaintenanceType.Semian)
            {
                tips = $"当前属于{(CurrentDate.Month < 7 ? "上" : "下")}半年度保养，当前单元格不可填。";
            }
            else if (CurrentType == EnumMaintenanceType.Quarterly)
            {
                tips = $"当前属于第{CurrentTypeValue}季度保养，当前单元格不可填。";
            }
            else if (CurrentType == EnumMaintenanceType.Monthly)
            {
                tips = $"当前属于第{CurrentTypeValue}月保养，当前单元格不可填。";
            }

            XtraMessageBoxHelper.Info(tips);
        }


        private List<EnumMaintenanceType> IsEditor(EnumMaintenanceType t, bool IsCalcYearValue = true)
        {
            List<EnumMaintenanceType> ts = new List<EnumMaintenanceType>();
            if (t == EnumMaintenanceType.Annual)
            {
                ts.Add(EnumMaintenanceType.Annual);
                if (IsCalcYearValue)
                {
                    if (CurrentDate.Year % 2 == 0)
                        ts.Add(EnumMaintenanceType.EvenAnnual);
                    if (CurrentDate.Year % 2 == 1)
                        ts.Add(EnumMaintenanceType.OddAnnual);
                }
                else
                {
                    ts.Add(EnumMaintenanceType.EvenAnnual);
                    ts.Add(EnumMaintenanceType.OddAnnual);
                }

                ts.Add(EnumMaintenanceType.Semian);
                ts.Add(EnumMaintenanceType.Quarterly);
                ts.Add(EnumMaintenanceType.Monthly);
            }
            if (t == EnumMaintenanceType.Semian)
            {
                ts.Add(EnumMaintenanceType.Semian);
                ts.Add(EnumMaintenanceType.Quarterly);
                ts.Add(EnumMaintenanceType.Monthly);
            }
            if (t == EnumMaintenanceType.Quarterly)
            {
                ts.Add(EnumMaintenanceType.Quarterly);
                ts.Add(EnumMaintenanceType.Monthly);
            }
            if (t == EnumMaintenanceType.Monthly)
                ts.Add(EnumMaintenanceType.Monthly);
            return ts;
        }


        private string IsEditorColumns(EnumMaintenanceType t)
        {
            string ts = "";
            switch (t)
            {
                case EnumMaintenanceType.Annual:
                case EnumMaintenanceType.OddAnnual:
                case EnumMaintenanceType.EvenAnnual:
                    ts = "年";
                    break;
                case EnumMaintenanceType.Monthly:
                    ts = CurrentDate.Month + "";
                    break;
                case EnumMaintenanceType.Quarterly:
                    ts = ((CurrentDate.Month - 1) / 3 + 1) + "";
                    break;
                case EnumMaintenanceType.Semian:
                    ts = ((CurrentDate.Month - 1) / 6 + 1) + "";
                    break;
                case EnumMaintenanceType.None:
                    break;
                default:
                    break;
            }

            return ts;
        }

        private void be_atta_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Caption == "删除" && XtraMessageBoxHelper.Ask("是否确定执行删除操作？") == DialogResult.OK)
            {
                pnl_Atta.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
                layoutControlItem2.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Always;
            }
            else if (e.Button.Caption == "查看")
            {
                (new pagePDFView(be_atta.Text, FileAutoID)).ShowDialog();
            }
        }
    }
}