using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;


public partial class Maintenance_TEC_WorksList : System.Web.UI.Page {
    //the function code for localization on this page
    ProfileCommon p;
    protected override void InitializeCulture() {
        p = (ProfileCommon)this.Context.Profile;
        
        if (Request.Form.Get("ctl00$selLanguage") != null)
            p.lang = Request.Form.Get("ctl00$selLanguage").ToString();
        if (p.lang == String.Empty)
            p.lang = Session["Localization"].ToString();

        if (p.lang.Length > 0) {
            this.Culture = p.lang;
            this.UICulture = System.Globalization.CultureInfo.CreateSpecificCulture(p.lang).Name;
        }
    }
    //select theme
    protected void Page_PreInit(object sender, EventArgs e) {
        Page.Theme = Profile.UI.Theme;

        // 沒有權限
        if (!SES_Common.Authorize(Request.Url.ToString(), Profile.UserName)) {
            Response.Redirect("/SEST/Common/NoAuthorization.aspx");
        }
    }


    protected void Page_Load(object sender, EventArgs e) {
        // 不是來自管理的路徑 (功能 hidden)
        if (Request.Url.ToString().ToUpper().IndexOf("SEST/MAINTENANCE/") < 0) {
            hlAddNew.Visible = false;                   //新增按鈕
            Page.Title = Resources.SiteMapLocalizations.TEC_WorkList;
        }
        else
            Page.Title = Resources.SiteMapLocalizations.Maintenance_WorkListEdit;


        if (!IsPostBack) {
            // 預設的搜尋日期
            txtStartDate.Text = DateTime.Today.AddDays(-30).ToString("yyyy/MM/dd");
            txtEndDate.Text = DateTime.Today.ToString("yyyy/MM/dd");

            //Status 的設定
            // 預設的搜尋條件
            string sDefaultSelected = "Processing";

            DataTable dtStatus = new TEC_WorkStatusNameData().Select();
            ListItem li;
            li = new ListItem("", "");
            ddlStatus.Items.Add(li);
            for (int iStatus = 0; iStatus < dtStatus.Rows.Count; iStatus++) {
                if (p.lang == "zh-TW") {
                    li = new ListItem(dtStatus.Rows[iStatus]["CName"].ToString(), dtStatus.Rows[iStatus]["StatusName"].ToString());
                }
                else if (p.lang == "ja-JP") {
                    li = new ListItem(dtStatus.Rows[iStatus]["JName"].ToString(), dtStatus.Rows[iStatus]["StatusName"].ToString());
                }
                else { // "en"
                    li = new ListItem(dtStatus.Rows[iStatus]["StatusName"].ToString(), dtStatus.Rows[iStatus]["StatusName"].ToString());
                }

                // 預設為選擇 Processing 狀態
                if (li.Value == sDefaultSelected)
                    li.Selected = true;

                ddlStatus.Items.Add(li);
            }



            // 記錄排序方式與資料來源
            //ddlStatus.SelectedIndex = ddlStatus.Items.IndexOf(new ListItem(sDefaultSelected));
            dtMainWork = new TEC_MainWorksData().SelectByManualSearch("T1.Status='" + sDefaultSelected + "'", "FABID ASC");
            btnPrompt.Text = "Total Counts : " + dtMainWork.Rows.Count;
            //// 如果預設的搜尋條件 (Pending) 沒有任何資料, 則預設的搜尋條件設為 Processing
            //if (dtMainWork.Rows.Count < 1) {
            //    sDefaultSelected = "Processing";
            //    ddlStatus.SelectedIndex = ddlStatus.Items.IndexOf(new ListItem(sDefaultSelected));
            //    dtMainWork = new TEC_MainWorksData().Select("Status='" + sDefaultSelected + "'", "FABID ASC");
            //}

            ViewState["ConditionStr"] = "Status='" + sDefaultSelected + "'";        // default show 
            ViewState["OrderByDirection"] = "ASC";                                  // direction

            GridView1.DataSource = dtMainWork;
            ViewState["dataSource"] = dtMainWork;
            GridView1.DataBind();

            Session["dtMainWorks"] = dtMainWork;	

            //for (int i = 0; i < dtMainWork.Rows.Count; i++) {
            //    for (int j = 0; j < dtMainWork.Columns.Count; j++) {
            //        if (dtMainWork.Columns[j].DataType.Name == "DateTime")
            //            dtMainWork.Rows[i][j] = "1990/1/1";
            //        if (dtMainWork.Columns[j].DataType.Name == "String")
            //            dtMainWork.Rows[i][j] = dtMainWork.Columns[j].ColumnName;
            //    }
            //}
            //DataView dv = new DataView(dtMainWork);
            //////ExportToExcel(dtMainWork, "text.xls");
            ////Response.Buffer = false;
            ////Response.AppendHeader("Content-Disposition", "attachment");
            ////Response.ContentEncoding = System.Text.Encoding.GetEncoding("big5");
            ////Response.Flush();
            ////Response.End();
            //ExportLinkButton1.Dataview = dv;
            //ExportLinkButton1.FileNameToExport = "Books.xls";
            //ExportLinkButton1.ExportType = PNayak.Web.UI.WebControls.ExportLinkButton.ExportTypeEnum.Excel;
            //ExportLinkButton1.Separator = PNayak.Web.UI.WebControls.ExportLinkButton.SeparatorTypeEnum.TAB;
        }

    }
    public string ConvertBig5(string strUtf) {
        System.Text.Encoding utf81 = System.Text.Encoding.GetEncoding("utf-8");
        System.Text.Encoding big51 = System.Text.Encoding.GetEncoding("big5");
        Response.ContentEncoding = big51;
        byte[] strUtf81 = utf81.GetBytes(strUtf.Trim());
        byte[] strBig51 = System.Text.Encoding.Convert(utf81, big51, strUtf81);

        char[] big5Chars1 = new char[big51.GetCharCount(strBig51, 0, strBig51.Length)];
        big51.GetChars(strBig51, 0, strBig51.Length, big5Chars1, 0);
        string tempString1 = new string(big5Chars1);
        return tempString1;
    }




    protected void lbToExcel_OnClick(object sender, EventArgs e) {

        // reference to http://www.codeproject.com/aspnet/ExportClassLibrary.asp
        // Export the details of specified columns
        try {
            // Get the datatable to export
            DataTable dtExport = ((DataTable)Session["dtMainWorks"]).Copy();

            // Specify the column list to export
            int[] iColumns = { 1, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15, 17, 18, 19 };

            // Export the details of specified columns to Excel
            RKLib.ExportData.Export objExport = new RKLib.ExportData.Export("Web");
            objExport.ExportDetails(dtExport, iColumns, RKLib.ExportData.Export.ExportFormat.Excel, DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls");
        }
        catch (Exception Ex) {
            //lblError.Text = Ex.Message;
        }
    }
    protected void btnToExcel_OnClick(object sender, EventArgs e) {

        //Response.Clear();
        //Response.Buffer = true;
        //Response.Charset = "utf-8";
        //Response.AppendHeader("content-disposition", "attachment;filename=filename.xls");
        //// 如果沒有getencoding("gb2312") 則輸出的文件會是亂碼
        //Response.ContentEncoding = System.Text.Encoding.Unicode;
        //Response.ContentType = "application/vnd.ms-excel";//設定輸出的文件類型為 excel
        //System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
        //System.Web.UI.HtmlTextWriter oHTMLTextWriter = new HtmlTextWriter(oStringWriter);
        //this.GridView1.RenderControl(oHTMLTextWriter);
        //Response.Output.Write(oStringWriter.ToString());
        //Response.Flush();
        //Response.End();

        ////ExportToExcel(dtMainWork, "test.xls");

        //// 在aspx 中 <%@ page language="C# ....須加入 ResponseEncoding="UTF-8" EnableEventValidation = "false"
        //System.IO.StringWriter sw = new System.IO.StringWriter();
        //System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(sw);
        //Response.Clear();
        //Response.Buffer = true;
        //Response.AppendHeader("Content-Disposition", "attachment; filename=P.xls");
        //Response.ContentType = "application/vnd.ms-excel";

        //GridView1.RenderControl(hw);
        //Response.Write(sw.ToString());
        //Response.End();


        // reference to http://www.codeproject.com/aspnet/ExportClassLibrary.asp
        // Export the details of specified columns
        try {
            // Get the datatable to export
            DataTable dtExport = ((DataTable)Session["dtMainWorks"]).Copy();

            // Specify the column list to export
            int[] iColumns = { 1, 5, 6, 7, 9, 10, 11, 12, 13, 14, 15, 17, 18, 19 };

            // Export the details of specified columns to Excel
            RKLib.ExportData.Export objExport = new RKLib.ExportData.Export("Web");
            objExport.ExportDetails(dtExport, iColumns, RKLib.ExportData.Export.ExportFormat.Excel, DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls");
        }
        catch (Exception Ex) {
            //lblError.Text = Ex.Message;
        }
    }
    public override void VerifyRenderingInServerForm(Control control) {
        //base.VerifyRenderingInServerForm(control);
    }

    private void ExportToExcel(DataTable dt, string FileName){
        Response.ContentType = "application/ms-excel";
        Response.AddHeader("Content-Disposition", "inline;filename=" + FileName);
        Response.Write (ConvertDtToTDF(dt));
    }
    // Converts a DataTable to Tab Delimited Format
    private string ConvertDtToTDF( DataTable dt){
        object[] ary;
        int i, iCol;

        //Output Column Headers
        for ( iCol=0; iCol< dt.Columns.Count; iCol++){
            Response.Write(dt.Columns[iCol].ToString() + "\t");
        }
        Response.Write("\r\n");

        //Output Data
        foreach( DataRow dr in dt.Rows){
            ary = dr.ItemArray;
            for (i=0;i<ary.Length; i++){
                Response.Write(ary[i].ToString() + "\t");
            }
            Response.Write("\r\n");
        }

        return "\r\n";
    }

    //private void ExportToExcel(string Filename, System.Web.UI.Page page, System.Data.DataTable DT, string[] colNames) {
    //    int rowIndex = MaxRowsPerSheet;
    //    int colIndex = 1;
    //    int sheetIndex = 0;
    //    System.Threading.Thread.CurrentThread.CurrentCulture = System.Globalization.CultureInfo.CreateSpecificCulture("en-US");
    //    Excel.Application oExcel = new Excel.Application();
    //    oExcel.SheetsInNewWorkbook = 1;
    //    Excel.Workbook WB = (Excel.Workbook)oExcel.Workbooks.Add(Missing.Value);
    //    Excel.Worksheet sheet = null;
    //    Excel.Range range = null;
    //    foreach (DataRow row in DT.Rows) {
    //        if (rowIndex == MaxRowsPerSheet) {
    //            rowIndex = 1;
    //            colIndex = 1;
    //            sheetIndex++;
    //            if (sheet != null)
    //                sheet = (Excel.Worksheet)WB.Worksheets.Add(Missing.Value, sheet, Missing.Value, Missing.Value);
    //            else
    //                sheet = (Excel.Worksheet)WB.Worksheets["Sheet1"];
    //            if (colNames == null) {
    //                foreach (DataColumn col in DT.Columns) {
    //                    range = (Excel.Range)sheet.Cells[rowIndex, colIndex++];
    //                    range.Value2 = col.ColumnName.ToString();
    //                }
    //            }
    //            else {
    //                foreach (string str in colNames) {
    //                    range = (Excel.Range)sheet.Cells[rowIndex, colIndex++];
    //                    range.Value2 = str.ToString();
    //                }
    //            }
    //            rowIndex++;
    //            sheet.Name = "Page " + (sheetIndex);
    //        }
    //        colIndex = 1;
    //        foreach (object item in row.ItemArray) {
    //            range = (Excel.Range)sheet.Cells[rowIndex, colIndex];
    //            range.Value2 = item.ToString();
    //            if (item.ToString().Length > 11 && range.NumberFormat != "#") {
    //                bool IsPhoneNumber = true;
    //                string strItem = item.ToString();
    //                for (int i = 0; i < 1; i++) {
    //                    if (!Char.IsDigit(strItem, i)) {
    //                        IsPhoneNumber = false;
    //                        break;
    //                    }
    //                }
    //                if (IsPhoneNumber)
    //                    range.EntireColumn.NumberFormat = "#";
    //            }
    //            colIndex++;
    //        }
    //        rowIndex++;
    //    }
    //    for (int i = 1; i <= WB.Worksheets.Count; i++) {
    //        sheet = (Excel.Worksheet)WB.Worksheets["Page " + i];
    //        int num_cols = DT.Columns.Count;
    //        for (int j = 1; j <= num_cols; j++) {
    //            range = (Excel.Range)sheet.Cells[1, j];
    //            range = range.EntireColumn;
    //            range.AutoFit();
    //            range.HorizontalAlignment = Excel.XlHAlign.xlHAlignRight;
    //        }
    //    }
    //    sheet = ((Excel.Worksheet)WB.Worksheets["Page 1"]);
    //    sheet.Activate();
    //    string filename = page.Server.MapPath("/APP_TPH_local/temp") + "\\" + page.Session.SessionID + ".tmp";
    //    WB.SaveAs(filename, Excel.XlFileFormat.xlWorkbookNormal, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Excel.XlSaveAsAccessMode.xlExclusive, Excel.XlSaveConflictResolution.xlLocalSessionChanges, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
    //    WB.Close(Missing.Value, Missing.Value, Missing.Value);
    //    oExcel.Workbooks.Close();
    //    oExcel.Quit();
    //    System.IO.FileStream input = new System.IO.FileStream(filename, System.IO.FileMode.Open);
    //    System.IO.Stream output = res.OutputStream;
    //    int len = (int)input.Length;
    //    byte[] buffer = new byte[len];
    //    input.Read(buffer, 0, len);
    //    output.Write(buffer, 0, len);
    //    input.Close();
    //    output.Close();
    //    System.IO.File.Delete(filename);
    //    DT.Dispose();
    //    DT = null;
    //    System.Runtime.InteropServices.Marshal.ReleaseComObject(range);
    //    System.Runtime.InteropServices.Marshal.ReleaseComObject(sheet);
    //    System.Runtime.InteropServices.Marshal.ReleaseComObject(WB);
    //    while (System.Runtime.InteropServices.Marshal.ReleaseComObject(oExcel) > 0) ;
    //    sheet = null;
    //    WB = null;
    //    oExcel = null;
    //    range = null;
    //    GC.Collect();
    //}

    //private void ExportToExcel() {
    //    Excel.Application oExcel = new Excel.Application();

    //    Excel.Workbooks oBooks;
    //    Excel.Workbook oBook;

    //    Excel.Sheets oSheets;
    //    Excel.Worksheet oSheet;

    //    Excel.Range oCells;

    //    string sFile;
    //    string sTemplate;

    //    DataTable dt = (DataTable)Application.Item("MyDataTable");

    //    sFile = Server.MapPath(Request.ApplicationPath) + "\\MyExcel.xls";
    //    sTemplate = Server.MapPath(Request.ApplicationPath) + "\\MyTemplate.xls";
    //    oExcel.Visible = false;
    //    oExcel.DisplayAlerts = false;
    //    //Start a new workbook
    //    oBooks = oExcel.Workbooks;
    //    oBooks.Open(Server.MapPath(Request.ApplicationPath) + "\\MyTemplate.xls");
    //    //Load colorful template with chart
    //    oBook = oBooks.Item(1);
    //    oSheets = oBook.Worksheets;
    //    oSheet = (Excel.Worksheet)oSheets.Item(1);
    //    oSheet.Name = "First Sheet";
    //    oCells = oSheet.Cells;
    //    DumpData(dt, oCells);
    //    //Fill in the data

    //    oSheet.SaveAs(sFile);
    //    //Save in a temporary file

    //    oBook.Close();

    //    //Quit Excel and thoroughly deallocate everything
    //    oExcel.Quit();
    //    ReleaseComObject(oCells);
    //    ReleaseComObject(oSheet);
    //    ReleaseComObject(oSheets);
    //    ReleaseComObject(oBook);
    //    ReleaseComObject(oBooks);
    //    ReleaseComObject(oExcel);

    //    oExcel = null;
    //    oBooks = null;
    //    oBook = null;
    //    oSheets = null;
    //    oSheet = null;
    //    oCells = null;

    //    System.GC.Collect();

    //    Response.Redirect(sFile);
    //    //Send the user to the file
    //}
    //private string DumpData(DataTable dt, Excel.Range oCells) {
    //    DataRow dr;
    //    object[] ary;
    //    int iRow;
    //    int iCol;

    //    //Output Column Headers
    //    for (iCol = 0; iCol <= dt.Columns.Count - 1; iCol++) {
    //        oCells(2, iCol + 1) = dt.Columns(iCol).ToString;
    //    }

    //    //Output Data
    //    for (iRow = 0; iRow <= dt.Rows.Count - 1; iRow++) {
    //        dr = dt.Rows.Item(iRow);
    //        ary = dr.ItemArray;
    //        for (iCol = 0; iCol <= Information.UBound(ary); iCol++) {
    //            oCells(iRow + 3, iCol + 1) = ary(iCol).ToString;
    //            Response.Write(ary(iCol).ToString + Constants.vbTab);
    //        }
    //    }
    //}


    // 在 Page_Load 中還沒有載入全部的控制項, 所以在 Page_PreRenderComplete 處理
    protected void Page_PreRenderComplete(object sender, EventArgs e) {

        //// 將取得的資料秀在 GridView ( default by Status=Processing )
        //if (!IsPostBack) {
        //    string sDefaultSelected = "Processing";
        //    // 預設的搜尋條件
        //    // 記錄排序方式與資料來源
        //    ////ddlStatus.SelectedIndex = ddlStatus.Items.IndexOf(new ListItem(sDefaultSelected));
        //    dtMainWork = new TEC_MainWorksData().Select("Status='" + sDefaultSelected + "'", "FABID ASC");
        //    // 如果預設的搜尋條件 (Pending) 沒有任何資料, 則預設的搜尋條件設為 Processing
        //    if (dtMainWork.Rows.Count < 1) {
        //        sDefaultSelected = "Processing";
        //        ddlStatus.SelectedIndex = ddlStatus.Items.IndexOf(new ListItem(sDefaultSelected));
        //        dtMainWork = new TEC_MainWorksData().Select("Status='" + sDefaultSelected + "'", "FABID ASC");
        //    }

        //    ViewState["ConditionStr"] = "Status='" + sDefaultSelected + "'";        // default show 
        //    ViewState["OrderByDirection"] = "ASC";                                  // direction

        //    GridView1.DataSource = dtMainWork;
        //    ViewState["dataSource"] = dtMainWork;
        //    GridView1.DataBind();
        //}
    }


    private string sWhereCondi = "";
    private DataTable dtMainWork = null;
    protected void btnToSelect_Click(object sender, EventArgs e) {
        //取得條件的字串
        sWhereCondi = "";
        if ( txtJobNo.Text != "")
            sWhereCondi += " and " + "T1.JobNo like '%" + txtJobNo.Text + "%'";
        if (txtFABID.Text != "")
            sWhereCondi += " and " + "T1.FABID like '%" + txtFABID.Text + "%'";
        if (txtTOOLID.Text != "")
            sWhereCondi += " and " + "T1.SES_ToolNo like '%" + txtTOOLID.Text + "%'";
        //if (txtGroupName.Text != "")
        //    sWhereCondi += " and " + "T2.GroupName like '%" + txtGroupName.Text + "%'";
        if (ddlDept.SelectedValue != "")
            sWhereCondi += " and " + "T2.GroupName like '%" + ddlDept.SelectedValue + "%'";
        if (txtResponsibility.Text != "")
            sWhereCondi += " and " + "T2.Responsibility like '%" + txtResponsibility.Text + "%'";
        if (txtTroubleNo.Text != "")
            sWhereCondi += " and " + "T1.TroubleNo like '%" + txtTroubleNo.Text + "%'";
        if (ddlStatus.SelectedValue != "")
            sWhereCondi += " and " + "T1.Status = '" + ddlStatus.SelectedValue + "'";
        string StartDate = txtStartDate.Text, EndDate = txtEndDate.Text;
        try {
            DateTime.Parse(StartDate);
            DateTime.Parse(EndDate);
        }
        catch {
            // 時間格式不正確
            chkExpectDate.Checked = false;
            chkCreateDate.Checked = false;
            chkFinishedDate.Checked = false;
            chkDeliveryReportDate.Checked = false;
        }

        if (chkExpectDate.Checked)
            sWhereCondi += " and " + "((T2.ExpectStartDate >= '" + StartDate + "' and T2.ExpectStartDate <='" + EndDate + "')" +
                                " or (T2.ExpectEndDate >= '" + StartDate + "' and T2.ExpectEndDate <='" + EndDate + "'))";
        if (chkCreateDate.Checked)
            sWhereCondi += " and " + "(T1.CreateDate >= '" + StartDate + "' and T1.CreateDate <='" + EndDate + "')";
        if (chkFinishedDate.Checked)
            sWhereCondi += " and " + "(T1.FinishDate >= '" + StartDate + "' and T1.FinishDate <='" + EndDate + "')";
        if (chkDeliveryReportDate.Checked)
            sWhereCondi += " and " + "(T1.DeliveryReportDate >= '" + StartDate + "' and T1.DeliveryReportDate <='" + EndDate + "')";

        if (sWhereCondi.Length > 0)
            sWhereCondi = sWhereCondi.Substring(4);
        else
            sWhereCondi = "1=1";

        //string sJobNo = "", sFABID = "", sToolID = "", sGroupName = "", sResponsibility = "";
        //string sStatus = "", sStartDate = "", sEndDate = "";
        //bool bCheckedExpectDate = false, bCheckedCreateDate = false, bCheckFinishedDate = false;
        ////取得條件的字串
        //sJobNo = txtJobNo.Text.Replace("--","").Replace("''","").Trim() ;
        //sFABID = txtFABID.Text.Replace("--", "").Replace("''", "").Trim();
        //sToolID = txtTOOLID.Text.Replace("--", "").Replace("''", "").Trim();
        //sGroupName = txtGroupName.Text.Replace("--", "").Replace("''", "").Trim();
        //sResponsibility = txtResponsibility.Text.Replace("--", "").Replace("''", "").Trim();
        //sStatus = ddlStatus.Text.Replace("--", "").Replace("''", "").Trim();
        //sStartDate = txtStartDate.Text.Replace("--", "").Replace("''", "").Trim();
        //sEndDate = txtEndDate.Text.Replace("--", "").Replace("''", "").Trim();


        // Columns : WorkID,JobNo,CreateDate,CreateFrom,Proposer,FABID,SES_ToolNo,Description,RootCause,Responsibility,ExpectStartDate,Status,
        //           FinishDate, TroubleNo, Comment, WorkID1, LastActionDate, Recorder, LastAction, LastRecordFile
        dtMainWork = new TEC_MainWorksData().SelectByManualSearch(sWhereCondi, "FABID ASC");

        Session["dtMainWorks"] = dtMainWork;
        if ( sWhereCondi != "1=1")
            btnPrompt.Text = "Total Counts : " + dtMainWork.Rows.Count;
        else
            btnPrompt.Text = Resources.Universal.WorksList_MaxRowPrompt;
        //dtMainWork = new TEC_MainWorksData().SelectByManualSearch(sJobNo, sFABID, sToolID, sGroupName, sResponsibility, sStatus,
        //    bCheckedExpectDate, bCheckedCreateDate, bCheckFinishedDate, sStartDate, sEndDate);


        // 記錄排序方式與資料來源
        ViewState["ConditionStr"] = sWhereCondi;         
        ViewState["OrderByDirection"] = "ASC";                      

        GridView1.DataSource = dtMainWork;
        ViewState["dataSource"] = dtMainWork;
        GridView1.DataBind();

    }



    protected void GridView1_DataBound(object sender, EventArgs e) {
        GridView gv = ((GridView)sender);


        // 取得 JobNo and Record 的欄位位置
        int iJobNoPosi = -1, iRecordPosi = -1;
        // 將 group and responsibility 的 \r\n 取代為 <br>
        int iGroup = -1, iResposibility = -1;
        int iRowIdx = 0;
        System.Text.StringBuilder sb = new System.Text.StringBuilder("");
        for (int i = 0; i < gv.Columns.Count; i++) {
            if (gv.Columns[i].ToString() == Resources.Universal.WorksList_JobNo)
                iJobNoPosi = i;
            if (gv.Columns[i].ToString() == Resources.Universal.WorksList_Record)
                iRecordPosi = i;
            //if (GridView1.Columns[i].HeaderText == Resources.Universal.WorksList_GroupID)
            //    iGroup = i;
            //if (GridView1.Columns[i].HeaderText == Resources.Universal.WorksList_Responsibility)
            //    iResposibility = i;
        }

        //foreach (DataRow dr in dtMainWork.Rows) {
        //    sb = new System.Text.StringBuilder("");
        //    // get details of main work item
        //    sb.AppendFormat("{0} : {1}\r\n", Resources.Universal.Comm_CreateDate, dr["CreateDate"].ToString());
        //    sb.AppendFormat("{0} : {1}\r\n", Resources.Universal.CreateBy, dr["CreateFrom"].ToString());
        //    sb.AppendFormat("{0} : {1}\r\n", Resources.Universal.WorksList_ExpectStartDate, dr["ExpectStartDate"].ToString());
        //    sb.AppendFormat("{0} : {1}\r\n", Resources.Universal.WorksList_ExpectEndDate, dr["ExpectEndDate"].ToString());

        //    gv.Rows[iRowIdx].Cells[0].ToolTip = sb.ToString().Substring(0, sb.Length - 2);
        //    if (iJobNoPosi > -1)
        //        gv.Rows[iRowIdx].Cells[iJobNoPosi].ToolTip = getJobNoDetail(dr["JobNo"].ToString());
        //    if (iRecordPosi > -1)
        //        gv.Rows[iRowIdx].Cells[iRecordPosi].ToolTip = getWorkRecord(dr["WorkID"].ToString());

        //    iRowIdx++;
        //}
        foreach (GridViewRow gvr in gv.Rows) {
            sb = new System.Text.StringBuilder("");
            int iRow = gv.PageIndex * gv.PageSize + iRowIdx;         // row index

            //// 開啟子視窗
            //Label lbl = ((Label)gv.Rows[iRowIdx].Cells[iJobNoPosi].FindControl("lblLinkToSubForm"));
            //lbl.Attributes.Add("onclick", "openDetailPage('" + dtMainWork.Rows[iRow]["WorkID"].ToString() + "')");
            //lbl.Attributes.Add("style", "cursor: hand; color: blue; ");

            // get details of main work item
            sb.AppendFormat("{0} : {1}\r\n", Resources.Universal.Comm_CreateDate, dtMainWork.Rows[iRow]["CreateDate"].ToString());
            sb.AppendFormat("{0} : {1}\r\n", Resources.Universal.WorksList_CreateFrom, dtMainWork.Rows[iRow]["CreateFrom"].ToString());
            //sb.AppendFormat("{0} : {1}\r\n", Resources.Universal.WorksList_ExpectStartDate, dtMainWork.Rows[iRow]["ExpectStartDate"].ToString());
            //sb.AppendFormat("{0} : {1}\r\n", Resources.Universal.WorksList_ExpectEndDate, dtMainWork.Rows[iRow]["ExpectEndDate"].ToString());

            gv.Rows[iRowIdx].Cells[0].ToolTip = sb.ToString().Substring(0, sb.Length - 2);
            if (iJobNoPosi > -1)
                gv.Rows[iRowIdx].Cells[iJobNoPosi].ToolTip = getJobNoDetail(dtMainWork.Rows[iRow]["JobNo"].ToString());
            if (iRecordPosi > -1)
                gv.Rows[iRowIdx].Cells[iRecordPosi].ToolTip = getWorkRecord(dtMainWork.Rows[iRow]["WorkID"].ToString());


            if ((Label)gvr.FindControl("lblGroupID") != null)
                ((Label)gvr.FindControl("lblGroupID")).Text = ((Label)gvr.FindControl("lblGroupID")).Text.Replace("\r\n", "<br>");
            if ((Label)gvr.FindControl("lblResponsibility") != null)
                ((Label)gvr.FindControl("lblResponsibility")).Text = ((Label)gvr.FindControl("lblResponsibility")).Text.Replace("\r\n", "<br>");

            //// 
            //if (((Label)gv.Rows[iRowIdx].FindControl("lblFinishDate")).Text != "") {
            //    ((Label)gv.Rows[iRowIdx].FindControl("lblLastSchedule")).Text += " >>" + ((Label)gv.Rows[iRowIdx].FindControl("lblFinishDate")).Text;
            //    gvr.ForeColor = System.Drawing.Color.Red;
            //}
            // 
            switch ((((Label)gv.Rows[iRowIdx].FindControl("lblStatus")).Text)) {
                case "Finished":
                    gvr.ForeColor = System.Drawing.Color.Black;
                    break;
                case "Discard":
                    gvr.ForeColor = System.Drawing.Color.Brown;
                    break;
                case "Processing":
                    gvr.ForeColor = System.Drawing.Color.DarkOrange;
                    break;
                default:
                    gvr.ForeColor = System.Drawing.Color.Red;
                    break;
            }
            
            iRowIdx++;
        }
    }
    // get JobNo details information
    private string getJobNoDetail(string JobNo) {
        if (JobNo == "")
            return "";

        DataTable dt = new TEC_JobNoData().Select(("JobNo='" + JobNo + "'"));
        if (dt.Rows.Count <= 0) {
            return "";
        }
        System.Text.StringBuilder sb = new System.Text.StringBuilder("");
        sb.AppendFormat("{0} : {1}\r\n", Resources.Universal.WorksList_JobNo, dt.Rows[0][1].ToString().Replace("\r\n", ","));
        sb.AppendFormat("{0} : {1}\r\n", Resources.Universal.JobNo_Charge, dt.Rows[0][2].ToString().Replace("\r\n", ","));
        sb.AppendFormat("{0} : {1}\r\n", Resources.Universal.Comm_FABID, dt.Rows[0][3].ToString().Replace("\r\n", ","));
        sb.AppendFormat("{0} : {1}\r\n", Resources.Universal.Comm_IsClosed, dt.Rows[0][4].ToString().Replace("\r\n", ","));
        sb.AppendFormat("{0} : {1}\r\n", Resources.Universal.Comm_Description, dt.Rows[0][5].ToString().Replace("\r\n", ","));

        return sb.ToString().Substring(0, sb.Length - 2);
    }
	// get WrokRecord details information
	private string getWorkRecord (string WorkID)
	{
		if (WorkID == "")
			return "";

        int iDisplayCount = 0;
        DataTable dt = new TEC_WorkRecordData ().Select ("WorkID='" + WorkID + "'");
		if (dt.Rows.Count <= 0)
			return "";
        else if (dt.Rows.Count > 5)
            iDisplayCount = 5;
        else
            iDisplayCount = dt.Rows.Count;

        System.Text.StringBuilder sb = new System.Text.StringBuilder("");
        // index 0 -> WorkID, index 1 -> DateTime, index 2 -> journalist, index 3 -> record text, index 4 -> attach file
        for (int i = 0; i < iDisplayCount; i++)  //只取最近五項
			sb.AppendFormat ("{0} ({1}) => {2}\r\n", dt.Rows[i]["RecordDateTime"].ToString (), dt.Rows[i]["Journalist"].ToString (), dt.Rows[i]["Action"].ToString () );

        return sb.ToString ().Substring (0, sb.Length - 2);
	}


    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) {
        if (e.Row.RowType == DataControlRowType.DataRow) {
            e.Row.Cells[1].Attributes.Add("style", "vnd.ms-excel.numberformat:@;");
        }
    }



    protected void gridView_PageIndexChanging(object sender, GridViewPageEventArgs e) {
        dtMainWork = (DataTable) ViewState["dataSource"] ;
        GridView1.DataSource = dtMainWork;
        GridView1.PageIndex = e.NewPageIndex;
        GridView1.DataBind();
    }

    protected void gridView_Sorting(object sender, GridViewSortEventArgs e) {
        dtMainWork = new TEC_MainWorksData().SelectByManualSearch(ViewState["ConditionStr"].ToString(),
            e.SortExpression + " " + ConvertSortDirectionToSql()); //e.SortDirection));

        GridView1.DataSource = dtMainWork;
        ViewState["dataSource"] = dtMainWork;
        GridView1.DataBind();
    }
    private string ConvertSortDirectionToSql() {
        string newSortDirection = "";
        if (ViewState["Direction"] != null) {
            if (ViewState["Direction"].ToString() == "ASC")
                newSortDirection = "DESC";
            else
                newSortDirection = "ASC";
        }
        else {
            newSortDirection = "ASC";
        }

        ViewState["Direction"] = newSortDirection;
        return newSortDirection;
    }
}
