using System;
using System.Windows.Forms;
using System.Reflection;
using System.Drawing;
using System.Collections;
using System.Data;
using Infragistics.Win.UltraWinEditors;

namespace Core.XgMes.Client.JGKC.SteelPlateManager
{
    public class Comm
    {

        public Comm()
        {
            //
            // TODO: 在此处添加构造函数逻辑
            //
        }
    public static void DoExc(string _Name ,Infragistics.Win.UltraWinGrid.UltraGrid _Grid,int _CellNO)
		{
			string strFileName = @"D:\" + _Name + System.DateTime.Today.ToString("yyMMdd")+".xls";

			System.Windows.Forms.SaveFileDialog sfd = new SaveFileDialog();
			sfd.Filter = "Microsoft Office Excel 工作簿 (*.xls)|*.xls";
			sfd.Title  = "导出到Excel文件";
			sfd.FileName = strFileName;

			if ( sfd.ShowDialog() == DialogResult.OK )
			{
				strFileName = sfd.FileName ; 
				Infragistics.Excel.Workbook wb = new Infragistics.Excel.Workbook();
				Infragistics.Excel.Worksheet ws2 = wb.Worksheets.Add("Sheet1");   
				ws2.Rows[0].Cells[0].Value = _Grid.Text;
				ws2.MergedCellsRegions.Add(0, 0, 0, _CellNO); 
				ws2.Rows[0].Cells[0].CellFormat.Alignment = Infragistics.Excel.HorizontalCellAlignment.Center;
				ws2.Rows[0].Cells[0].CellFormat.VerticalAlignment = Infragistics.Excel.VerticalCellAlignment.Center;
				ws2.Rows[0].Cells[0].CellFormat.WrapText = Infragistics.Excel.ExcelDefaultableBoolean.True;
				ws2.Rows[0].Cells[0].CellFormat.Font.Height = 300;
				ws2.Rows[0].Cells[0].CellFormat.Font.UnderlineStyle = Infragistics.Excel.FontUnderlineStyle.Single;
				ws2.Rows[0].Height = 510;

				int int_index = 0;
				for ( int i=0; i< _Grid.DisplayLayout.Bands[0].Columns.Count; i++ )
				{
					if ( ! _Grid.DisplayLayout.Bands[0].Columns[i].Hidden )
					{
						ws2.Rows[1 + _Grid.DisplayLayout.Bands[0].Columns[i].RowLayoutColumnInfo.OriginY].Cells[_Grid.DisplayLayout.Bands[0].Columns[i].RowLayoutColumnInfo.OriginX].Value = _Grid.DisplayLayout.Bands[0].Columns[i].Header.Caption;					
						
						ws2.MergedCellsRegions.Add(1 + _Grid.DisplayLayout.Bands[0].Columns[i].RowLayoutColumnInfo.OriginY, 
							_Grid.DisplayLayout.Bands[0].Columns[i].RowLayoutColumnInfo.OriginX,
							1 + _Grid.DisplayLayout.Bands[0].Columns[i].RowLayoutColumnInfo.OriginY +
							_Grid.DisplayLayout.Bands[0].Columns[i].RowLayoutColumnInfo.SpanY-1,
							_Grid.DisplayLayout.Bands[0].Columns[i].RowLayoutColumnInfo.OriginX +
							_Grid.DisplayLayout.Bands[0].Columns[i].RowLayoutColumnInfo.SpanX-1); 				

						int_index += _Grid.DisplayLayout.Bands[0].Columns[i].RowLayoutColumnInfo.SpanX;
					}
				}
				for ( int i =0; i<= _CellNO; i++)
				{
					for ( int j=1; j<=2; j++)
					{						
						ws2.Rows[j].Cells[i].CellFormat.Alignment = Infragistics.Excel.HorizontalCellAlignment.Center;
						ws2.Rows[j].Cells[i].CellFormat.VerticalAlignment = Infragistics.Excel.VerticalCellAlignment.Center;
						ws2.Rows[j].Cells[i].CellFormat.WrapText = Infragistics.Excel.ExcelDefaultableBoolean.True;
						ws2.Rows[j].Cells[i].CellFormat.FillPatternBackgroundColor = Color.LightSteelBlue;
						ws2.Rows[j].Cells[i].CellFormat.FillPatternForegroundColor = Color.LightSteelBlue;

						ws2.Rows[j].Cells[i].CellFormat.TopBorderColor = Color.Black;
						ws2.Rows[j].Cells[i].CellFormat.BottomBorderColor = Color.Black;
						ws2.Rows[j].Cells[i].CellFormat.LeftBorderColor = Color.Black;				
						ws2.Rows[j].Cells[i].CellFormat.RightBorderColor = Color.Black;
					}
				}

				for ( int i=0; i< _Grid.Rows.Count; i++ )
				{
					for ( int j=0; j< _Grid.DisplayLayout.Bands[0].Columns.Count; j++ )
					{
						if ( ! _Grid.Rows[i].Cells[j].Hidden && _Grid.DisplayLayout.Bands[0].Columns[j].RowLayoutColumnInfo.LabelPosition != Infragistics.Win.UltraWinGrid.LabelPosition.LabelOnly )
						{
							ws2.Rows[3+i].Cells[_Grid.DisplayLayout.Bands[0].Columns[j].RowLayoutColumnInfo.OriginX].Value = _Grid.Rows[i].Cells[j].Value;
							ws2.Rows[3+i].Cells[_Grid.DisplayLayout.Bands[0].Columns[j].RowLayoutColumnInfo.OriginX].CellFormat.VerticalAlignment = Infragistics.Excel.VerticalCellAlignment.Center;

							if ( _Grid.DisplayLayout.Bands[0].Columns[j].DataType == typeof(System.Decimal))
							{
								ws2.Rows[3+i].Cells[_Grid.DisplayLayout.Bands[0].Columns[j].RowLayoutColumnInfo.OriginX].CellFormat.Alignment = Infragistics.Excel.HorizontalCellAlignment.Right;
							}

						}
																		
					}
				}
				Infragistics.Excel.BIFF8Writer.WriteWorkbookToFile(wb, strFileName);
			}
		}

		/// <summary>
		/// 设置Grid求和区域
		/// </summary>
		/// <param name="pGrid">目标Grid</param>
		/// <returns></returns>		 
		public static void SetGridSumArea(Infragistics.Win.UltraWinGrid.UltraGridBase pGrid)
		{
			try
			{
	
				if(pGrid.Rows.Count == 0)
				{
					foreach(Infragistics.Win.UltraWinGrid.UltraGridBand band in pGrid.DisplayLayout.Bands)
					{
						foreach(Infragistics.Win.UltraWinGrid.SummarySettings sum in band.Summaries)
						{
							sum.SummaryDisplayArea = Infragistics.Win.UltraWinGrid.SummaryDisplayAreas.None;
						}
					}
				}
				else
				{
					foreach(Infragistics.Win.UltraWinGrid.UltraGridBand band in pGrid.DisplayLayout.Bands)
					{
						foreach(Infragistics.Win.UltraWinGrid.SummarySettings sum in band.Summaries)
						{
							if(pGrid.DisplayLayout.GroupByBox.Hidden)
							{
								sum.SummaryDisplayArea = Infragistics.Win.UltraWinGrid.SummaryDisplayAreas.Bottom;
							}
							else
							{
								sum.SummaryDisplayArea = ((Infragistics.Win.UltraWinGrid.SummaryDisplayAreas)((Infragistics.Win.UltraWinGrid.SummaryDisplayAreas.Bottom | Infragistics.Win.UltraWinGrid.SummaryDisplayAreas.InGroupByRows | Infragistics.Win.UltraWinGrid.SummaryDisplayAreas.GroupByRowsFooter)));
							}
						}
					}
				}
			}
			catch(System.Exception ex)
			{
				System.Diagnostics.Debug.WriteLine(ex.ToString());
			}
		}

	
		/// <summary>
		/// 关闭窗体
		/// </summary>
		/// <param name="objForm">目标Form</param>
		/// <returns></returns>		 
		public static void CloseForm(System.Windows.Forms.Form objForm)
		{
			System.Windows.Forms.DialogResult result = DialogResult.No;

			result=MessageBox.Show("您确认要关闭当前窗口吗?","提示信息",MessageBoxButtons.YesNo,MessageBoxIcon.Question);
			if(result == DialogResult.Yes) objForm.Close();

		}
			
		/// <summary>
		/// 对目标对象进行字符串的转换
		/// </summary>
		/// <param name="obj"></param>
		/// <returns></returns>
		public static string ObjToStr(object obj)
		{
			if(obj == null || obj.GetType() == typeof(System.DBNull))
			{
				return "";
			}
			else
			{
				return Convert.ToString(obj);
			}
		}

		/// <summary>
		/// 对目标对象进行数字的转换
		/// </summary>
		/// <param name="obj"></param>
		/// <returns></returns>
		public static int ObjToInt(object obj)
		{
			try
			{
				if(obj == null || obj.GetType() == typeof(System.DBNull) || ObjToStr(obj).Length ==0)
				{
					return 0;
				}
				else
				{
					return Convert.ToInt32(obj);
				}
			}
			catch(System.Exception ex)
			{
				System.Diagnostics.Debug.WriteLine(ex.ToString());
				return 0;
			}
		}

		/// <summary>
		/// 对目标对象进行数字(小数)的转换
		/// </summary>
		/// <param name="obj"></param>
		/// <returns></returns>
		public static System.Decimal ObjToDecimal(object obj)
		{
			try
			{
				if(obj == null || obj.GetType() == typeof(System.DBNull) || ObjToStr(obj).Length ==0)
				{
					return 0;
				}
				else
				{
					return Convert.ToDecimal(obj);
				}
			}
			catch(System.Exception ex)
			{
				System.Diagnostics.Debug.WriteLine(ex.ToString());
				return 0;
			}
		}

		/// <summary>
		/// 对目标对象进行数字(小数)的转换
		/// </summary>
		/// <param name="obj"></param>
		/// <returns></returns>
		public static System.Double ObjToDouble(object obj)
		{
			try
			{
				if(obj == null || obj.GetType() == typeof(System.DBNull) || ObjToStr(obj).Length ==0)
				{
					return 0;
				}
				else
				{
					return Convert.ToDouble(obj);
				}
			}
			catch(System.Exception ex)
			{
				System.Diagnostics.Debug.WriteLine(ex.ToString());
				return 0;
			}
		}

		
		/// <summary>
		/// 将目标GRID导出EXCEL文件
		/// </summary>
		/// <param name="ulGrid"></param>
		/// <param name="ExcelExporter"></param>
		/// <returns></returns>

		public static void ExPortExcel(Infragistics.Win.UltraWinGrid.UltraGrid ulGrid,Infragistics.Win.UltraWinGrid.ExcelExport.UltraGridExcelExporter ExcelExporter)
		{
			string filePath;
			string fileName;
			SaveFileDialog saveDlg = new SaveFileDialog();

			try
			{
				if( !System.IO.Directory.Exists(System.Windows.Forms.Application.StartupPath + @"\Report"))
				{
					System.IO.Directory.CreateDirectory(System.Windows.Forms.Application.StartupPath + @"\Report");
				}
				filePath = System.Windows.Forms.Application.StartupPath + @"\Report";

				saveDlg.InitialDirectory = filePath;
				saveDlg.DefaultExt = "*.xls";
				saveDlg.Filter = "XLS Files|*.xls";
				saveDlg.FilterIndex = 2;
				saveDlg.RestoreDirectory = true ;

				if(saveDlg.ShowDialog() == DialogResult.OK)
				{
					fileName = saveDlg.FileName;
					ExcelExporter.Export(ulGrid,fileName);

					//创建一个新的进程打开excel
					System.Diagnostics.ProcessStartInfo st = new System.Diagnostics.ProcessStartInfo(fileName);
					st.WindowStyle = System.Diagnostics.ProcessWindowStyle.Maximized;
					System.Diagnostics.Process.Start(st);
				
				}

			}
			catch(Exception ex)
			{
				System.Diagnostics.Debug.WriteLine(ex.ToString());
			}
		
		}
        public static bool FillComboEditor(ref UltraComboEditor ulComboEditor, DataSet dset)
        {
            if (dset == null) return false;
            if (dset.Tables.Count < 1) return false;
            if (dset.Tables[0].Columns.Count < 2) return false;

            ulComboEditor.Items.Clear();
            for (int i = 0; i < dset.Tables[0].Rows.Count; i++)
                ulComboEditor.Items.Add(dset.Tables[0].Rows[i][0].ToString(), dset.Tables[0].Rows[i][1].ToString());
            return true;
        }
		/// <summary>
		/// GRID 列绑定DropDownList
		/// </summary>
		/// <param name="_grid">Grid</param>
		/// <param name="_ds">DataSet</param>
		///  <param name="tableName">绑定表名</param>
		/// <param name="_displayColumn">绑定列名</param>
		/// <param name="_displayMember">显示项</param>
		/// <param name="_ValueMember">值项</param>
		/// <returns></returns>
		public static void SetGridDropDownList(Infragistics.Win.UltraWinGrid.UltraGrid _grid,System.Data.DataSet _ds,string _tableName,string _displayColumn,string _displayMember,string _ValueMember)
		{
			try
			{
				_grid.DisplayLayout.Bands[_tableName].Columns[_displayColumn].Style = Infragistics.Win.UltraWinGrid.ColumnStyle.DropDownList;
				Infragistics.Win.UltraWinGrid.UltraDropDown ultraCombo = new Infragistics.Win.UltraWinGrid.UltraDropDown();
				_grid.FindForm().Controls.Add(ultraCombo);
				ultraCombo.DisplayMember = _ds.Tables[0].Columns[_displayMember].ToString();
				ultraCombo.ValueMember = _ds.Tables[0].Columns[_ValueMember].ToString();	
				ultraCombo.Visible = false;
				ultraCombo.DataSource = _ds.Tables[0].DefaultView;//++
				ultraCombo.Width = _grid.DisplayLayout.Bands[_tableName].Columns[_displayColumn].RowLayoutColumnInfo.PreferredCellSize.Width;//++
	
				foreach(System.Data.DataColumn col in _ds.Tables[0].Columns)
				{
					if(col.ColumnName != _displayMember)
					{
						ultraCombo.DisplayLayout.Bands[0].Columns[col.ColumnName].Hidden = true;
					}
					else
					{
						ultraCombo.DisplayLayout.Bands[0].Columns[col.ColumnName].Band.ColHeadersVisible = false;
						ultraCombo.DisplayLayout.Bands[0].Columns[col.ColumnName].Width  = ultraCombo.Width;
					}
				}

				_grid.DisplayLayout.Bands[_tableName].Columns[_displayColumn].ValueList = ultraCombo;
				_grid.DisplayLayout.Bands[_tableName].Columns[_displayColumn].CellAppearance.TextHAlign  = Infragistics.Win.HAlign.Left;
				_grid.DisplayLayout.Bands[_tableName].Columns[_displayColumn].CellAppearance.TextVAlign = Infragistics.Win.VAlign.Middle;

			}
			catch(Exception ex)
			{
				System.Diagnostics.Debug.WriteLine(ex.ToString());
			}

		}

		/// <summary>
		/// 初始化Infragistics.Win.UltraWinGrid.UltraCombo 控件绑定表
		/// </summary>
		/// <param name="_grid">Grid</param>
		/// <param name="_ds">DataSet</param>
		///  <param name="tableName">绑定表名</param>
		/// <param name="_displayColumn">绑定列名</param>
		/// <param name="_displayMember">显示项</param>
		/// <param name="_ValueMember">值项</param>
		/// <returns></returns>
		public static void Init_ComboControl(System.Windows.Forms.Control ComboControl,string TableName,string _displayMember,string _valueMember,ref System.Data.DataSet dst)
		{
			try
			{
				switch(ComboControl.GetType().ToString())
				{
					case "Infragistics.Win.UltraWinGrid.UltraCombo":
						if(!dst.Tables.Contains(TableName))
						{
							MessageBox.Show("绑定表："+TableName+"不存在，不能对控件"+ComboControl.Name+"进行初始化！");
							return;
						}
						System.Data.DataTable newTable = dst.Tables[TableName].Copy();
						newTable.TableName=TableName;
						System.Data.DataRow newRow = newTable.NewRow();
						for(int i=0;i<dst.Tables[TableName].Columns.Count;i++)
						{
							newRow[i]="";
						}
						newTable.Rows.Add(newRow);
						newTable.AcceptChanges();
	
						((Infragistics.Win.UltraWinGrid.UltraCombo)ComboControl).DataSource = new System.Data.DataView(newTable);
						((Infragistics.Win.UltraWinGrid.UltraCombo)ComboControl).DisplayMember = _displayMember;
						((Infragistics.Win.UltraWinGrid.UltraCombo)ComboControl).ValueMember = _valueMember;
						foreach(System.Data.DataColumn col in dst.Tables[TableName].Columns)
						{
							if(col.ColumnName != _displayMember)
							{
								((Infragistics.Win.UltraWinGrid.UltraCombo)ComboControl).DisplayLayout.Bands[TableName].Columns[col.ColumnName].Hidden = true;
							}
							else
							{
								((Infragistics.Win.UltraWinGrid.UltraCombo)ComboControl).DisplayLayout.Bands[TableName].Columns[col.ColumnName].Band.ColHeadersVisible = false;
								((Infragistics.Win.UltraWinGrid.UltraCombo)ComboControl).DisplayLayout.Bands[TableName].Columns[col.ColumnName].Width  = ((Infragistics.Win.UltraWinGrid.UltraCombo)ComboControl).Width;
							}
						}
						break;
				}
			}
			catch(System.Exception ex)
			{
				System.Diagnostics.Debug.WriteLine(ex.ToString());
			}
		}


		/// <summary>
		/// 获取grid-选择字段="TRUE"的行数
		/// </summary>
		/// <param name="ulGrid">目标grid</param>
		/// <returns>int</returns>
		/// 
		public static int GetSelectRows(Infragistics.Win.UltraWinGrid.UltraGrid ulGrid)
		{
			int rowsCount = 0;

			
			foreach(Infragistics.Win.UltraWinGrid.UltraGridRow row in ulGrid.Rows)
			{				
				GetTrueRows(row,ref rowsCount);
			}
			
			return rowsCount;

		}

		private static void GetTrueRows( Infragistics.Win.UltraWinGrid.UltraGridRow row,ref int TrueNum)
		{
			if(row.GetType()==typeof(Infragistics.Win.UltraWinGrid.UltraGridRow))
			{
				if(row.Cells["Select"].Value.ToString().ToUpper()=="TRUE")
				{
					TrueNum++;
				}
			}
			else
			{
				foreach(Infragistics.Win.UltraWinGrid.UltraGridRow tmprow in row.ChildBands[0].Rows)
				{
					GetTrueRows(tmprow,ref TrueNum);
				}
			}
		}
		
		/// <summary>
		/// 获取grid-选择字段="TRUE"指定字段值
		/// </summary>
		/// <param name="_SelectGrid">存在选择行的UltraGrid</param>
		/// <param name="_Select">选择字段</param>
		/// <param name="_FieldValue">字段值</param>
		/// <returns>ArrayList</returns>
		public static System.Collections.ArrayList GetFieldValue(Infragistics.Win.UltraWinGrid.UltraGrid _SelectGrid,string _Select,string _FieldValue)
		{
			System.Collections.ArrayList resultArray = new System.Collections.ArrayList();
			
			foreach(Infragistics.Win.UltraWinGrid.UltraGridRow row in _SelectGrid.Rows)
			{
				if(ObjToStr(row.Cells[_Select].Value).ToUpper() == "TRUE")
					resultArray.Add(ObjToStr(row.Cells[_FieldValue].Value));
				
			}
			return resultArray;

		}

		/// <summary>
		/// 设置ulGridRow指定字段值
		/// </summary>
		/// <param name="GridRow">目标GridRow</param>
		/// <param name="Value">设置值 </param>
		/// <param name="Key">字段KEY</param>
		/// <returns></returns>
		public static void SetGridFlagValue(Infragistics.Win.UltraWinGrid.UltraGridRow GridRow,string _Value,string Key)
		{
			if(GridRow.GetType()==typeof(Infragistics.Win.UltraWinGrid.UltraGridGroupByRow))
			{
				foreach(Infragistics.Win.UltraWinGrid.UltraGridRow row in GridRow.ChildBands[0].Rows)
				{
					SetGridFlagValue(row,_Value,Key);
				}
			}
			else
			{
				if(!GridRow.IsFilteredOut)
					GridRow.Cells[Key].Value = _Value;
			}
		}

		/// <summary>
		/// 获取ulGridRow指定字段值(针对有分组行时)
		/// </summary>
		/// <param name="row">UltraGridRow</param>
		/// <param name="_Key">选择字段KEY</param>
		/// <param name="_CompareValue">比对值</param>
		/// <param name="_CellKey">指定字段KEY</param>
		/// <param name="_ResultField">返回制定字段值数组</param>
		/// <returns></returns>	
		public static void GetAdjustData(Infragistics.Win.UltraWinGrid.UltraGridRow row,string _Key,string _CompareValue,string _CellKey,ref ArrayList _ResultField)
		{
			if(row.GetType()==typeof(Infragistics.Win.UltraWinGrid.UltraGridRow))
			{
				if(Comm.ObjToStr(row.Cells[_Key].Value).ToUpper() == _CompareValue)
				{
					_ResultField.Add(Comm.ObjToStr(row.Cells[_CellKey].Value));
				}
			}
			else
			{
				foreach(Infragistics.Win.UltraWinGrid.UltraGridRow tmprow in row.ChildBands[0].Rows)
				{
					GetAdjustData(tmprow,_Key,_CompareValue,_CellKey,ref _ResultField);
				}
			}
		}
       
  
        
    }
	
}
