using DevExpress.XtraBars;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Views.Grid;
using DeviceRepair.Models;
using DeviceRepair.Models.Tag;
using Newtonsoft.Json;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
using TsSFCDeivceClient.Common;
using TsSFCDeivceClient.Model;
using TsSFCDevice.Control;
using TsSFCDevice.Control.CustomFormatProvider;
using TsSFCDevice.Control.Tag;

namespace TsSFCDeivceClient.View.Tag
{
    public partial class TagFormView : DevExpress.XtraBars.Ribbon.RibbonForm
    {
        private TagRecordInfo m_CurrentObject;

        private TagRecordFilter _filter;
        public TagRecordFilter filter
        {
            get
            {
                if (_filter == null)
                    _filter = new TagRecordFilter();
                _filter.EquipmentDisPlayID = barIpsEquipmentID.EditValue + "";
                _filter.TagFormStatus = TagStatus;
                _filter.sDate = StartDate;
                _filter.eDate = EndDate;
                return _filter;
            }
        }

        /// <summary>
        /// 设备编号
        /// </summary>
        public string EquipmentNo { get { return barIpsEquipmentID.EditValue + ""; } }

        /// <summary>
        /// Tag 状态
        /// </summary>
        public string TagStatus
        {
            get
            {
                string status = "";
                switch (barIpsStatus.EditValue + "")
                {
                    case "已提交":
                        status = "N";
                        break;
                    case "已完成":
                        status = "C";
                        break;
                    default:
                        break;
                }
                return status;
            }
        }

        /// <summary>
        /// 开始时间
        /// </summary>
        public DateTime StartDate
        {
            get
            {
                DateTime t = DateTime.Today.AddDays(-7);
                DateTime.TryParse(barIpsStartDate.EditValue + "", out t);
                return t;
            }
            set
            {
                barIpsStartDate.EditValue = value;
            }
        }

        /// <summary>
        /// 结束数据
        /// </summary>
        public DateTime EndDate
        {
            get
            {
                DateTime t = DateTime.Today.AddDays(1).AddMilliseconds(-1);
                DateTime.TryParse(barIpsEndDate.EditValue + "", out t);
                return t;
            }
            set
            {
                barIpsEndDate.EditValue = value;
            }
        }

        public TagFormView(UserInfo user, string APPVERSION = "5.0.0.0")
        {
            InitializeComponent();

            Runtime.CurrentUser = user;
            Runtime.inParams = JsonConvert.SerializeObject(new { OPERATORGUID = user.GUID, OPERATOR = user.UserCode, CLIENTIP = ComputerHelper.Instance().IpAddress, CLIENTMAC = ComputerHelper.Instance().MacAddress, CLIENTNAME = ComputerHelper.Instance().ComputerName, APPVERSION = APPVERSION });
        }

        private void TagFormView_Load(object sender, EventArgs e)
        {
            if (Runtime.CurrentUser == null)
            {
                TsSFCDevice.Control.XtraMessageBoxHelper.Error($"非法的调用，请重试。");
                this.Close();
            }

            if (string.IsNullOrWhiteSpace(RunConfig.config.ServiceApiUrl))
            {
                TsSFCDevice.Control.XtraMessageBoxHelper.Error($"缺少配置字段（设备管理软件接口地址）【ServiceApiUrl】。");
                this.Close();
            }

            #region 控件右键菜单屏蔽

            ribbonControl1.AllowCustomization = false;
            ribbonControl1.AllowMinimizeRibbon = false;
            ribbonControl1.ShowCustomizationMenu += (ss, ee) => { ee.ShowCustomizationMenu = false; };
            gridView1.OptionsMenu.EnableColumnMenu = false;

            #endregion

            #region 初始化搜索字段

            StartDate = DateTime.Today.AddDays(-7);
            EndDate = DateTime.Today.AddDays(1).AddMilliseconds(-1);

            #endregion

            #region 表格样式初始化

            gridView1.OptionsBehavior.Editable = false;
            gridView1.OptionsBehavior.ReadOnly = true;


            gridView1.OptionsSelection.EnableAppearanceFocusedCell = false;
            gridView1.OptionsScrollAnnotations.ShowSelectedRows = DevExpress.Utils.DefaultBoolean.False;
            gridView1.OptionsSelection.ShowCheckBoxSelectorInColumnHeader = DevExpress.Utils.DefaultBoolean.False;
            gcStatus.DisplayFormat.FormatType = DevExpress.Utils.FormatType.Custom;
            gcStatus.DisplayFormat.Format = new StatusFormatter();
            gcStatus.DisplayFormat.FormatString = "tag";

            foreach (DevExpress.XtraGrid.Columns.GridColumn item in gridView1.Columns)
            {
                item.OptionsColumn.AllowEdit = false;
                item.OptionsColumn.AllowGroup = DevExpress.Utils.DefaultBoolean.True;
                item.OptionsColumn.AllowMerge = DevExpress.Utils.DefaultBoolean.False;
                item.OptionsColumn.AllowShowHide = false;
            }

            if (Runtime.UserHasAuth(AuthCodeConstValue.Tag_WATCH))
            {
                InitializeDataSource(false);
            }

            #endregion

        }

        /// <summary>
        /// 自增长行号
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridView_CustomDrawRowIndicator(object sender, RowIndicatorCustomDrawEventArgs e)
        {
            if (e.Info.IsRowIndicator && e.RowHandle >= 0)
            {
                e.Info.DisplayText = (e.RowHandle + 1).ToString();
                e.Appearance.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Center;
                e.Appearance.TextOptions.VAlignment = DevExpress.Utils.VertAlignment.Center;
            }
        }

        List<TagRecordInfo> tags;
        /// <summary>
        /// 初始化数据
        /// </summary>
        private void InitializeDataSource(bool InitializeView = true)
        {
            try
            {
                splashScreenManager1.ShowWaitForm();

                if (filter.sDate > filter.eDate)
                    throw new Exception("开始时间无法大于结束时间!");

                APIResponseData apiResponseData = Biz.HttpHelper.Instance.Post($"{RunConfig.config.ServiceApiUrl}{DeviceApiUrlConstValue.Tag_Get_Datas}", JsonConvert.SerializeObject(filter));

                if (!apiResponseData.IsSuccess)
                    throw new Exception(apiResponseData.Message);

                tags = apiResponseData.ToDeserializeObject<List<TagRecordInfo>>();

                SizeF size = this.CreateGraphics().MeasureString((tags.Count).ToString(), gridView1.Appearance.ViewCaption.Font);
                gridView1.IndicatorWidth = Convert.ToInt32(size.Width) + 25;

                gridControl1.DataSource = tags;
                if (InitializeView)
                    gridView_RowCellClick(gridView1, new RowCellClickEventArgs(new DevExpress.Utils.DXMouseEventArgs(MouseButtons.Left, 1, 1, 1, 1), 0, gcTagNo));
                splashScreenManager1.TryCloseWait();
            }
            catch (Exception ex)
            {
                splashScreenManager1.TryCloseWait();
                TsSFCDevice.Control.XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        /// <summary>
        /// 单元格点击事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void gridView_RowCellClick(object sender, RowCellClickEventArgs e)
        {
            try
            {
                if (e.Button != MouseButtons.Right)
                {
                    m_CurrentObject = gridView1.GetRow(e.RowHandle) as TagRecordInfo;
                    if (m_CurrentObject != null)
                    {
                        string status = m_CurrentObject.TagFormStatus;
                        if (status == "N")
                        {
                            btnExportXlsx.Enabled = false;
                            btnExportPdf.Enabled = false;
                            btnPrint.Enabled = false;
                            btnEdit.Enabled = true;
                        }
                        else if (status == "C")
                        {
                            btnExportXlsx.Enabled = true;
                            btnExportPdf.Enabled = true;
                            btnPrint.Enabled = true;
                            btnEdit.Enabled = false;
                        }

                        if (!xueTagForm1.Visible)
                            xueTagForm1.Visible = true;

                        xueTagForm1.CurrentData = m_CurrentObject;
                    }
                }
            }
            catch (Exception ex)
            {
                TsSFCDevice.Control.XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        /// <summary>
        /// 数据查询
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnQuery_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (!Runtime.UserHasAuth(AuthCodeConstValue.Tag_WATCH))
            {
                Common.XtraMessageBoxHelper.Error($"当前账号缺少此操作的权限");
                return;
            }

            // 数据加载
            InitializeDataSource();
        }

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCreat_ItemClick(object sender, ItemClickEventArgs e)
        {
            try
            {
                if (!Runtime.UserHasAuth(AuthCodeConstValue.Tag_ADD))
                {
                    Common.XtraMessageBoxHelper.Error($"当前账号缺少此操作的权限");
                    return;
                }

                var vCtlTemp = new xueTagForm() { Dock = DockStyle.Fill, Size = new Size(480, 850) };
                vCtlTemp.HideReceipt();

                Form f = new Form() { Text = "Tag 新增", Size = new Size(530, 700), StartPosition = FormStartPosition.CenterScreen, WindowState = FormWindowState.Normal };
                DevExpress.Utils.Layout.StackPanel sp = new DevExpress.Utils.Layout.StackPanel() { Dock = DockStyle.Bottom, Height = 70, Padding = new Padding(10), LayoutDirection = DevExpress.Utils.Layout.StackPanelLayoutDirection.RightToLeft };
                SidePanel sp2 = new SidePanel() { Dock = DockStyle.Fill };

                SimpleButton add = new SimpleButton { Text = "Tag新增", Width = 120, Height = 38 };
                SimpleButton cancel = new SimpleButton { Text = "取消", Width = 120, Height = 38 };

                vCtlTemp.SelectDeviceDialog += VCtlTemp_SelectedDevice;
                vCtlTemp.TagDataSaved += VCtlTemp_DataSaved;
                cancel.Click += (ss, ee) => { f.Close(); };
                add.Click += (ss, ee) =>
                {
                    if (!vCtlTemp.CanClose())
                        return;
                    f.Close();
                };
                f.Controls.Add(sp2);
                f.Controls.Add(sp);
                sp2.Controls.Add(vCtlTemp);
                sp.Controls.Add(cancel);
                sp.Controls.Add(add);
                f.ShowDialog(this);
            }
            catch (Exception ex)
            {
                TsSFCDevice.Control.XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        /// <summary>
        /// 选择设备
        /// </summary>
        private void VCtlTemp_SelectedDevice(xueTagForm tagView)
        {
            using (pageDeivceView view = new pageDeivceView())
            {
                view.Text = "设备选择";
                if (view.ShowDialog(this) == DialogResult.OK)
                {
                    DeviceInformationInfo CurrentDeviceInfo = view.CurrentDeviceInfo;
                    tagView.CurrentData = new TagRecordInfo
                    {
                        EquipmentDisPlayID = CurrentDeviceInfo.EquipmentID,
                        EquipmentID = CurrentDeviceInfo.AutoID,
                        EquipmentName = CurrentDeviceInfo.EquipmentName,
                        CreatorName = Runtime.CurrentUser.UserName,
                        CreatOn = DateTime.Today
                    };
                }
                else
                {
                    tagView.FindForm().Close();
                }
            }
        }

        private void VCtlTemp_DataSaved(TagRecordInfo tag)
        {
            try
            {
                splashScreenManager1.ShowWaitForm();
                APIResponseData apiResponseData = Biz.HttpHelper.Instance.Post($"{RunConfig.config.ServiceApiUrl}{DeviceApiUrlConstValue.Tag_Creat_Record}", JsonConvert.SerializeObject(tag));

                if (!apiResponseData.IsSuccess)
                    throw new Exception(apiResponseData.Message);

                TagRecordInfo tagRecord = apiResponseData.ToDeserializeObject<TagRecordInfo>();
                if (tags == null)
                {
                    tags = new List<TagRecordInfo>();
                    gridControl1.DataSource = tags;
                }

                TagRecordInfo item = tags.FirstOrDefault(x => x.AutoID == tagRecord.AutoID);
                if (item != null)
                {
                    item.EquipmentID = tagRecord.EquipmentID;
                    item.EquipmentDisPlayID = tagRecord.EquipmentDisPlayID;
                    item.EquipmentName = tagRecord.EquipmentName;
                    item.BrokenDamaged = tagRecord.BrokenDamaged;
                    item.Access = tagRecord.Access;
                    item.Clean = tagRecord.Clean;
                    item.Inspect = tagRecord.Inspect;
                    item.SourceOfContamination = tagRecord.SourceOfContamination;
                    item.NotInUse = tagRecord.NotInUse;
                    item.NotNeeded = tagRecord.NotNeeded;
                    item.UnsafeConditions = tagRecord.UnsafeConditions;
                    item.MissingComponents = tagRecord.MissingComponents;
                    item.DetailsOfIssue = tagRecord.DetailsOfIssue;
                    item.TagFormStatus = tagRecord.TagFormStatus;
                    item.CreateBy = tagRecord.CreateBy;
                    item.CreatOn = tagRecord.CreatOn;
                    item.CreatorName = tagRecord.CreatorName;
                    item.ModifyBy = tagRecord.ModifyBy;
                    item.ModifyOn = tagRecord.ModifyOn;
                    item.ModifyName = tagRecord.ModifyName;
                    item.ReceiptBy = tagRecord.ReceiptBy;
                    item.ReceiptOn = tagRecord.ReceiptOn;
                    item.ReceiptName = tagRecord.ReceiptName;
                    item.ReceiptDetailsOfIssue = tagRecord.ReceiptDetailsOfIssue;
                }
                else
                {
                    tags.Add(tagRecord);
                }

                gridView1.RefreshData();
                gridView1.FocusedRowHandle = gridView1.RowCount - 1;
                gridView1.SelectRow(gridView1.RowCount - 1);
                gridView_RowCellClick(gridView1, new RowCellClickEventArgs(new DevExpress.Utils.DXMouseEventArgs(MouseButtons.Left, 1, 1, 1, 1), (gridView1.RowCount - 1), gcTagNo));

                splashScreenManager1.TryCloseWait();
                TsSFCDevice.Control.XtraMessageBoxHelper.Info("操作成功!");
            }
            catch (Exception ex)
            {
                splashScreenManager1.TryCloseWait();
                TsSFCDevice.Control.XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        private void ipsEquipmentID_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            ((sender as ButtonEdit)).EditValue = "";
        }

        private void btnExportPdf_ItemClick(object sender, ItemClickEventArgs e)
        {

        }

        private void btnPrint_ItemClick(object sender, ItemClickEventArgs e)
        {

        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void barButtonItem1_ItemClick(object sender, ItemClickEventArgs e)
        {
            try
            {
                if (!Runtime.UserHasAuth(AuthCodeConstValue.Tag_ALTER))
                {
                    Common.XtraMessageBoxHelper.Error($"当前账号缺少此操作的权限");
                    return;
                }

                if (m_CurrentObject == null)
                {
                    TsSFCDevice.Control.XtraMessageBoxHelper.Error($"请选择要操作的数据!");
                    return;
                }

                if (m_CurrentObject.TagFormStatus != "N")
                {
                    TsSFCDevice.Control.XtraMessageBoxHelper.Error($"当前状态的表单无法修改!");
                    return;
                }

                var vCtlTemp = new xueTagForm() { Dock = DockStyle.Fill, Size = new Size(480, 850) };
                vCtlTemp.HideReceipt();

                Form f = new Form() { Text = "Tag 修改", Size = new Size(530, 700), StartPosition = FormStartPosition.CenterScreen, WindowState = FormWindowState.Normal };
                DevExpress.Utils.Layout.StackPanel sp = new DevExpress.Utils.Layout.StackPanel() { Dock = DockStyle.Bottom, Height = 70, Padding = new Padding(10), LayoutDirection = DevExpress.Utils.Layout.StackPanelLayoutDirection.RightToLeft };
                SidePanel sp2 = new SidePanel() { Dock = DockStyle.Fill };

                SimpleButton add = new SimpleButton { Text = "Tag修改", Width = 120, Height = 38 };
                SimpleButton cancel = new SimpleButton { Text = "取消", Width = 120, Height = 38 };

                vCtlTemp.CurrentData = m_CurrentObject;
                vCtlTemp.TagDataSaved += VCtlTemp_DataSaved;
                cancel.Click += (ss, ee) => { f.Close(); };
                add.Click += (ss, ee) =>
                {
                    if (!vCtlTemp.CanClose())
                        return;
                    f.Close();
                };
                f.Controls.Add(sp2);
                f.Controls.Add(sp);
                sp2.Controls.Add(vCtlTemp);
                sp.Controls.Add(cancel);
                sp.Controls.Add(add);
                f.ShowDialog(this);
            }
            catch (Exception ex)
            {
                TsSFCDevice.Control.XtraMessageBoxHelper.Error(ex.Message);
                return;
            }
        }

        private void btnExportXlsx_ItemClick(object sender, ItemClickEventArgs e)
        {
            try
            {
                FolderBrowserDialog dlg = new FolderBrowserDialog();
                if (dlg.ShowDialog(this) == DialogResult.OK)
                {
                    string path = dlg.SelectedPath.ToString();
                    try
                    {
                        splashScreenManager1.ShowWaitForm();

                        APIResponseData apiResponseData = Biz.HttpHelper.Instance.Post($"{RunConfig.config.ServiceApiUrl}{DeviceApiUrlConstValue.Tag_Get_Datas}", JsonConvert.SerializeObject(filter));

                        if (!apiResponseData.IsSuccess)
                            throw new Exception(apiResponseData.Message);

                        List<TagRecordInfo> Datas = apiResponseData.ToDeserializeObject<List<TagRecordInfo>>();

                        IWorkbook workbook = new XSSFWorkbook();
                        ISheet sheet = workbook.CreateSheet($"Tag");

                        // 样式获取
                        ICellStyle headStyle = HeadStyle(workbook);
                        ICellStyle contentStyle = ContentStyle(workbook);

                        // 创建表头
                        IRow headerRow = sheet.CreateRow(0);
                        PropertyInfo[] properties = typeof(TagRecordInfo).GetProperties();

                        int _colIndex = 0;
                        int ColLastIndex = 0;
                        for (int i = 0; i < properties.Length; i++)
                        {
                            DisplayNameAttribute[] attrs =
                                (DisplayNameAttribute[])properties[i]
                                    .GetCustomAttributes(typeof(DisplayNameAttribute), true);
                            if (attrs == null || attrs.Length == 0)
                            {
                                continue;
                            }

                            ICell cell = headerRow.CreateCell(_colIndex);
                            cell.SetCellValue(attrs[0].DisplayName);

                            ICellStyle styleContent = workbook.CreateCellStyle();
                            styleContent.CloneStyleFrom(headStyle);

                            headerRow.GetCell(_colIndex).CellStyle = styleContent;
                            headerRow.GetCell(_colIndex).CellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Medium;
                            headerRow.GetCell(_colIndex).CellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Medium;
                            headerRow.GetCell(_colIndex).CellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Medium;
                            headerRow.GetCell(_colIndex).CellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Medium;
                            _colIndex++;
                        }

                        ColLastIndex = _colIndex;
                        // 填充数据
                        for (int rowIndex = 0; rowIndex < Datas.Count; rowIndex++)
                        {
                            IRow dataRow = sheet.CreateRow(rowIndex + 1);
                            _colIndex = 0;

                            for (int i = 0; i < properties.Length; i++)
                            {
                                DisplayNameAttribute[] attrs =
                                (DisplayNameAttribute[])properties[i]
                                    .GetCustomAttributes(typeof(DisplayNameAttribute), true);
                                if (attrs == null || attrs.Length == 0)
                                {
                                    continue;
                                }

                                ICell cell = dataRow.CreateCell(_colIndex);
                                object value = properties[i].GetValue(Datas[rowIndex]);

                                if (properties[i].PropertyType == typeof(DateTime))
                                {
                                    DateTime date = ((DateTime)value);
                                    if (DateTime.MinValue == date)
                                    {
                                        value = "";
                                    }
                                    else
                                    {
                                        value = date.ToString("yyyy.MM.dd");
                                    }
                                }

                                cell.SetCellValue(value + "");

                                ICellStyle styleContent = workbook.CreateCellStyle();
                                styleContent.CloneStyleFrom(contentStyle);
                                dataRow.GetCell(_colIndex).CellStyle = styleContent;

                                // 第一列
                                if (_colIndex == 0)
                                    dataRow.GetCell(_colIndex).CellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Medium;
                                else if (_colIndex == ColLastIndex)
                                {
                                    // 最后一列
                                    dataRow.GetCell(_colIndex).CellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Medium;
                                }

                                //if (rowIndex == ColLastIndex)
                                //    dataRow.GetCell(_colIndex).CellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Medium;

                                _colIndex++;
                            }
                        }

                        for (int i = 0; i < ColLastIndex; i++)
                        {
                            sheet.AutoSizeColumn(i);
                        }

                        using (FileStream fs =
                               new FileStream(
                                   Path.Combine(path,
                                       $"Tag-{DateTime.Now.ToString("yyyyMMddhhmmssfff")}.xlsx"),
                                   FileMode.Create, FileAccess.Write))
                        {
                            workbook.Write(fs);
                            splashScreenManager1.TryCloseWait();
                            Common.XtraMessageBoxHelper.Info("操作成功！");
                        }
                    }
                    catch (Exception ex)
                    {
                        throw ex;
                    }
                }
            }
            catch (Exception ex)
            {
                splashScreenManager1.TryCloseWait();
                Common.XtraMessageBoxHelper.Error(ex.Message);
            }
        }

        public ICellStyle HeadStyle(IWorkbook workbook)
        {
            ICellStyle style = workbook.CreateCellStyle();
            style.WrapText = true;//设置换行这个要先设置
            style.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;//居中
            style.VerticalAlignment = VerticalAlignment.Center;
            style.FillPattern = FillPattern.SolidForeground;
            style.FillForegroundColor = NPOI.HSSF.Util.HSSFColor.Grey25Percent.Index;
            return style;
        }

        public ICellStyle ContentStyle(IWorkbook workbook)
        {
            ICellStyle cellStyle = workbook.CreateCellStyle();
            cellStyle.Alignment = NPOI.SS.UserModel.HorizontalAlignment.Center;//居中
            cellStyle.VerticalAlignment = VerticalAlignment.Center;//水平居中
            cellStyle.BorderLeft = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyle.BorderTop = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyle.BorderRight = NPOI.SS.UserModel.BorderStyle.Thin;
            cellStyle.BorderBottom = NPOI.SS.UserModel.BorderStyle.Thin;
            return cellStyle;
        }
    }
}