using DevExpress.Spreadsheet;
using DevExpress.Utils.Menu;
using DevExpress.XtraSpreadsheet.Menu;
using DeviceRepair.Models;
using DeviceRepair.Models.Enum;
using DeviceRepair.Utils;
using TsSFCDevice.Client.Launch.Common.NpoiExtend;
using System.Collections.Generic;
using System.Linq;
using System;

namespace TsSFCDevice.Client.Launch.PreserveTemplate
{
    public class Template_AM_01 : BaseTemplate
    {
        /// <summary>
        /// 设备型号
        /// </summary>
        internal readonly string EquipmentModelAddress = "[C,1]";

        /// <summary>
        /// 设备编号
        /// </summary>
        internal readonly string EquipmentNumberAddress = "[E,1]";

        /// <summary>
        /// 年月
        /// </summary>
        internal readonly string YearAndMonthAddress = "[H,1]";

        /// <summary>
        /// 班次/频次
        /// </summary>
        internal readonly string BanciColumnAddress = "G";

        /// <summary>
        /// 日期
        /// </summary>
        internal readonly string DayColumnAddress = "H";

        /// 正文
        /// </summary>
        internal override SpreadsheetPopupMenu popupContent
        {
            get
            {
                if (_popupContent == null)
                {
                    _popupContent = new SpreadsheetPopupMenu()
                    {
                        Caption = "正文",
                        Items =
                        {
                            new DXMenuItem("正常",(s,e)=>{WriteValue(EnumMaintenanceCellType.Content, "√"); }),
                            new DXMenuItem("有问题",(s,e)=>{WriteValue(EnumMaintenanceCellType.Content, "△", EnumMaintenanceOperationType.Write, true); }),
                            new DXMenuItem("不适用或无生产",(s,e)=>{WriteValue(EnumMaintenanceCellType.Content, "N/A"); }),
                            new DXMenuItem("清空",(s,e)=>{WriteValue(EnumMaintenanceCellType.Content, "", EnumMaintenanceOperationType.Clear); }),
                        }
                    };
                }
                return _popupContent;
            }
        }

        public Template_AM_01() : base()
        {

        }

        /// <summary>
        /// 初始化对象
        /// </summary>
        /// <param name="ws">Worksheet 控件对象</param>
        /// <param name="CurrentType">当前计划类型</param>
        /// <param name="EditColValue">当前编辑列</param>
        public Template_AM_01(Worksheet ws) : base(ws)
        {
            #region 设备型号
            DeviceSpecification.Add(SheetExtend.AddressToIndex(EquipmentModelAddress));
            #endregion

            #region 设备型号
            EquipmentID.Add(SheetExtend.AddressToIndex(EquipmentNumberAddress));
            #endregion

            #region 年检表 年/月
            YearAndMonth.Add(SheetExtend.AddressToIndex(YearAndMonthAddress));
            #endregion

            int MonthStartColIndex = SheetExtend.ColumnIndexFromLetter(DayColumnAddress);
            int MonthEndColIndex = MonthStartColIndex + 30;
            int BanciColIndex = SheetExtend.ColumnIndexFromLetter(BanciColumnAddress);

            for (int rowIndex = 2; rowIndex < LastUsedRowIndex; rowIndex++)
            {
                #region 空行判断
                Cell FirstCell = worksheet.Cells[rowIndex, 0];
                if (FirstCell.Value.IsEmpty && !FirstCell.IsMerged)
                    break;
                #endregion

                for (int colIndex = MonthStartColIndex; colIndex <= MonthEndColIndex; colIndex++)
                {
                    Cell cell = worksheet.Cells[rowIndex, colIndex];
                    Cell BanciCell = worksheet[rowIndex, BanciColIndex];

                    EnumMaintenanceBanciType Banci;
                    switch ((BanciCell?.Value?.TextValue ?? "").Trim())
                    {
                        case "早":
                            Banci = EnumMaintenanceBanciType.Morning;
                            break;
                        case "中":
                            Banci = EnumMaintenanceBanciType.Noon;
                            break;
                        case "夜":
                            Banci = EnumMaintenanceBanciType.Night;
                            break;
                        case "周":
                            Banci = EnumMaintenanceBanciType.Week;
                            break;
                        default:
                            Banci = EnumMaintenanceBanciType.None;
                            break;
                    }

                    Cell FirstDataCell = worksheet[FirstCell.RowIndex, FirstCell.ColumnIndex];
                    if (FirstCell.IsMerged)
                    {
                        //获取主单元格位置
                        int PreRowIndex = (FirstCell.GetMergedRanges()[0]).TopRowIndex;
                        int PreColumnIndex = (FirstCell.GetMergedRanges()[0]).LeftColumnIndex;
                        FirstDataCell = worksheet[PreRowIndex, PreColumnIndex];
                    }

                    if ((FirstDataCell?.Value?.TextValue ?? "").Trim() == "其他异常处理")
                    {
                        // 异常备注：
                        ExceptionDescription.Add(new SheetDataItem { RowIndex = FirstDataCell.RowIndex, ColumnIndex = 1, MaintenanceType = EnumMaintenanceType.Daily, MaintenanceTypeValue = worksheet.Cells[1, colIndex].Value.NumericValue + "", BanciType = Banci });

                        // 保养人签字
                        Operation.Add(new SheetDataItem { RowIndex = rowIndex, ColumnIndex = colIndex, MaintenanceType = EnumMaintenanceType.Daily, MaintenanceTypeValue = worksheet.Cells[1, colIndex].Value.NumericValue + "", BanciType = Banci });
                    }
                    else
                    {
                        // 正文
                        Content.Add(new SheetDataItem { RowIndex = rowIndex, ColumnIndex = colIndex, MaintenanceType = EnumMaintenanceType.Daily, MaintenanceTypeValue = worksheet.Cells[1, colIndex].Value.NumericValue + "", BanciType = Banci });
                    }
                }
            }
        }

        /// <summary>
        /// 表单验证
        /// </summary>
        /// <returns></returns>
        public override TemplateValidateResultModel FormValidate(Guid Sign, EnumMaintenanceType OperationType, string OperationTypeValue, EnumMaintenanceBanciType Banci)
        {
            try
            {
                IEnumerable<SheetDataItem> PubObj;
                DateTime CurrentMaintenanceDate = DateTime.Today;
                if (!DateTime.TryParse(OperationTypeValue, out CurrentMaintenanceDate))
                {
                    throw new Exception("当前保养日期获取失败！");
                }

                #region 保养人签名
                /* 保养的班次 -- 保养人签名 */
                if (Banci == EnumMaintenanceBanciType.None)
                {
                    List<SheetDataItem> m_Operation = Operation.Where(x => x.MaintenanceTypeValue == (CurrentMaintenanceDate.Day + "")).ToList();
                    if (m_Operation != null && m_Operation.Count > 0)
                    {
                        SheetDataItem Rtn = m_Operation.First(x => (x.Value + "").IsNull());
                        if (Rtn != null)
                            return new TemplateValidateResultModel { Item = Rtn, Msg = "操作人是必填的！" };
                        return new TemplateValidateResultModel { Item = m_Operation.First(), Msg = "操作人是必填的！" };
                    }
                }
                #endregion

                #region 保养正文验证
                /* 保养正文 */
                PubObj = Content.Where(x => x.MaintenanceTypeValue == (CurrentMaintenanceDate.Day + "") && (x.BanciType != Banci && x.BanciType != EnumMaintenanceBanciType.Week) && !(x.Value + "").IsNull() && x.Sign == Sign);
                if (PubObj != null && PubObj.Count() > 0)
                {
                    /* 存在非当前班次保养的单元格被填写 */
                    return new TemplateValidateResultModel { Item = PubObj.First(), Msg = $"请勿填写非本次的保养内容,班次的判定为操作人签名的班次！" };
                }

                List<SheetDataItem> m_Data = Content.Where(x => x.MaintenanceTypeValue == (CurrentMaintenanceDate.Day + "") && (x.BanciType == Banci || x.BanciType == EnumMaintenanceBanciType.Week)).ToList();
                PubObj = m_Data.Where(x => (x.Value + "").IsNull() && x.BanciType != EnumMaintenanceBanciType.Week);
                if (PubObj != null && PubObj.Count() > 0)
                {
                    /* 如果存在空值单元格 */
                    return new TemplateValidateResultModel { Item = PubObj.First(), Msg = $"存在未填写保养内容！" };
                }
                #endregion

                #region 其他异常处理
                /* 其他异常处理 */
                List<SheetDataItem> m_Exception = ExceptionDescription.Where(x => x.MaintenanceTypeValue == (CurrentMaintenanceDate.Day + "")).ToList();
                PubObj = m_Data.Where(x => (x.Value + "").Equals("△", StringComparison.OrdinalIgnoreCase));
                if (PubObj != null && PubObj.Count() > 0)
                {
                    /* 存在异常处理单元格 */
                    if (m_Exception != null && m_Exception.Count > 0)
                    {
                        /* 当前班次的单元格 */
                        SheetDataItem ExceptionItem = m_Exception.FirstOrDefault(x => x.BanciType == Banci);

                        /* 当前班次单元格数据为空 */
                        if ((ExceptionItem.Value + "").IsNull())
                        {
                            /* 如果存在空值单元格 */
                            IEnumerable<SheetDataItem> HasDataItem = m_Exception.Where(x => x.Sign == Sign && !(x.Value + "").IsNull());
                            if (HasDataItem != null && HasDataItem.Count() > 0)
                            {
                                ExceptionItem.Value = string.Join("", HasDataItem.Select(x => (x.Value + "")).ToArray());
                            }
                            else
                            {
                                return new TemplateValidateResultModel { Item = m_Exception.First(), Msg = $"当前报修存在异常数据，请填写其他异常处理内容！" };
                            }
                        }
                    }
                }
                #endregion

                return null;
            }
            catch (Exception)
            {
                throw;
            }
        }

        public override void ReplaceData(BaseTemplate Data)
        {
            foreach (SheetDataItem item in Data.EquipmentName)
            {
                SheetDataItem sdi = EquipmentName.FirstOrDefault(x => x.ColumnIndex == item.ColumnIndex && x.RowIndex == item.RowIndex);
                sdi.Value = item.Value;
            }

            foreach (SheetDataItem item in Data.InstallationSite)
            {
                SheetDataItem sdi = InstallationSite.FirstOrDefault(x => x.ColumnIndex == item.ColumnIndex && x.RowIndex == item.RowIndex);
                sdi.Value = item.Value;
            }

            foreach (SheetDataItem item in Data.DeviceSpecification)
            {
                SheetDataItem sdi = DeviceSpecification.FirstOrDefault(x => x.ColumnIndex == item.ColumnIndex && x.RowIndex == item.RowIndex);
                sdi.Value = item.Value;
            }

            foreach (SheetDataItem item in Data.EquipmentID)
            {
                SheetDataItem sdi = EquipmentID.FirstOrDefault(x => x.ColumnIndex == item.ColumnIndex && x.RowIndex == item.RowIndex);
                sdi.Value = item.Value;
            }

            foreach (SheetDataItem item in Data.Year)
            {
                SheetDataItem sdi = Year.FirstOrDefault(x => x.ColumnIndex == item.ColumnIndex && x.RowIndex == item.RowIndex);
                sdi.Value = item.Value;
            }

            foreach (SheetDataItem item in Data.YearAndMonth)
            {
                SheetDataItem sdi = YearAndMonth.FirstOrDefault(x => x.ColumnIndex == item.ColumnIndex && x.RowIndex == item.RowIndex);
                sdi.Value = item.Value;
            }

            foreach (SheetDataItem item in Data.Content)
            {
                SheetDataItem sdi = Content.FirstOrDefault(x => x.ColumnIndex == item.ColumnIndex && x.RowIndex == item.RowIndex);
                sdi.Value = item.Value;
            }

            foreach (SheetDataItem item in Data.ExceptionDescription)
            {
                SheetDataItem sdi = ExceptionDescription.FirstOrDefault(x => x.ColumnIndex == item.ColumnIndex && x.RowIndex == item.RowIndex && x.MaintenanceTypeValue == item.MaintenanceTypeValue);
                sdi.Value = item.Value;
            }

            foreach (SheetDataItem item in Data.Operation)
            {
                SheetDataItem sdi = Operation.FirstOrDefault(x => x.ColumnIndex == item.ColumnIndex && x.RowIndex == item.RowIndex && x.MaintenanceTypeValue == item.MaintenanceTypeValue);
                sdi.Value = item.Value;
            }

            foreach (SheetDataItem item in Data.OperationDate)
            {
                SheetDataItem sdi = OperationDate.FirstOrDefault(x => x.ColumnIndex == item.ColumnIndex && x.RowIndex == item.RowIndex);
                sdi.Value = item.Value;
            }
        }
    }
}
