using System;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using NPOI.SS.UserModel;
using System.IO;
using NPOI.HSSF.UserModel;
using NPOI.XSSF.UserModel;
using System.Text.RegularExpressions;
using DeviceRepair.Models;
using DeviceRepairAndOptimization.Common;
using DeviceRepairAndOptimization.Biz;
using Newtonsoft.Json;

namespace DeviceRepairAndOptimization.Pages.FormVersion
{
    public partial class Page_FormVersionAdd : XtraForm
    {
        private int AutoId = 0;
        public string Caption;
        private MaintenanceFormVersionInfo subData;

        private int FileVer
        {
            get
            {
                return (int)radioGroup1.EditValue;
            }
        }

        public Page_FormVersionAdd(string FormTitle)
        {
            InitializeComponent();
            Caption = FormTitle;
        }

        public Page_FormVersionAdd(string FormTitle, int AutoID)
        {
            InitializeComponent();
            Caption = FormTitle;
            AutoId = AutoID;
        }

        private void Page_FormVersionAdd_Load(object sender, EventArgs e)
        {
            try
            {
                this.Text = Caption;
                xtraOpenFileDialog1.FileName = string.Empty;
                xtraOpenFileDialog1.Filter = "(*.xls)|*.xls;*.xlsx";
                xtraOpenFileDialog1.Multiselect = false;
                xtraOpenFileDialog1.Title = "请选择待导入的点检表Excel文件";

                if (AutoId != 0)
                {
                    splashScreenManager1.ShowWaitForm();
                    APIResponseData apiResponseData = FormManager.Instance.GetSingle(AutoId);
                    if (!apiResponseData.IsSuccess)
                        throw new Exception(apiResponseData.Message);

                    subData = apiResponseData.ToDeserializeObject<MaintenanceFormVersionInfo>();

                    //暂时禁用,后面改为替换
                    txt_FilePath.Enabled = false;
                    txt_FormName.Text = subData.FormName;
                    txt_Number.Text = subData.VersionCode;
                    txt_Rev.Text = subData.VersionRev;
                    txt_Remark.Text = subData.Remarks;
                    radioGroup1.EditValue = subData.VersionCode;
                    txt_FilePath.Text = "";
                    FormExtended.TryCloseWait(splashScreenManager1);
                }
            }
            catch (Exception ex)
            {
                subData = null;
                splashScreenManager1.TryCloseWait();
                XtraMessageBoxHelper.Error(ex.Message);
                this.DialogResult = DialogResult.Abort;
            }
        }

        private async void btn_Submit_Click(object sender, EventArgs e)
        {
            try
            {
                splashScreenManager1.ShowWaitForm();

                if (subData == null)
                    throw new Exception("请选择要上传的点检表");

                if (txt_Remark.Text.Length >= 2000)
                {
                    splashScreenManager1.TryCloseWait();
                    XtraMessageBoxHelper.Warn($"说明字段长度超出限制,请不要超过2000个字符！");
                    return;
                }

                if (subData.AutoID > 0)
                {
                    subData.ChangeUser = GlobalInfo.CurrentUser.AutoID;
                    subData.Remarks = txt_Remark.Text.Trim();
                    APIResponseData apiResponseData = FormManager.Instance.ChangeRemark(subData);
                    splashScreenManager1.TryCloseWait();

                    if (apiResponseData.IsSuccess)
                        XtraMessageBoxHelper.Info("操作成功！");
                    else
                        XtraMessageBoxHelper.Error(apiResponseData.Message);
                }
                else
                {
                    //新增
                    //上传到webservice
                    APIResponseData apiResponseData = await FormManager.Instance.UploadFile(txt_FilePath.Text);
                    if (!apiResponseData.IsSuccess)
                    {
                        splashScreenManager1.TryCloseWait();
                        XtraMessageBoxHelper.Error(apiResponseData.Message);
                        return;
                    }

                    subData.FormPath = apiResponseData.Data + "";
                    subData.CreatUser = GlobalInfo.CurrentUser.AutoID;
                    subData.Remarks = txt_Remark.Text.Trim();
                    subData.FormStatus = true;
                    apiResponseData = FormManager.Instance.InsertSingle(subData);

                    splashScreenManager1.TryCloseWait();
                    if (apiResponseData.IsSuccess)
                        XtraMessageBoxHelper.Info("操作成功！");
                    else
                        XtraMessageBoxHelper.Error(apiResponseData.Message);
                }
            }
            catch (Exception ex)
            {
                splashScreenManager1.TryCloseWait();
                XtraMessageBoxHelper.Error(ex.Message);
            }

            this.DialogResult = DialogResult.OK;
        }

        private void btn_Cancel_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.Cancel;
        }

        private void txt_FilePath_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            string FilePath = string.Empty;
            if (xtraOpenFileDialog1.ShowDialog() == DialogResult.OK)
            {
                // 将选择的文件路径显示在 ButtonEdit 控件中
                txt_FilePath.Text = xtraOpenFileDialog1.FileName;
                FilePath = xtraOpenFileDialog1.FileName;

                try
                {
                    splashScreenManager1.ShowWaitForm();

                    if (AutoId > 0)
                        subData = new MaintenanceFormVersionInfo() { AutoID = AutoId };
                    else
                        subData = new MaintenanceFormVersionInfo();
                    ReadInformation(FilePath);

                    splashScreenManager1.TryCloseWait();
                }
                catch (Exception ex)
                {
                    subData = null;
                    txt_FormName.Text = "";
                    txt_Number.Text = "";
                    txt_Rev.Text = "";
                    txt_Remark.Text = "";
                    txt_FilePath.Text = "";

                    splashScreenManager1.TryCloseWait();
                    XtraMessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                splashScreenManager1.TryCloseWait();
            }
        }

        /// <summary>
        /// 读取Excel内容
        /// </summary>
        /// <param name="filePath"></param>
        void ReadInformation(string filePath)
        {
            if (!string.IsNullOrEmpty(filePath))
            {
                // 检查文件类型是否是 Excel 文件
                if (Path.GetExtension(filePath).Equals(".xls", StringComparison.OrdinalIgnoreCase) ||
                    Path.GetExtension(filePath).Equals(".xlsx", StringComparison.OrdinalIgnoreCase))
                {
                    try
                    {
                        MaintenanceFormVersionInfo entity = null;
                        using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                        {
                            string fileExtension = Path.GetExtension(filePath);

                            if (fileExtension.Equals(".xls", StringComparison.OrdinalIgnoreCase))
                            {
                                // 如果是 .xls 文件
                                HSSFWorkbook workbook = new HSSFWorkbook(fileStream);
                                entity = ReadHeaderFromWorkbook(workbook);
                            }
                            else if (fileExtension.Equals(".xlsx", StringComparison.OrdinalIgnoreCase))
                            {
                                // 如果是 .xlsx 文件
                                XSSFWorkbook workbook = new XSSFWorkbook(fileStream);
                                entity = ReadHeaderFromWorkbook(workbook);
                            }
                            else
                            {
                                // 不支持的文件类型
                                throw new NotSupportedException("不支持的文件类型");
                            }
                        }

                        if (entity != null)
                        {
                            //检测当前文档是否存在
                            APIResponseData apiResponseData = FormManager.Instance.DataIsExists(entity);
                            if (!apiResponseData.IsSuccess)
                                throw new Exception(apiResponseData.Message);

                            if (Convert.ToBoolean(apiResponseData.Data))
                            {
                                throw new Exception("当前点检表已存在!");
                            }

                            //返回到UI
                            subData.FormName = entity.FormName;
                            subData.VersionCode = entity.VersionCode;
                            subData.VersionRev = entity.VersionRev;

                            txt_FormName.Text = entity.FormName;
                            txt_Number.Text = entity.VersionCode;
                            txt_Rev.Text = entity.VersionRev;
                        }
                        else
                        {
                            throw new Exception("请选择点检表文件！");
                        }
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                }
                else
                {
                    new Exception("请选择有效的 Excel 文件！");
                }
            }
            else
            {
                new Exception("请选择要上传的文件！");
            }
        }

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

            // 获取第一个工作表
            ISheet CurrentSheet = null;
            int SheetCount = workbook.NumberOfSheets;
            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 != radioGroup1.EditValue + "")
                        {
                            throw new Exception("操作失败，点检表版本与选定的版本不一致!");
                        }

                        maintenance.VersionRev = patternToRemoveString(os[1], "Rev版本:(\\s).?").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);
        }
    }
}