using DevExpress.XtraBars;
using DevExpress.XtraBars.ToolbarForm;
using DevExpress.XtraEditors;
using DeviceRepair.Models;
using DeviceRepair.Models.Enum;
using System;
using System.Windows.Forms;
using DeviceRepair.Utils;
using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.SS.UserModel;
using Newtonsoft.Json;
using TsSFCDevice.Client.Biz.Impl;
using System.Text.RegularExpressions;

namespace TsSFCDevice.Client.Launch.CheckForm
{
    public partial class pageFormVersionEdit : ToolbarForm
    {
        public MaintenanceFormVersionInfo CurrentModel;

        PreserveTemplate.BaseTemplate template = null;

        bool isAM = false;

        public pageFormVersionEdit() : this(new MaintenanceFormVersionInfo { FormBelong = EnumDeviceBelong.PM.ToString() })
        {
        }

        public pageFormVersionEdit(MaintenanceFormVersionInfo currentModel)
        {
            InitializeComponent();
            CurrentModel = currentModel;
            isAM = EnumDeviceBelong.AM.ToString() == currentModel.FormBelong;

            if (isAM)
            {
                txtVersion.Properties.Items.Clear();
                txtVersion.Properties.Items.Add(new DevExpress.XtraEditors.Controls.RadioGroupItem
                {
                    Description = "FM-P0075.01",
                    Value = "FM-P0075.01"
                });
                txtVersion.Properties.Items.Add(new DevExpress.XtraEditors.Controls.RadioGroupItem
                {
                    Description = "FM-P0075.15",
                    Value = "FM-P0075.15"
                });
                txtVersion.Properties.Items.Add(new DevExpress.XtraEditors.Controls.RadioGroupItem
                {
                    Description = "FM-P0075.17",
                    Value = "FM-P0075.17"
                });
                txtVersion.EditValue = "FM-P0075.01";
                this.Text = "AM 的点检表";
            }
        }

        private void pageFormVersionEdit_Load(object sender, EventArgs e)
        {
            if (CurrentModel.AutoID != 0)
            {
                txtName.EditValue = CurrentModel.FormName;
                txtName.Enabled = false;
                txtCode.EditValue = CurrentModel.VersionCode;
                txtCode.Enabled = false;
                txtRev.EditValue = CurrentModel.VersionRev;
                txtRev.Enabled = false;

                txtFilePath.EditValue = CurrentModel.FormFileName ?? Path.GetFileName(CurrentModel.FormPath);
                txtFilePath.Enabled = false;

                txtVersion.EditValue = CurrentModel.VersionCode;
                txtVersion.Enabled = false;

                txtNote.EditValue = CurrentModel.Remarks;
            }
        }

        /// <summary>
        /// 提交
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSave_ItemClick(object sender, ItemClickEventArgs e)
        {
            try
            {
                if (CanCloas())
                {
                    if (CurrentModel.AutoID == 0)
                    {
                        CurrentModel.ContentData = JsonConvert.SerializeObject(template);
                        CurrentModel.FormName = txtName.EditValue + "";
                        CurrentModel.FormPath = txtFilePath.EditValue + "";
                        CurrentModel.FormStatus = true;
                        CurrentModel.Remarks = txtNote.EditValue + "";
                        CurrentModel.VersionCode = txtCode.EditValue + "";
                        CurrentModel.VersionRev = txtRev.EditValue + "";
                        CurrentModel.FormFileName = Path.GetFileName(txtFilePath.EditValue + "");
                        CurrentModel.FormBelong = isAM ? "AM" : "PM";
                    }
                    else
                    {
                        CurrentModel.Remarks = txtNote.EditValue + "";
                    }
                    this.DialogResult = DialogResult.OK;
                }
            }
            catch (Exception ex)
            {
                XtraMessageBoxHelper.Error(ex.Message);
                return;
            }

            this.DialogResult = DialogResult.OK;
        }

        /// <summary>
        /// 选择文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void txtFilePath_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Ellipsis)
            {
                try
                {
                    XtraOpenFileDialog xtraOpenFileDialog1 = new XtraOpenFileDialog();
                    xtraOpenFileDialog1.FileName = string.Empty;
                    xtraOpenFileDialog1.Filter = "(*.xls)|*.xls;*.xlsx";
                    xtraOpenFileDialog1.Multiselect = false;
                    xtraOpenFileDialog1.Title = "请选择待导入的点检表Excel文件";

                    if (xtraOpenFileDialog1.ShowDialog(this) == DialogResult.OK)
                    {
                        string FilePath = xtraOpenFileDialog1.FileName;
                        splashScreenManager1.ShowWaitForm();
                        template = null;
                        using (FileStream fileStream = new FileStream(FilePath, FileMode.Open, FileAccess.Read))
                        {
                            string fileExtension = Path.GetExtension(FilePath);
                            MaintenanceFormVersionInfo entity;
                            if (fileExtension.Equals(".xls", StringComparison.OrdinalIgnoreCase))
                            {
                                // 如果是 .xls 文件
                                HSSFWorkbook workbook = new HSSFWorkbook(fileStream);
                                if (isAM)
                                {
                                    entity = ReadHeaderFromWorkbookAM(workbook);
                                }
                                else
                                {
                                    entity = ReadHeaderFromWorkbookPM(workbook);
                                }

                            }
                            else if (fileExtension.Equals(".xlsx", StringComparison.OrdinalIgnoreCase))
                            {
                                // 如果是 .xlsx 文件
                                XSSFWorkbook workbook = new XSSFWorkbook(fileStream);
                                if (isAM)
                                {
                                    entity = ReadHeaderFromWorkbookAM(workbook);
                                }
                                else
                                {
                                    entity = ReadHeaderFromWorkbookPM(workbook);
                                }

                            }
                            else
                            {
                                // 不支持的文件类型
                                throw new NotSupportedException("不支持的文件类型");
                            }

                            DevExpress.XtraSpreadsheet.SpreadsheetControl spreadsheetControl1 = new DevExpress.XtraSpreadsheet.SpreadsheetControl();
                            spreadsheetControl1.BeginUpdate();
                            spreadsheetControl1.LoadDocument(IOExtend.FileToByteArray(FilePath));
                            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
                            {
                                throw new NotSupportedException("非标准设备保养表单！");
                            }

                            switch (entity.VersionCode)
                            {
                                case PreserveTemplate.TemplateConstValue.CompositeTemplateV2:
                                    template = new PreserveTemplate.TemplateIndexV2(spreadsheetControl1.Document.Worksheets.ActiveWorksheet);
                                    break;
                                case PreserveTemplate.TemplateConstValue.CompositeTemplateV1:
                                    template = new PreserveTemplate.TemplateIndexV1(spreadsheetControl1.Document.Worksheets.ActiveWorksheet);
                                    break;
                                case PreserveTemplate.TemplateConstValue.MonthTemplateV1:
                                    template = new PreserveTemplate.Template_AM_17(spreadsheetControl1.Document.Worksheets.ActiveWorksheet);
                                    break;
                                case PreserveTemplate.TemplateConstValue.DailyTemplateV2:
                                    template = new PreserveTemplate.Template_AM_01(spreadsheetControl1.Document.Worksheets.ActiveWorksheet);
                                    break;
                                case PreserveTemplate.TemplateConstValue.DailyTemplateV1:
                                    template = new PreserveTemplate.Template_AM_15(spreadsheetControl1.Document.Worksheets.ActiveWorksheet);
                                    break;
                                default:
                                    template = null;
                                    break;
                            }

                            if (entity != null)
                            {
                                //检测当前文档是否存在
                                if (CheckFormRepository.Instance.Get_CheckForm_Exists(entity.VersionCode, entity.VersionRev))
                                {
                                    throw new Exception("当前点检表已存在!");
                                }
                            }
                            else
                            {
                                throw new Exception("请选择点检表文件！");
                            }

                            txtCode.EditValue = entity.VersionCode;
                            txtFilePath.EditValue = FilePath;
                            txtName.EditValue = entity.FormName;
                            txtRev.EditValue = entity.VersionRev;
                        }

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

        /// <summary>
        /// 校验表单
        /// </summary>
        /// <returns></returns>
        private bool CanCloas()
        {
            // 校验点检表文件
            if (CurrentModel.AutoID == 0)
            {
                if ((txtFilePath.EditValue + "").IsNull())
                    throw new ArgumentException("文件路径不能为空!");

                string FilePath = txtFilePath.EditValue + "";
                if (!File.Exists(FilePath))
                    throw new ArgumentException("找不到待提交的文件!");

                if (txtVersion.EditValue + "" != txtCode.EditValue + "")
                    throw new ArgumentException("文件版本与上传文件版本不匹配!");

                CurrentModel.FormPath = FilePath;

                // 校验说明
                string Note = txtNote.EditValue + "";
                if (!Note.IsNull() && Note.Length > 200)
                    throw new ArgumentException("说明的文字长度不允许超出200字!");
            }
            else
            {
                string Note = txtNote.EditValue + "";
                if (!Note.IsNull() && Note.Length > 200)
                    throw new ArgumentException("说明的文字长度不允许超出200字!");
            }

            return true;
        }

        /// <summary>
        /// 从工作簿中读取页眉
        /// </summary>
        /// <param name="workbook"></param>
        /// <returns></returns>
        private MaintenanceFormVersionInfo ReadHeaderFromWorkbookAM(IWorkbook workbook)
        {
            MaintenanceFormVersionInfo maintenance = null;

            try
            {
                // 获取第一个工作表
                ISheet CurrentSheet = null;
                int SheetCount = workbook.NumberOfSheets;

                if (SheetCount == 0)
                {
                    throw new ArgumentException("导入的点检表文件出错,文件中无内容!");
                }

                CurrentSheet = workbook.GetSheet("Table2");
                if (CurrentSheet == null)
                {
                    throw new ArgumentException("导入的点检表文件出错,当前文件中不存在【Table2】的Sheet页!");
                }

                // 获取页眉
                if (CurrentSheet != null && CurrentSheet.Header != null)
                {
                    Tuple<string, string, string> tuple = GetPageHeadVersionInfo(CurrentSheet);
                    maintenance = new MaintenanceFormVersionInfo();
                    maintenance.FormName = tuple.Item1;
                    maintenance.VersionCode = tuple.Item2;
                    maintenance.VersionRev = tuple.Item3;
                }

                // 验证模板内容
                ArgumentException argEx;
                if (maintenance.VersionCode == PreserveTemplate.TemplateConstValue.DailyTemplateV2)
                {
                    PreserveTemplate.FM_P0075_01 fm = new PreserveTemplate.FM_P0075_01();
                    argEx = fm.CheckCurrentSheet(CurrentSheet);

                }
                else if (maintenance.VersionCode == PreserveTemplate.TemplateConstValue.DailyTemplateV1)
                {
                    PreserveTemplate.FM_P0075_15 fm = new PreserveTemplate.FM_P0075_15();
                    argEx = fm.CheckCurrentSheet(CurrentSheet);
                }
                else if (maintenance.VersionCode == PreserveTemplate.TemplateConstValue.MonthTemplateV1)
                {
                    PreserveTemplate.FM_P0075_17 fm = new PreserveTemplate.FM_P0075_17();
                    argEx = fm.CheckCurrentSheet(CurrentSheet);
                }
                else
                {
                    throw new ArgumentException($"未适配的点检表编号【{maintenance.VersionCode}】,无法导入!");
                }

                if (argEx != null)
                    throw argEx;

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

        /// <summary>
        /// 从工作簿中读取页眉
        /// </summary>
        /// <param name="workbook"></param>
        /// <returns></returns>
        private MaintenanceFormVersionInfo ReadHeaderFromWorkbookPM(IWorkbook workbook)
        {
            MaintenanceFormVersionInfo maintenance = new MaintenanceFormVersionInfo();

            // 获取第一个工作表
            ISheet CurrentSheet = null;
            int SheetCount = workbook.NumberOfSheets;


            if ("FM-P0075.17" == (txtVersion.EditValue + ""))
            {
                if (SheetCount == 0)
                {
                    throw new ArgumentException("导入的点检表文件出错,文件中无内容!");
                }

                CurrentSheet = workbook.GetSheet("Table2");
                if (CurrentSheet == null)
                {
                    throw new ArgumentException("导入的点检表文件出错,当前文件中不存在【Table2】的Sheet页!");
                }
            }
            else
            {
                for (int i = 0; i < SheetCount; i++)
                {
                    ISheet sheet = workbook.GetSheetAt(i);
                    if (sheet.SheetName.Equals("正文"))
                    {
                        CurrentSheet = sheet;
                    }
                }
            }

            if (CurrentSheet == null)
            {
                throw new Exception("读取文档信息出错,当前文档不存在【正文】Sheet页!");
            }

            // 获取页眉
            if (CurrentSheet != null && CurrentSheet.Header != null)
            {
                //文档名称
                string FormName = CurrentSheet.Header.Center;
                if (!string.IsNullOrEmpty(FormName))
                    maintenance.FormName = patternToRemoveString(FormName).Trim();

                if (maintenance.FormName.Length > 100)
                {
                    throw new Exception("操作失败，点检表名称长度超限，最大长度为100字!");
                }

                string Other = CurrentSheet.Header.Right;
                if (!string.IsNullOrEmpty(Other))
                {
                    string[] os = patternToRemoveString(Other).Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
                    if (os.Length == 3)
                    {
                        maintenance.VersionCode = os[0].Trim().ToUpper();
                        if (maintenance.VersionCode != txtVersion.EditValue + "")
                        {
                            throw new Exception("操作失败，点检表版本与选定的版本不一致!");
                        }

                        maintenance.VersionRev = patternToRemoveString(os[1], "Rev版本:(\\s{0,})").Trim();
                    }
                    else
                    {
                        throw new Exception("操作失败，点检表文档编号或点检表版本不能为空！!");
                    }
                }
            }
            return maintenance;
        }

        /// <summary>
        /// 正则去除字符串
        /// </summary>
        /// <param name="inputText"></param>
        /// <returns></returns>
        string patternToRemoveString(string inputText, string patternToRemove = "&\"\\S*?\"")
        {
            return Regex.Replace(inputText, patternToRemove, string.Empty);
        }

        /// <summary>
        /// 获取页眉右侧单元格
        /// </summary>
        /// <param name="CurrentSheet"></param>
        /// <returns></returns>
        private Tuple<string, string, string> GetPageHeadVersionInfo(ISheet CurrentSheet)
        {
            try
            {
                Func<string, string, string> func = (s1, s2) =>
                  {
                      if (s2.IsNull())
                          s2 = "&\"\\S*?\"";

                      string s3 = Regex.Replace(s1, s2, string.Empty);
                      return s3;
                  };

                //文档名称
                string FormName = NPOI.XSSF.UserModel.Extensions.XSSFHeaderFooter.StripFields(CurrentSheet.Header.Center);
                if (!FormName.IsNull())
                    FormName = func(FormName, null).Trim();

                if (FormName.IsNull())
                {
                    throw new Exception("操作失败，点检表名称不能为空!");
                }

                if (FormName.Length > 100)
                {
                    throw new Exception("操作失败，点检表名称长度超限，最大长度为100字!");
                }

                string VersionInfo = CurrentSheet.Header.Right;
                if (!VersionInfo.IsNull())
                {
                    string[] infs = func(VersionInfo, null).Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
                    if (infs.Length == 3)
                    {
                        string VersionCode = infs[0].Trim().ToUpper();
                        if (VersionCode.IsNull())
                        {
                            throw new Exception("操作失败，点检表编码版本不能为空!");
                        }

                        if (VersionCode != txtVersion.EditValue + "")
                        {
                            throw new Exception("操作失败，点检表编码版本与选定的编码版本不一致!");
                        }

                        string VersionRev = func(infs[1].Replace("：", ":"), "Rev版本:(\\s{0,})").Trim();
                        if (VersionRev.IsNull())
                        {
                            throw new Exception("操作失败，点检表Rev版本不能为空!");
                        }

                        if (VersionRev.Length > 50)
                        {
                            throw new Exception("操作失败，点检表Rev版本长度不能超出50个字符!");
                        }

                        return Tuple.Create(FormName, VersionCode, VersionRev);
                    }
                    else
                    {
                        throw new Exception("操作失败，点检表文档页眉编号或点检表版本读取失败,格式不正确!");
                    }
                }
                else
                {
                    throw new Exception("操作失败，点检表中未检测到页眉数据！!");
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
    }
}