using DevExpress.Spreadsheet;
using DevExpress.XtraEditors;
using DevExpress.XtraSpreadsheet;
using DevExpress.XtraSpreadsheet.Menu;
using DeviceRepairAndOptimization.Models;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text.RegularExpressions;
using System.Windows.Forms;
using System.Linq;
using System.Threading.Tasks;
using DevExpress.Utils.Menu;
using DeviceRepairAndOptimization.Common;
using DeviceRepairAndOptimization.Biz;

namespace DeviceRepairAndOptimization.Pages.DriveMaintenance
{
    public partial class xuc_DriveMaintenance : XtraUserControl
    {
        SheetDatasModel vls = new SheetDatasModel();

        private const string pattern = @"^[a-zA-Z][1-9]\d*$";

        /// <summary>
        /// 窗体未显示到的行数
        /// </summary>
        int SubRowsCount = 0;
        /// <summary>
        /// 窗体未显示到的列数
        /// </summary>
        int SubColumnsCount = 0;

        string TemplatePath = string.Empty;
        DriveInfomationModel driveInfo;

        List<Cell> EditCell;
        List<Cell> CanEditCell;
        List<Cell> SignatureEditCell;
        List<Cell> DateEditCell;

        /// <summary>
        /// 照片集合
        /// </summary>
        public Image[] Images
        {
            get
            {
                try
                {
                    List<Image> ls = new List<Image>();
                    foreach (Control item in imgs_Content.Controls)
                    {
                        if (item.GetType() == typeof(PictureEdit))
                        {
                            ls.Add(((PictureEdit)item).Image);
                        }
                    }
                    return ls.ToArray();
                }
                catch
                {
                    return null;
                }
            }
        }

        /// <summary>
        /// 上传的其他文件
        /// </summary>
        public string File
        {
            get
            {
                return txt_FilePath.Text;
            }
        }

        /// <summary>
        /// 获取excel的数据集
        /// </summary>
        public byte[] GetExcelFileBytes
        {
            get
            {
                try
                {
                    return worksheet.Workbook.SaveDocument(DocumentFormat.Xlsx);
                }
                catch
                {
                    return null;
                }
            }
        }


        public Worksheet worksheet
        {
            get
            {
                return excelControl.Document.Worksheets.ActiveWorksheet;
            }
        }

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

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

        #region 有效数据行总高度
        /// <summary>
        /// 有效数据行总高度
        /// </summary>
        private double _RowHeightSum = 0;
        private double RowHeightSum
        {
            get
            {
                if (_RowHeightSum > 0)
                    return _RowHeightSum;

                if (worksheet == null)
                    return _RowHeightSum;

                for (int i = LastUsedRowIndex; i > 0; i--)
                {
                    _RowHeightSum += worksheet.Rows[i].RowHeight * (double)ZoomValue / 100;
                    if (_RowHeightSum < excelControl.Height)
                    {
                        SubRowsCount++;
                    }
                    else
                    {
                        SubRowsCount = SubRowsCount * 2;
                        break;
                    }
                }
                return _RowHeightSum;
            }
        }
        #endregion

        #region 有效数据列总宽度
        /// <summary>
        /// 有效数据列总宽度
        /// </summary>
        private double _ColumnWidthSum = 0;
        private double ColumnWidthSum
        {
            get
            {
                if (_ColumnWidthSum > 0)
                    return _ColumnWidthSum;

                if (worksheet == null)
                    return _ColumnWidthSum;

                for (int i = LastUsedColumnIndex; i > 0; i--)
                {
                    _ColumnWidthSum += worksheet.Columns[i].ColumnWidth * (double)ZoomValue / 100;
                    if (_ColumnWidthSum < excelControl.Width)
                    {
                        SubColumnsCount++;
                    }
                    else
                    {
                        SubColumnsCount = SubColumnsCount * 2;
                        break;
                    }
                }
                return _ColumnWidthSum;
            }
        }
        #endregion

        private Cell CurrentCell;

        // 创建右键菜单
        SpreadsheetPopupMenu popupMenu;
        SpreadsheetPopupMenu popupMenuContent;
        SpreadsheetPopupMenu popupMenuUser;
        SpreadsheetPopupMenu popupMenuDate;

        List<ExcelContent> Datas = new List<ExcelContent>();

        int ZoomValue
        {
            get
            {
                return excelControl.ActiveWorksheet.ActiveView.Zoom;
            }
        }

        public xuc_DriveMaintenance(DriveInfomationModel entity, string templatePath)
        {
            InitializeComponent();
            TemplatePath = templatePath;
            driveInfo = entity;
        }

        /// <summary>
        /// 程序加载
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void xuc_DriveMaintenance_Load(object sender, EventArgs e)
        {
            splashScreenManager1.ShowWaitForm();

            LoadingTemplate();

            //获取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)
            {
                //开启横向滚动条
                excelControl.Options.HorizontalScrollbar.Visibility = SpreadsheetScrollbarVisibility.Visible;
            }

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

                    //判断是否为编辑列
                    if (cell != null && EditCell.IndexOf(cell) >= 0)
                    {
                        if (cell.IsMerged)
                        {
                            //获取主单元格位置
                            int top = (cell.GetMergedRanges()[0]).TopRowIndex;
                            int left = (cell.GetMergedRanges()[0]).LeftColumnIndex;

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

                        popupMenu.ShowPopup(excelControl, new Point(ev.X, ev.Y));
                    }
                    else
                    //判断是否为异常填写
                    if (CanEditCell.IndexOf(cell) >= 0)
                    {
                        if (cell.IsMerged)
                        {
                            //获取主单元格位置
                            int top = (cell.GetMergedRanges()[0]).TopRowIndex;
                            int left = (cell.GetMergedRanges()[0]).LeftColumnIndex;

                            CurrentCell = worksheet.Cells[top, left];
                        }
                        popupMenuContent.ShowPopup(excelControl, new Point(ev.X, ev.Y));
                    }
                    else
                    //保养签名
                    if (SignatureEditCell.IndexOf(cell) >= 0)
                    {
                        if (cell.IsMerged)
                        {
                            //获取主单元格位置
                            int top = (cell.GetMergedRanges()[0]).TopRowIndex;
                            int left = (cell.GetMergedRanges()[0]).LeftColumnIndex;

                            CurrentCell = worksheet.Cells[top, left];
                        }
                        else
                        {
                            CurrentCell = cell;
                        }
                        popupMenuUser.ShowPopup(excelControl, new Point(ev.X, ev.Y));
                    }
                    else
                    //保养日期
                    if (DateEditCell.IndexOf(cell) >= 0)
                    {
                        if (cell.IsMerged)
                        {
                            //获取主单元格位置
                            int top = (cell.GetMergedRanges()[0]).TopRowIndex;
                            int left = (cell.GetMergedRanges()[0]).LeftColumnIndex;

                            CurrentCell = worksheet.Cells[top, left];
                        }
                        else
                        {
                            CurrentCell = cell;
                        }
                        popupMenuDate.ShowPopup(excelControl, new Point(ev.X, ev.Y));
                    }
                }
            };


            popupMenu = new SpreadsheetPopupMenu()
            {
                //正常:√ 紧固:N 给油:U 清洁:C 修理:R 调整:T 替换:H   有问题打△并写在异常处理拦,不适用或无生产打N/A，
                Items =
                {
                    new DXMenuItem("正常",(a,aa)=>{CurrentCell.Value = "√"; ChangeDatas(ExcelContentType.Text,"√"); } ),
                    new DXMenuItem("紧固",(a,aa)=>{CurrentCell.Value = "N"; ChangeDatas(ExcelContentType.Text,"N"); } ),
                    new DXMenuItem("给油",(a,aa)=>{CurrentCell.Value = "U"; ChangeDatas(ExcelContentType.Text,"U"); } ),
                    new DXMenuItem("清洁",(a,aa)=>{CurrentCell.Value = "C"; ChangeDatas(ExcelContentType.Text,"C"); } ),
                    new DXMenuItem("修理",(a,aa)=>{CurrentCell.Value = "R"; ChangeDatas(ExcelContentType.Text,"R"); } ),
                    new DXMenuItem("调整",(a,aa)=>{CurrentCell.Value = "T"; ChangeDatas(ExcelContentType.Text,"T"); } ),
                    new DXMenuItem("替换",(a,aa)=>{CurrentCell.Value = "H"; ChangeDatas(ExcelContentType.Text,"H"); } ),
                    new DXMenuItem("有问题",(a,aa)=>{CurrentCell.Value = "△"; ChangeDatas(ExcelContentType.Text,"△"); } ),
                    new DXMenuItem("不适用或无生产",(a,aa)=>{CurrentCell.Value = "N/A";  ChangeDatas(ExcelContentType.Text,"N/A");} ),
                    new DXMenuItem("清空",(a,aa)=>{CurrentCell.Value = "";  ChangeDatas(ExcelContentType.Text,"",true);} ),
                }
            };

            //其它异常处理
            popupMenuContent = new SpreadsheetPopupMenu()
            {
                Items =
                {
                     new DXMenuItem("编辑",(a,aa)=>
                     {
                        // 显示输入框
                        string result = XtraInputBox.Show("其它异常处理:", "输入框", "");
                         // 设置单元格的文本格式
                        CurrentCell.BeginUpdate();
                        CurrentCell.Alignment.Vertical = SpreadsheetVerticalAlignment.Top;
                        CurrentCell.Alignment.Horizontal = SpreadsheetHorizontalAlignment.Left;
                        CurrentCell.EndUpdate();
                        CurrentCell.Value += result;
                        ChangeDatas(ExcelContentType.Text,result,string.IsNullOrEmpty(result));
                     } ),
                }
            };

            //签名
            popupMenuUser = new SpreadsheetPopupMenu()
            {
                Items =
                {
                     new DXMenuItem("签名",(a,aa)=> { CurrentCell.Value = GlobalInfo.CurrentUser.RealName; } ),
                     new DXMenuItem("清空",(a,aa)=> { CurrentCell.Value = ""; ChangeDatas(ExcelContentType.Text,"",true);} ),
                }
            };

            //时间
            popupMenuDate = new SpreadsheetPopupMenu()
            {
                Items =
                {
                     new DXMenuItem("时间",(a,aa)=>
                     {
                         // 创建 DateEdit 控件
                        DateEdit dateEdit = new DateEdit(){ Width = 800,Height = 320 };
                        dateEdit.Properties.CalendarView = DevExpress.XtraEditors.Repository.CalendarView.Fluent;

                        // 弹出式日期选择框
                        if (XtraDialog.Show(dateEdit, "选择日期", MessageBoxButtons.OKCancel) == DialogResult.OK)
                        {
                            // 用户点击了确定按钮，获取选定的日期
                            DateTime selectedDate = dateEdit.DateTime;
                              CurrentCell.Value = selectedDate.ToString("yyyy年MM月dd日");
                        }
                     } ),
                      new DXMenuItem("清空",(a,aa)=>
                     {
                         CurrentCell.Value = "";
                         ChangeDatas(ExcelContentType.Text,"",true);
                     } ),
                }
            };

            splashScreenManager1.TryCloseWait();
        }

        /// <summary>
        /// 表单发生更改
        /// </summary>
        /// <param name="contentType"></param>
        /// <param name="value"></param>
        /// <param name="beClear"></param>
        void ChangeDatas(ExcelContentType contentType, string value, bool beClear = false)
        {
            if (beClear)
            {
                ExcelContent entity = Datas.Where(x => x.RowIndex == CurrentCell.RowIndex && x.ColumnIndex == CurrentCell.ColumnIndex).FirstOrDefault();
                if (entity != null)
                    Datas.Remove(entity);
            }
            else
            {
                Datas.Add(new ExcelContent
                {
                    ColumnIndex = CurrentCell.ColumnIndex,
                    RowIndex = CurrentCell.RowIndex,
                    ContentType = contentType,
                    Text = value
                });
            }
        }


        void LoadingTemplate()
        {
            //// 创建并显示等待窗口
            //SplashScreenManager.ShowDefaultWaitForm("加载模板", "请稍等...");

            //执行耗时操作
            //取当前运行目录
            string currentDirectory = Application.StartupPath;

            //string filePath = Path.Combine(currentDirectory, "Download", TemplatePath);
            excelControl.LoadDocument(IOExtend.FileToByteArray(TemplatePath));
            //excelControl.LoadDocument(TemplatePath);

            if (excelControl.Document.Worksheets.Contains("正文"))
                excelControl.Document.Worksheets.ActiveWorksheet = excelControl.Document.Worksheets["正文"];
            excelControl.ActiveWorksheet.ActiveView.Zoom = 145;

            excelControl.DocumentLoaded += (s, e) =>
            {
                EditCell = new List<Cell>();
                CanEditCell = new List<Cell>();
                SignatureEditCell = new List<Cell>();
                DateEditCell = new List<Cell>();

                //设置基本信息
                for (int i = 0; i < LastUsedRowIndex; i++)
                {
                    CellValue value = worksheet.Cells[i, 0].Value;
                    //填写设备型号,设备序号,年份信息
                    if (value.IsText && value.TextValue == "序号")
                    {
                        for (int j = 1; j < LastUsedColumnIndex; j++)
                        {
                            value = worksheet.Cells[i, j].Value;
                            if (value.IsText && value.TextValue.Contains("设备型号"))
                            {
                                value = worksheet.Cells[i, j + 1].Value;
                                if (value.IsEmpty)
                                {
                                    worksheet.Cells[i, j + 1].Value = driveInfo.EquipmentName;
                                    j++;
                                }
                            }
                            else if (value.IsText && value.TextValue.Contains("设备编号"))
                            {
                                value = worksheet.Cells[i, j + 1].Value;
                                if (value.IsEmpty)
                                {
                                    worksheet.Cells[i, j + 1].Value = driveInfo.EquipmentID;
                                    j++;
                                }
                            }
                            else if (value.IsText && value.TextValue.IndexOf("标记") >= 0 && value.TextValue.IndexOf("并写在异常处理拦,不适用或无生产打") >= 0)
                            {
                                worksheet.Cells[i, j].Value = value.TextValue.Replace("      年", DateTime.Now.Year + "年");
                            }
                        }
                    }
                    else if (value.IsText && Regex.IsMatch(value.TextValue.Trim(), pattern))
                    {
                        //如果首列的内容为  单英文开头+ N*数字结束,则判断为需填写的列
                        for (int j = 1; j < LastUsedColumnIndex; j++)
                        {
                            value = worksheet.Cells[i, j].Value;

                            if (worksheet.Cells[i, j].IsMerged)
                            {
                                //获取主单元格位置
                                int top = (worksheet.Cells[i, j].GetMergedRanges()[0]).TopRowIndex;
                                int left = (worksheet.Cells[i, j].GetMergedRanges()[0]).LeftColumnIndex;
                                if (!worksheet.Cells[top, left].Value.IsEmpty)
                                    continue;
                            }

                            if (value.IsEmpty)
                            {
                                // 获取指定单元格的图片集合
                                var picturesInCell = worksheet.Pictures.Where(picture =>
                                picture.TopLeftCell.RowIndex <= i &&
                                picture.BottomRightCell.RowIndex >= i &&
                                picture.TopLeftCell.ColumnIndex <= j &&
                                picture.BottomRightCell.ColumnIndex >= j);

                                if (picturesInCell.Any())
                                    continue;

                                EditCell.Add(worksheet.Cells[i, j]);
                            }
                        }
                    }
                    else if (value.IsText && value.TextValue.Replace("\n", "").Trim() == "其它异常处理" && worksheet.Cells[i, 1].IsMerged)
                    {
                        //异常处理信息
                        List<CellRange> cells = worksheet.Cells[i, 1].GetMergedRanges().ToList();
                        if (cells != null && cells.Count == 1)
                        {
                            CanEditCell.AddRange(cells[0]);

                            //保养日期
                            value = worksheet.Cells[i, cells[0].RightColumnIndex + 1].Value;
                            if (value.IsText && value.TextValue.Replace("\n", "").Trim() == "保养签名")
                            {
                                for (int j = cells[0].RightColumnIndex + 2; j < LastUsedColumnIndex; j++)
                                {
                                    SignatureEditCell.Add(worksheet.Cells[i, j]);
                                }
                            }

                            //保养签名
                            value = worksheet.Cells[i + 1, cells[0].RightColumnIndex + 1].Value;
                            if (value.IsText && value.TextValue.Replace("\n", "").Trim() == "保养日期")
                            {
                                for (int j = cells[0].RightColumnIndex + 2; j < LastUsedColumnIndex; j++)
                                {
                                    DateEditCell.Add(worksheet.Cells[i + 1, j]);
                                }
                            }
                        }
                    }
                }

                // 关闭等待窗口
                //SplashScreenManager.CloseDefaultWaitForm();
            };
        }

        private void excelControl_ScrollPositionChanged(object sender, ScrollPositionChangedEventArgs e)
        {
            Task.Run(() =>
            {
                if (RowHeightSum > this.excelControl.Height)
                {
                    if (e.RowIndex > (LastUsedRowIndex - SubRowsCount))
                        Invoke(new Action(() => { worksheet.ScrollToRow(LastUsedRowIndex - SubRowsCount); }));
                }

                if (ColumnWidthSum > this.excelControl.Width)
                {
                    if (e.ColumnIndex > (LastUsedColumnIndex - SubColumnsCount))
                        Invoke(new Action(() => { worksheet.ScrollToColumn(LastUsedColumnIndex - SubColumnsCount); }));
                }
            });
        }

        /// <summary>
        /// 取消右键菜单的显示
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void excelControl_PopupMenuShowing(object sender, PopupMenuShowingEventArgs e)
        {
            e.Menu = null;
        }

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

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

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

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

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

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

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

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

}
