using DevExpress.Spreadsheet;
using DevExpress.Utils.Menu;
using DevExpress.XtraEditors;
using DevExpress.XtraSpreadsheet;
using DeviceRepair.Models;
using DeviceRepair.Models.Enum;
using DeviceRepair.Utils;
using DeviceRepairAndOptimization.Biz;
using DeviceRepairAndOptimization.Biz.PreserveTemplate;
using DeviceRepairAndOptimization.Common;
using DeviceRepairAndOptimization.Pages.Maintenance;
using Newtonsoft.Json;
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.DriveMaintenance
{
    [System.Runtime.InteropServices.Guid("CC3F4BA1-1721-48A0-B4DF-184A5BBC9401")]
    public partial class page_DriveMaintenance : XtraForm
    {
        #region 属性

        Guid CurrentSign = Guid.NewGuid();

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

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

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

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

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

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

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

        private string CurrentTypeValue = string.Empty;

        private EnumMaintenanceBanciType Banci = EnumMaintenanceBanciType.None;

        /// <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>
        private List<Cell> ExCurrentCell = new List<Cell>();

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

        /// <summary>
        /// 保养的计划时间
        /// </summary>
        DateTime CurrentDate;

        public DateTime DaylyMaintenanceDate;

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

        #endregion

        #region 右键菜单

        void WriteValue(EnumMaintenanceCellType CellType, string value, EnumMaintenanceOperationType operationType, bool IsException = false)
        {
            try
            {
                // 获取当前对象的单元格数据
                SheetDataItem item = GetSheetItem(CurrentCell, CellType);

                // 判断是否已提交数据
                if (CurrentType == EnumMaintenanceType.Daily && CellType != EnumMaintenanceCellType.ExceptionDescription && (!CurrentCell.Value.IsEmpty && item.Sign != CurrentSign) && !isAdmin)
                {
                    throw new Exception("当前保养项已被其他人填写,本次操作无法处理!");
                }

                // 添加当前编辑数据标记
                item.Sign = operationType == EnumMaintenanceOperationType.Clear ? Guid.Empty : CurrentSign;

                if (operationType == EnumMaintenanceOperationType.Clear)
                {
                    // 数据清除
                    if (CellType == EnumMaintenanceCellType.ExceptionDescription)
                    {
                        /* 日保养 签字后,清除签名在清除异常会出现找不到班次的清空无法清空 */
                        if (item.Value == null && CurrentType == EnumMaintenanceType.Daily)
                        {
                            IEnumerable<SheetDataItem> items = template.ExceptionDescription.Where(x => x.RowIndex == CurrentCell.RowIndex && x.ColumnIndex == CurrentCell.ColumnIndex && x.Sign == CurrentSign);
                            if (items != null && items.Count() > 0)
                            {
                                foreach (var im in items)
                                {
                                    if (!(im.Value?.ToString() ?? "").IsNull())
                                    {
                                        string OldValue = CurrentCell.Value.TextValue;
                                        CurrentCell.Value = OldValue.Replace(im.Value + "", "");
                                        im.Value = null;
                                    }
                                    else
                                    {
                                        im.Value = null;
                                    }
                                }
                            }
                        }
                        else
                        {
                            if (!(item.Value?.ToString() ?? "").IsNull())
                            {
                                string OldValue = CurrentCell.Value.TextValue;
                                CurrentCell.Value = OldValue.Replace(item.Value + "", "");
                                item.Value = null;
                            }
                            else
                            {
                                item.Value = null;
                            }
                        }
                    }
                    else
                    {
                        if (isAdmin && CellType == EnumMaintenanceCellType.Operation)
                        {
                            /* 修改状态下,不允许更改签名 */
                            throw new ArgumentException("不允许修改保养人签名！");
                        }
                        else if (isAdmin && CellType == EnumMaintenanceCellType.OperationDate)
                        {
                            /* 修改状态下,不允许更改保养日期 */
                            throw new ArgumentException("不允许修改保养日期！");
                        }

                        CurrentCell.Value = CellValue.Empty;
                        item.Value = null;
                    }

                    if (CellType == EnumMaintenanceCellType.Operation)
                    {
                        Banci = EnumMaintenanceBanciType.None;
                    }
                }
                else
                {
                    string ipsValue = value;

                    // 异常处理
                    if (CellType == EnumMaintenanceCellType.ExceptionDescription)
                    {
                        // 显示输入框
                        ipsValue = XtraInputBox.Show("其它异常处理:", "输入框", "");
                        if (((CurrentCell?.Value?.TextValue?.Length ?? 0) + ipsValue.Length) > 4000)
                        {
                            throw new ArgumentException("其它异常处理的内容不能超出4000字！");
                        }
                    }

                    // 正文
                    if (CellType == EnumMaintenanceCellType.Content)
                        ExCellSet(IsException);

                    // 签名
                    if (CellType == EnumMaintenanceCellType.Operation && CurrentType == EnumMaintenanceType.Daily)
                    {
                        if (isAdmin)
                        {
                            /* 修改状态下,不允许更改签名 */
                            XtraMessageBoxHelper.Error("不允许修改保养人签名！");
                            return;
                        }

                        if (!(value + "").IsNull())
                        {
                            if (Banci != EnumMaintenanceBanciType.None)
                            {
                                XtraMessageBoxHelper.Error("每日保养,一次仅能填写一个班次的数据,如填写错误请先清除签名 !");
                                return;
                            }
                            Banci = GetSheetItem(CurrentCell, EnumMaintenanceCellType.Operation)?.BanciType ?? EnumMaintenanceBanciType.None;
                        }
                        else
                        {
                            Banci = EnumMaintenanceBanciType.None;
                        }
                    }

                    // 数据写入
                    if (CellType == EnumMaintenanceCellType.ExceptionDescription)
                    {
                        if (CurrentCell.Value.TextValue.IsNull())
                        {
                            CurrentCell.Value = template.ExceptionFreezeString + ipsValue;
                        }
                        else
                        {
                            CurrentCell.Value = CurrentCell.Value.TextValue + ipsValue;
                        }
                    }
                    else
                    {
                        CurrentCell.Value = ipsValue;
                    }

                    // 设置单元格的文本格式
                    CurrentCell.BeginUpdate();
                    if (CellType == EnumMaintenanceCellType.ExceptionDescription)
                    {
                        CurrentCell.Alignment.WrapText = true;
                        CurrentCell.Alignment.Horizontal = SpreadsheetHorizontalAlignment.Left;
                        CurrentCell.Alignment.Vertical = SpreadsheetVerticalAlignment.Top;
                    }
                    else
                    {
                        CurrentCell.Alignment.Horizontal = SpreadsheetHorizontalAlignment.Center;
                        CurrentCell.Alignment.Vertical = SpreadsheetVerticalAlignment.Center;
                    }
                    CurrentCell.EndUpdate();

                    item.Value = ipsValue;
                }

                if (!string.IsNullOrWhiteSpace(value) && CurrentType == EnumMaintenanceType.Daily)
                {
                    double width = worksheet.Columns[CurrentCell.ColumnIndex].Width;
                    worksheet.Columns[CurrentCell.ColumnIndex].AutoFitColumns();
                    if (worksheet.Columns[CurrentCell.ColumnIndex].Width < width)
                    {
                        worksheet.Columns[CurrentCell.ColumnIndex].Width = width;
                    }
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        void ExCellSet(bool isEx)
        {
            // 如果当前单元格已经存在，且当前单元格不在ExCurrentCell中，则将当前单元格添加到ExCurrentCell中
            if (isEx && !ExCurrentCell.Contains(CurrentCell))
            {
                ExCurrentCell.Add(CurrentCell);
            }
            // 如果当前单元格不存在，且当前单元格在ExCurrentCell中，则将当前单元格从ExCurrentCell中移除
            else if (!isEx && ExCurrentCell.Contains(CurrentCell))
            {
                ExCurrentCell.Remove(CurrentCell);
            }
        }

        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)
        {
            // 验证内容
            List<SheetDataItem> verifyData;

            /* 每日保养数据校验 */
            if (CurrentType == EnumMaintenanceType.Daily)
            {
                TemplateValidateResultModel result = template.FormValidate(CurrentSign, CurrentType, DaylyMaintenanceDate.ToShortDateString(), Banci);
                if (result != null)
                {
                    ScrollToCellRow(result.Item);
                    XtraMessageBoxHelper.Error(result.Msg);
                    return;
                }
            }
            else
            {
                //其他保养
                verifyData = template.Content.Where(x => IsEditor(CurrentType).Contains(x.MaintenanceType) && IsEditorColumns(CurrentType, x) && string.IsNullOrWhiteSpace(x.Value + ""))?.ToList();
                if (verifyData != null && verifyData.Count > 0)
                {
                    // 选定指定单元格
                    SheetDataItem item = verifyData[0];
                    ScrollToCellRow(item);
                    XtraMessageBoxHelper.Error($"存在未填写保养内容！");
                    return;
                }

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

                // 存在异常处理数据
                if (ExCurrentCell != null && ExCurrentCell.Count > 0)
                {
                    if (CurrentType == EnumMaintenanceType.Daily || CurrentFormModel.VersionCode == TemplateConstValue.MonthTemplateV1)
                    {
                        if (template.ExceptionDescription != null && template.ExceptionDescription.Count > 0 && !template.ExceptionDescription.Any(x => x.Value != null && x.Sign == CurrentSign))
                        {
                            ScrollToCellRow(template.ExceptionDescription[0]);

                            string ErrorString = "当前报修存在异常数据，请填写其他异常处理内容！";
                            if (CurrentFormModel.VersionCode == TemplateConstValue.MonthTemplateV1)
                                ErrorString = "当前报修存在未保养项目的数据，请填写异常备注内容！";
                            XtraMessageBoxHelper.Error(ErrorString);
                            return;
                        }
                    }
                    else
                    {
                        verifyData = template.ExceptionDescription.Where(x => (IsEditor(CurrentType, false).Contains(x.MaintenanceType)
                        || (CurrentFormModel.VersionCode == TemplateConstValue.CompositeTemplateV2 && x.MaintenanceType == EnumMaintenanceType.None)) && string.IsNullOrWhiteSpace(x.Value + ""))?.ToList();

                        foreach (var exl in ExCurrentCell)
                        {
                            if (verifyData.Any(x => x.RowIndex > exl.RowIndex))
                            {
                                int rowIndex = verifyData.Where(x => x.RowIndex > exl.RowIndex).Min(x => x.RowIndex);
                                var item = verifyData.FirstOrDefault(x => x.RowIndex == rowIndex);
                                if (item != null && string.IsNullOrWhiteSpace(item.Value + ""))
                                {
                                    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(new SubTemplateData(template), new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }),
                CreateBy = GlobalInfo.CurrentUser.AutoID,
                EquipmentID = CurrentDrive.EquipmentID,
                EquipmentPrimaryID = CurrentDrive.AutoID,
                EquipmentName = CurrentDrive.EquipmentName,
                InstallationSite = CurrentDrive.InstallationLocation,
                FormPrimaryID = CurrentDrive.MaintenanceFormVersion,
                FormName = CurrentFormModel.FormName,
                FormVersionCode = CurrentFormModel.VersionCode,
                FormVersionRev = CurrentFormModel.VersionRev,
                MYear = CurrentPlanModel.MaintenanceYear,
                Specification = CurrentDrive.Specification,
                PlanPrimaryID = CurrentPlanModel.AutoID,
                PlanType = CurrentPlanModel.MaintenanceType
            };

            MaintenanceRecordSubmit subData = new MaintenanceRecordSubmit { Record = mrm };
            if (CurrentType == EnumMaintenanceType.Daily)
            {
                subData.Daily_Date = DaylyMaintenanceDate;
                subData.Banci = (int)Banci;
            }

            // 添加图片
            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);
            }
            else if (be_atta.Visible && !string.IsNullOrWhiteSpace(be_atta.EditValue + ""))
            {
                subData.Files.Add(new AttachmentSubmitModel { AutoID = FileAutoID });
            }

            /* PM 模式下收到设置中的 必须上传照片控制, AM则不受控制 */
            if (MustPic && (subData?.Imgs?.Count ?? 0) == 0)
            {
                bool canSubmit = false;
                switch (CurrentFormModel.VersionCode)
                {
                    case TemplateConstValue.CompositeTemplateV2:
                    case TemplateConstValue.CompositeTemplateV1:
                        canSubmit = false;
                        break;
                    case TemplateConstValue.DailyTemplateV2:
                    case TemplateConstValue.DailyTemplateV1:
                    case TemplateConstValue.MonthTemplateV1:
                        canSubmit = true;
                        break;
                }

                if (!canSubmit)
                {
                    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
            {
                ServiceTime = 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;
                            }
                        }
                    }
                    LoadingTemplate();
                }
                else
                {
                    // 加载历史记录
                    APIResponseData apiResponseData = PreserveManager.Instance.GetPreserveRecordItem(CurrentPlanID, 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);

                switch (CurrentFormModel.VersionCode)
                {
                    case TemplateConstValue.CompositeTemplateV2:
                        template = JsonConvert.DeserializeObject<TemplateIndexV2>(CurrentFormModel.ContentData);
                        break;
                    case TemplateConstValue.CompositeTemplateV1:
                        template = JsonConvert.DeserializeObject<TemplateIndexV1>(CurrentFormModel.ContentData);
                        break;
                    case TemplateConstValue.DailyTemplateV2:
                        template = JsonConvert.DeserializeObject<Template_AM_01>(CurrentFormModel.ContentData);
                        break;
                    case TemplateConstValue.DailyTemplateV1:
                        template = JsonConvert.DeserializeObject<Template_AM_15>(CurrentFormModel.ContentData);
                        break;
                    case TemplateConstValue.MonthTemplateV1:
                        template = JsonConvert.DeserializeObject<Template_AM_17>(CurrentFormModel.ContentData);
                        break;
                    default:
                        break;
                }

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

                if (template == null)
                    throw new Exception("非标准的点检表文件,请检查!");

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

                // 右键菜单点击事件
                template.OnWriteValue += WriteValue;

                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.Daily:
                            CurrentTypeValue = DaylyMaintenanceDate.Day + "";
                            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;
                        }
                        else if (item == EnumMaintenanceCellType.Content)
                        {
                            EditCondition.Add(item,
                            x => x.ColumnIndex == CurrentCell.ColumnIndex
                            && x.RowIndex == CurrentCell.RowIndex
                            && ts.Contains(x.MaintenanceType)
                            && IsEditorColumns(CurrentType, x)
                        );
                        }
                        else
                        {
                            EditCondition.Add(item,
                            x => x.ColumnIndex == CurrentCell.ColumnIndex
                            && x.RowIndex == CurrentCell.RowIndex
                            && IsEditor(CurrentType, false).Contains(x.MaintenanceType)
                            && IsEditorColumns(CurrentType, x, true)
                        );
                        }
                    }

                    #endregion
                }
                else
                {

                    List<SheetDataItem> Items = template.Operation.Where(x => x.Value != null).ToList();
                    if (Items != null && Items.Count > 0 && CurrentType == EnumMaintenanceType.Daily)
                    {
                        Banci = Items[0].BanciType;
                        DaylyMaintenanceDate = new DateTime(CurrentPlanModel.MaintenanceYear, CurrentPlanModel.MaintenanceMonth, Convert.ToInt32(Items[0].MaintenanceTypeValue));
                    }

                    foreach (var item in Items)
                    {
                        item.Sign = CurrentSign;
                    }

                    Items = template.OperationDate.Where(x => x.Value != null).ToList();
                    foreach (var item in Items)
                    {
                        item.Sign = CurrentSign;
                    }

                    Items = template.Content.Where(x => x.Value != null).ToList();
                    foreach (var item in Items)
                    {
                        item.Sign = CurrentSign;
                    }


                    Items = template.ExceptionDescription.Where(x => x.Value != null).ToList();
                    foreach (var item in Items)
                    {
                        item.Sign = CurrentSign;
                    }

                    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.EquipmentName)
                        {
                            Cell cell = worksheet.Cells[item.RowIndex, item.ColumnIndex];
                            cell.Value = CurrentDrive.EquipmentName;
                        }
                        #endregion

                        #region 安装地点
                        foreach (SheetDataItem item in template.InstallationSite)
                        {
                            Cell cell = worksheet.Cells[item.RowIndex, item.ColumnIndex];
                            cell.Value = CurrentDrive.InstallationLocation;
                        }
                        #endregion

                        #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();
                        }

                        foreach (SheetDataItem item in template.YearAndMonth)
                        {
                            Cell cell = worksheet.Cells[item.RowIndex, item.ColumnIndex];
                            if (cell.Value.IsText && !cell.Value.TextValue.IsNull())
                            {
                                cell.Value = cell.Value.TextValue.Replace("    年", $"{CurrentPlanModel.MaintenanceYear}年").Replace("  月", $"{CurrentPlanModel.MaintenanceMonth.ToString().PadLeft(2, '0')}月");
                            }
                        }

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

                        #endregion
                    }
                    else
                    {
                        Cell cell = null;
                        #region 设备名称
                        //设备名称
                        foreach (SheetDataItem item in template.EquipmentName)
                        {
                            cell = worksheet.Cells[item.RowIndex, item.ColumnIndex];
                            cell.Value = CurrentDrive.EquipmentName;
                        }
                        #endregion

                        #region 安装地点
                        //安装地点
                        foreach (SheetDataItem item in template.InstallationSite)
                        {
                            cell = worksheet.Cells[item.RowIndex, item.ColumnIndex];
                            cell.Value = CurrentDrive.InstallationLocation;
                        }
                        #endregion

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

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

                        #region 年份赋值

                        //年份赋值
                        foreach (SheetDataItem item in template.Year)
                        {
                            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();
                        }

                        foreach (SheetDataItem item in template.YearAndMonth)
                        {
                            cell = worksheet.Cells[item.RowIndex, item.ColumnIndex];
                            if (cell.Value.IsText && !cell.Value.TextValue.IsNull())
                            {
                                cell.Value = cell.Value.TextValue.Replace("    年", $"{CurrentPlanModel.MaintenanceYear}年").Replace("  月", $"{CurrentPlanModel.MaintenanceMonth.ToString().PadLeft(2, '0')}月");
                            }
                        }

                        #endregion

                        #region 正文赋值
                        List<SheetDataItem> datas = template.Content.Where(x => x.Value != null)?.ToList();
                        foreach (SheetDataItem item in datas)
                        {
                            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 = worksheet.Cells[item.RowIndex, item.ColumnIndex];
                            cell.Value = item.Value + "";
                            cell.Alignment.WrapText = true;
                            cell.Alignment.Horizontal = SpreadsheetHorizontalAlignment.Left;
                            cell.Alignment.Vertical = SpreadsheetVerticalAlignment.Top;
                        }
                        #endregion

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

                            if (CurrentType == EnumMaintenanceType.Daily)
                            {
                                double width = worksheet.Columns[cell.ColumnIndex].Width;
                                worksheet.Columns[cell.ColumnIndex].AutoFitColumns();
                                if (worksheet.Columns[cell.ColumnIndex].Width < width)
                                {
                                    worksheet.Columns[cell.ColumnIndex].Width = width;
                                }
                            }
                        }
                        #endregion

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

                            if (CurrentType == EnumMaintenanceType.Daily)
                            {
                                double width = worksheet.Columns[cell.ColumnIndex].Width;
                                worksheet.Columns[cell.ColumnIndex].AutoFitColumns();
                                if (worksheet.Columns[cell.ColumnIndex].Width < width)
                                {
                                    worksheet.Columns[cell.ColumnIndex].Width = width;
                                }
                            }
                        }
                        #endregion


                        #region 设置右键菜单

                        spreadsheetControl1.MouseDown += (s1, e1) =>
                        {
                            if (e1.Button == MouseButtons.Right)
                            {
                                // 获取鼠标位置对应的单元格
                                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))
                                if (EditCondition.ContainsKey(EnumMaintenanceCellType.Operation) && template.Operation.Any(EditCondition[EnumMaintenanceCellType.Operation]) && (MaintenanceAutoID == 0 || isAdmin))
                                {
                                    // 操作人
                                    template.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))
                                else if (EditCondition.ContainsKey(EnumMaintenanceCellType.OperationDate) && template.OperationDate.Any(EditCondition[EnumMaintenanceCellType.OperationDate]) && (MaintenanceAutoID == 0 || isAdmin))
                                {
                                    // 保养日期
                                    template.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))
                                else if (EditCondition.ContainsKey(EnumMaintenanceCellType.Content) && template.Content.Any(EditCondition[EnumMaintenanceCellType.Content]) && (MaintenanceAutoID == 0 || isAdmin))
                                {
                                    // 保养正文
                                    template.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))
                                else if (EditCondition.ContainsKey(EnumMaintenanceCellType.ExceptionDescription) && template.ExceptionDescription.Any(EditCondition[EnumMaintenanceCellType.ExceptionDescription]) && (MaintenanceAutoID == 0 || isAdmin))
                                {
                                    // 保养 - 其他异常
                                    template.popupException.ShowPopup(spreadsheetControl1, new Point(e1.X, e1.Y));
                                }
                            }
                        };

                        #endregion
                    }

                    worksheet.ScrollTo(0, 0);

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


        }

        #region 方法

        /// <summary>
        /// 加载模板
        /// </summary>
        /// <exception cref="Exception"></exception>
        void LoadingTemplate()
        {
            //获取当前计划信息
            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 (CurrentModel != null && CurrentModel.FormPrimaryID != CurrentFormModel.AutoID)
                throw new Exception($"当前历史保养计划的表单与当前表单不同,无法修改!");

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

            if (CurrentFormModel.VersionCode == TemplateConstValue.DailyTemplateV1
                || CurrentFormModel.VersionCode == TemplateConstValue.DailyTemplateV2
                || CurrentFormModel.VersionCode == TemplateConstValue.MonthTemplateV1
                )
            {
                this.Text = "设备的AM保养表单";
            }

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

            if (CurrentDate.Month != CurrentPlanModel.MaintenanceMonth)
            {
                CurrentDate = new DateTime(CurrentPlanModel.MaintenanceYear, CurrentPlanModel.MaintenanceMonth, 1);
            }

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

            if (spreadsheetControl1.Document.Worksheets.Contains("正文"))
                spreadsheetControl1.Document.Worksheets.ActiveWorksheet = spreadsheetControl1.Document.Worksheets["正文"];
            else if (spreadsheetControl1.Document.Worksheets.Contains("Table2"))
                spreadsheetControl1.Document.Worksheets.ActiveWorksheet = spreadsheetControl1.Document.Worksheets["Table2"];
            else
            {
                XtraMessageBoxHelper.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(this) == DialogResult.OK)
                    {
                        using (Graphics graphics = Graphics.FromImage(d.CameraImage))
                        {
                            string watermarkText = ApiHelper.Instance.GetServiceTime();
                            if (string.IsNullOrWhiteSpace(watermarkText))
                            {
                                XtraMessageBoxHelper.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)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        /// <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(this) == DialogResult.OK)
                {
                    txt_Attr.Text = ofd.FileName;
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        /// <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}月保养，当前单元格不可填。";
            }
            else if (CurrentType == EnumMaintenanceType.Daily)
            {
                tips = $"当前属于第{DaylyMaintenanceDate.Day}号保养,当前单元格不可填。";
            }

            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);
            if (t == EnumMaintenanceType.Daily)
                ts.Add(EnumMaintenanceType.Daily);
            return ts;
        }

        // 半年的单元格限制
        int SemianCol = 0;
        string[] MonthString = new string[] { "一", "二", "三", "四", "五", "六", "七", "八", "九", "十", "十一", "十二" };
        private bool IsEditorColumns(EnumMaintenanceType t, SheetDataItem item, bool IgnoreAnnualValidate = false)
        {
            if (t == EnumMaintenanceType.Annual || t == EnumMaintenanceType.OddAnnual || t == EnumMaintenanceType.EvenAnnual)
            {
                if (item.MaintenanceType == EnumMaintenanceType.Annual)
                {
                    // 年
                    return true;
                }
                else if ((CurrentDate.Year % 2 == 0 || IgnoreAnnualValidate) && item.MaintenanceType == EnumMaintenanceType.EvenAnnual)
                {
                    // 偶数年
                    return true;
                }
                else if ((CurrentDate.Year % 2 == 1 || IgnoreAnnualValidate) && item.MaintenanceType == EnumMaintenanceType.OddAnnual)
                {
                    // 奇数年
                    return true;
                }
                else if (item.MaintenanceType == EnumMaintenanceType.Quarterly && ((CurrentDate.Month - 1) / 3 + 1) + "" == item.MaintenanceTypeValue)
                {
                    // 季度
                    return true;
                }
                else if (item.MaintenanceType == EnumMaintenanceType.Semian)
                {
                    // 半年
                    return true;
                }
                else if (item.MaintenanceType == EnumMaintenanceType.Monthly
                    &&
                        ((CurrentDate.Month + "" == item.MaintenanceTypeValue)
                        || MonthString[Math.Abs((CurrentDate.Month - 1) % 12)] + "月" == item.MaintenanceTypeValue
                ))
                {
                    // 月
                    return true;
                }
            }
            else if (t == EnumMaintenanceType.Monthly)
            {
                if (item.MaintenanceType == EnumMaintenanceType.Monthly &&
                        ((CurrentDate.Month + "" == item.MaintenanceTypeValue)
                        || MonthString[Math.Abs((CurrentDate.Month - 1) % 12)] + "月" == item.MaintenanceTypeValue
                ))
                {
                    // 月
                    return true;
                }
            }
            else if (EnumMaintenanceType.Quarterly == t)
            {
                if (item.MaintenanceType == EnumMaintenanceType.Quarterly && ((CurrentDate.Month - 1) / 3 + 1) + "" == item.MaintenanceTypeValue)
                {
                    // 季度
                    return true;
                }
                else if (item.MaintenanceType == EnumMaintenanceType.Monthly && CurrentDate.Month + "" == item.MaintenanceTypeValue)
                {
                    // 月
                    return true;
                }
            }
            else if (EnumMaintenanceType.Semian == t)
            {
                if (SemianCol == 0)
                    SemianCol = template.Content.Min(x => x.ColumnIndex);

                if (((CurrentDate.Month - 1) / 6 + 1) + "" == "1" && SemianCol == item.ColumnIndex)
                {
                    // 上半年
                    return true;
                }
                else if (((CurrentDate.Month - 1) / 6 + 1) + "" == "2" && (SemianCol + 1) == item.ColumnIndex)
                {
                    // 下半年
                    return true;
                }
                // template.Content.Min(x=>x.ColumnIndex)
            }
            else if (EnumMaintenanceType.Daily == t)
            {
                /* 班次未选定,则不限定班次均可编辑 */
                if (Banci == EnumMaintenanceBanciType.None)
                    return DaylyMaintenanceDate.Day.ToString() == item.MaintenanceTypeValue;
                else
                {
                    /* 如果班次已选定,则未编辑的单元格判断班次,当前已编辑的单元格可修改 */
                    return DaylyMaintenanceDate.Day.ToString() == item.MaintenanceTypeValue && (item.BanciType == Banci || item.BanciType == EnumMaintenanceBanciType.Week || item.Sign == CurrentSign);
                }
            }
            return false;
        }

        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(this);
            }
        }


        private SheetDataItem GetSheetItem(Cell cell, EnumMaintenanceCellType type)
        {
            SheetDataItem item;
            switch (type)
            {
                case EnumMaintenanceCellType.Content:
                    item = template.Content.FirstOrDefault(x => x.ColumnIndex == cell.ColumnIndex
                    && x.RowIndex == cell.RowIndex);
                    break;
                case EnumMaintenanceCellType.Operation:
                    item = template.Operation.FirstOrDefault(x => x.ColumnIndex == cell.ColumnIndex
                    && x.RowIndex == cell.RowIndex);
                    break;
                case EnumMaintenanceCellType.OperationDate:
                    item = template.OperationDate.FirstOrDefault(x => x.ColumnIndex == cell.ColumnIndex
                    && x.RowIndex == cell.RowIndex);
                    break;
                case EnumMaintenanceCellType.ExceptionDescription:
                    if (CurrentFormModel.VersionCode == TemplateConstValue.CompositeTemplateV1 || CurrentFormModel.VersionCode == TemplateConstValue.CompositeTemplateV2)
                    {
                        item = template.ExceptionDescription.FirstOrDefault(x => x.ColumnIndex == cell.ColumnIndex
                    && x.RowIndex == cell.RowIndex);
                    }
                    else
                    {
                        item = template.ExceptionDescription.FirstOrDefault(x => x.ColumnIndex == cell.ColumnIndex
                    && x.RowIndex == cell.RowIndex && IsEditorColumns(x.MaintenanceType, x));
                    }

                    break;
                default:
                    item = null;
                    break;
            }
            return item;
        }
    }
}