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_JobNo : System.Web.UI.Page {
    // 屬性
    private bool LoadDataEmpty {
        //  some controls that are used within a GridView, such as the calendar control, can cuase post backs.
        //  we need to preserve LoadDataEmpty across post backs.
        get { return (bool)(ViewState["LoadDataEmpty"] ?? false); }
        set { ViewState["LoadDataEmpty"] = value; }
    }





    //the function code for localization on this page
    protected override void InitializeCulture() {
        ProfileCommon 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");
        }
    }



    //public void LinkButtonCancel_Onclick(object sender, EventArgs e) { }

    public void btnAddNew_Click(object sender, EventArgs e) {
        GridView1.ShowFooter = true;
        btnAddNew.Enabled = false;
    }
    public void btnSave_Click(object sender, EventArgs e) {
        GridView1.ShowFooter = false;
        btnAddNew.Enabled = true;
    }
    public void btnInsertCancel_Click(object sender, EventArgs e) {
        GridView1.ShowFooter = false;
        btnAddNew.Enabled = true;
    }


    protected void Page_Load(object sender, EventArgs e)  {
        if (!IsPostBack) {
            GridView1.DataKeyNames = new TEC_JobNoData().PrimaryKeyColumnNames;

            ddlStatus.SelectedIndex = 1;
        }
    }
    protected void Page_PreRenderComplete(object sender, EventArgs e) {
        //btnAddNew.Visible = true;
        //if (ViewState["SourceTable"] != null) { 
        //    GridView1.DataSourceID = "";
        //    GridView1.DataSource = (DataTable) ViewState["SourceTable"];
        //    GridView1.DataBind();

        //    if ( ((DataTable) ViewState["SourceTable"]).Rows.Count == 0)
        //        btnAddNew.Visible = false;
        //}
    }

    protected void ObjectDataSourceMain_Selected(object sender, ObjectDataSourceStatusEventArgs e) {
        //  bubble exceptions before we touch e.ReturnValue
        if (e.Exception != null) {
            throw e.Exception;
        }

        //  get the DataTable from the ODS select mothod
        DataTable dataTable = (DataTable)e.ReturnValue;

        //  if rows=0 then add a dummy (null) row and set the LoadDataEmpty flag.
        if (dataTable.Rows.Count == 0) {
            dataTable.Rows.Add(dataTable.NewRow());
            LoadDataEmpty = true;
        }
        else {
            LoadDataEmpty = false;
        }
    }

    protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e) {
        //  when binding a row, look for a zero row condition based on the flag.
        //  if we have zero data rows (but a dummy row), hide the grid view row
        //  and clear the controls off of that row so they don't cause binding errors
        if (LoadDataEmpty && e.Row.RowType == DataControlRowType.DataRow) {
            e.Row.Visible = false;
            e.Row.Controls.Clear();
        }

    }

    protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e) {

        //  handle the save button on the footer row. this is the only manual data operation
        //  that must be done. update and delete are handled by the gridview and ODS
        if (e.CommandName == "Save") {
            string JobNo = ((TextBox)GridView1.FooterRow.FindControl("txtAddJobNo")).Text.Trim().ToUpper();
            string FABID = Request[GridView1.FooterRow.FindControl("txtFABID").ClientID.Replace("_","$")].ToString() ?? "";
            string Tools = Request[GridView1.FooterRow.FindControl("txtTools").ClientID.Replace("_", "$")].ToString() ?? ""; //((TextBox)GridView1.FooterRow.FindControl("txtTools")).Text ?? "";
            string CreateDate = ((TextBox)GridView1.FooterRow.FindControl("txtAddCreateDate")).Text ?? "";
            string Charge = ((TextBox)GridView1.FooterRow.FindControl("txtAddCharge")).Text ?? "";
            Boolean IsClosed = ((CheckBox)GridView1.FooterRow.FindControl("ChkAddIsClosed")).Checked;
            string Description = ((TextBox)GridView1.FooterRow.FindControl("txtAddDescription")).Text ?? "";

            // 判斷 AZZ,AJW (以FAB為基本單位, 沒有機台的配給) or TW,AJW (會配給有機台)
            if ((JobNo.Substring(0, 2) == "TW" || JobNo.Substring(0, 2) == "JW" || JobNo.Substring(0, 3) == "JWL") && JobNo.Substring(0, 3) != "TWL") {
                if (FABID.Trim() == "") {
                    Response.Redirect("/SEST/Common/ErrorPage.aspx?BackPageCount=-2&ErrorMessage=" + Resources.Universal.Msg_FABIDCanNotAssignEmpty);
                    return;
                }
                if (Tools.Trim() == "") {
                    Response.Redirect("/SEST/Common/ErrorPage.aspx?BackPageCount=-2&ErrorMessage=" + Resources.Universal.Err_ToolCanNotAssignEmpty);
                    return;
                }
            }
            else if (JobNo.Substring(0,3) != "AJM" && JobNo.Substring(0,3) != "ATM") {
                if (FABID.Trim() == "") {
                    Response.Redirect("/SEST/Common/ErrorPage.aspx?BackPageCount=-2&ErrorMessage=" + Resources.Universal.Msg_FABIDCanNotAssignEmpty);
                    return;
                }
            }
            new TEC_JobNoData().Insert(JobNo, FABID, Tools, CreateDate, Charge, IsClosed, Description);

            //GridView1.DataBind();
        }
        if (e.CommandName == "Update") {
            // 取得目前更新的row index
            int iRowEdit = -1;
            for (int i = 0; i < GridView1.Rows.Count; i++) {
                if ( (GridView1.Rows[i].RowState & DataControlRowState.Edit) == DataControlRowState.Edit) {
                    iRowEdit = i; break;
                }
            }

            string JobNo = ((TextBox)GridView1.Rows[iRowEdit].FindControl("txtEditJobNo")).Text;
            string FABID = Request[GridView1.Rows[iRowEdit].FindControl("txtFABID").ClientID.Replace("_", "$")].ToString() ?? "";
            string Tools = ((TextBox)GridView1.Rows[iRowEdit].FindControl("txtTools")).Text ?? "";
            //string CreateDate = ((TextBox)GridView1.FooterRow.FindControl("txtAddCreateDate")).Text ?? ""; 
            //string Charge = ((TextBox)GridView1.Rows[iRowEdit].FindControl("txtEditCharge")).Text ?? "";
            //Boolean IsClosed = ((CheckBox)GridView1.Rows[iRowEdit].FindControl("ChkEditIsClosed")).Checked;
            //string Description = ((TextBox)GridView1.Rows[iRowEdit].FindControl("txtEditDescription")).Text ?? "";
            // 會自動的執行 update 命令 ( 與 AddNew 不一樣), 而且並無法記錄住  txtFABID 的值 (txtTools 卻可以
            // 不知道是不是應該 txtFABID 這個欄位有排序
            //new TEC_JobNoData().Update(JobNo, FABID, Tools, CreateDate, Charge, IsClosed, Description, JobNo);
            ((TextBox)GridView1.Rows[iRowEdit].FindControl("txtFABID")).Text = FABID;
            // 判斷 AZZ,AJW,AJW (以FAB為基本單位, 沒有機台的配給) or JWL or JW or TW (會配給有機台)
            if ((JobNo.Substring(0, 2) == "TW" || JobNo.Substring(0, 2) == "JW" || JobNo.Substring(0, 3) == "JWL") && JobNo.Substring(0, 3) != "TWL") {
                if (FABID.Trim() == "") {
                    Response.Redirect("/SEST/Common/ErrorPage.aspx?BackPageCount=-2&ErrorMessage=" + Resources.Universal.Msg_FABIDCanNotAssignEmpty);
                    return;
                }
                if (Tools.Trim() == "") {
                    Response.Redirect("/SEST/Common/ErrorPage.aspx?BackPageCount=-2&ErrorMessage=" + Resources.Universal.Err_ToolCanNotAssignEmpty);
                    return;
                }
            }
            else if (JobNo.Substring(0, 3) != "AJM" && JobNo.Substring(0, 3) != "ATM") {
                if (FABID.Trim() == "") {
                    Response.Redirect("/SEST/Common/ErrorPage.aspx?BackPageCount=-2&ErrorMessage=" + Resources.Universal.Msg_FABIDCanNotAssignEmpty);
                    return;
                }
            }
            
            
            btnAddNew.Enabled = true;
            GridView1.DataBind();
        }

        
        // 當選擇編輯時不允許新增, 當按取消編輯時再允許
        if (e.CommandName == "Edit") {
            btnInsertCancel_Click( null, null);
            GridView1.ShowFooter = false;
            btnAddNew.Enabled = false;
        }
        if (e.CommandName == "Cancel")
            btnAddNew.Enabled = true;


        // 往前移一頁(避免重新整理時再執行一次)再重新載入
        //Page_Load(this, new EventArgs());
        string sBackCount = "0";
        if (e.CommandName == "Delete")
            sBackCount = "-1";
        else if (e.CommandName == "Save")
            sBackCount = "-2";
        if (int.Parse(sBackCount) < 0) {
            //string sScript = "";
            //sScript = "<script language='javascript' type='text/javascript'>\r\n";
            //sScript += "window.history.go(" + sBackCount + ");";
            //sScript += "window.location.replace('JobNo.aspx');";
            //sScript += "</script>\r\n";
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Back", SES_Common.BackScript("JobNo.aspx", 1));
        }
    }

    protected void btnSearch_Click(object sender, EventArgs e) {
        //取得條件的字串
        string sWhereCondi = "";
        try {
            if (txtSelConditionStartDate.Text.Trim() != "")
                DateTime.Parse(txtSelConditionStartDate.Text.Trim());
            if (txtSelConditionEndDate.Text.Trim() != "")
                DateTime.Parse(txtSelConditionEndDate.Text.Trim());
        }
        catch {
            Response.Redirect("/SEST/Common/ErrorPage.aspx?BackPageCount=-1&ErrorMessage=" + Resources.Universal.Err_DateFormatIncorrect);
            return;
        }
        if (txtSelConditionJobNo.Text != "")
            sWhereCondi += " And JobNo like '%" + txtSelConditionJobNo.Text.Trim() + "%'";
        if (txtSelConditionFABID.Text != "")
            sWhereCondi += " And FABID like '%" + txtSelConditionFABID.Text.Trim() + "%'";
        if (txtSelConditionStartDate.Text != "")
            sWhereCondi += " And CreateDate >= '" + txtSelConditionStartDate.Text.Trim() + "'";
        if (txtSelConditionEndDate.Text != "")
            sWhereCondi += " And CreateDate <= '" + txtSelConditionEndDate.Text.Trim() + "'";
        if (ddlStatus.SelectedValue != "") {
            switch (ddlStatus.SelectedValue) {
                case "Processing":
                    sWhereCondi += " And IsClosed=0";
                    break;
                case "Closed":
                    sWhereCondi += " And IsClosed=1";
                    break;
            }
        }

        if (!IsPostBack) {
            sWhereCondi = "IsClosed=False";    // first time (default) select of processing
        }
        else {
            if (sWhereCondi == "")
                sWhereCondi = "1=1";                // do not select while selecting on not any condition
            else
                sWhereCondi = sWhereCondi.Substring(4).Replace("--", "").Replace("''", "");
        }
        

        // 利用 SelectParameters 的方式呼叫另一個有 Condition 的 Select 函數
        //DataTable dtJobNo = null;
        //dtJobNo = new TEC_JobNoData().Select(sWhereCondi);
        GridView1.ShowFooter = false;
        btnAddNew.Enabled = true;

        //if (dtJobNo != null) {
        //ViewState["SourceTable"] = dtJobNo;

        //hidCondition.Value = sWhereCondi;
        ObjectDataSource1.SelectParameters.RemoveAt(0);
        ObjectDataSource1.SelectParameters.Add("Condition", sWhereCondi);
        GridView1.EditIndex = -1;
        //GridView1.DataSourceID = "";
        //GridView1.DataSource = dtJobNo;
        //GridView1.DataBind();

        //}
    }


    // open sub window to select FABID while object click on client
    protected void txtEditFABID_onLoad(object sender, EventArgs e) {
        //// 因為是以 this.id 方式傳送值, 所以 Update and Add New 可以共用
        //TextBox txt = (TextBox)sender;
        //txt.ReadOnly = true;
        ////txt.Attributes.Add("onclick", "openSubPageFABID(this.id)");
        //txt.Attributes.Add("onclick", "txtFAB_onclick(this.id)");
        //txt.Attributes.Add("style", "cursor: hand");
    }
    protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e) {
        // 080508 : 變更一個工番可以對應多個 FAB (此頁改由直接按物件開 SelectPage ~ 與 Open FAB 一樣)
        HyperLink hl = (HyperLink)e.Row.FindControl("hlTools");
        //// 一般項目 (for Update)
        //if (hl != null && e.Row.FindControl("txtEditFABID") != null) {
        //    hl.Attributes.Add("onclick", "openSubPageToolID('" + e.Row.FindControl("txtTools").ClientID + "'," +
        //        e.Row.FindControl("txtEditFABID").ClientID + ",'True' )");
        //    hl.Attributes.Add("style", "cursor: hand");
        //}
        //// 新增項目 (Footer)
        //if (hl != null && e.Row.FindControl("txtFABID") != null) {
        //    hl.Attributes.Add("onclick", "openSubPageToolID('" + e.Row.FindControl("txtTools").ClientID + "'," +
        //        e.Row.FindControl("txtFABID").ClientID + ",'True' )");
        //    hl.Attributes.Add("style", "cursor: hand");
        //}
        if (e.Row.FindControl("txtFABID") != null && e.Row.FindControl("txtTools") != null) {
            TextBox txt = (TextBox)e.Row.FindControl("txtFABID");
            //txt.ReadOnly = true;
            //txt.Attributes.Add("onclick", "openSubPageFABID(this.id)");
            txt.Attributes.Add("onclick", "txtFAB_onclick(this.id,'" + e.Row.FindControl("txtTools").ClientID + "')");
            txt.Attributes.Add("style", "cursor: hand");
            
            txt = (TextBox)e.Row.FindControl("txtTools");
            //txt.ReadOnly = true;  // ReadOnly 在 submit 後無法取得資料
            txt.Attributes.Add("onclick", "txtTool_onclick(this.id,'" + e.Row.FindControl("txtFABID").ClientID + "')");
            txt.Attributes.Add("style", "cursor: hand");
        }

        hl = (HyperLink)e.Row.FindControl("hlCreateDate");
        // 一般項目 (for Update)
        if (hl != null && e.Row.FindControl("txtEditCreateDate") != null) {
            hl.Attributes.Add("onclick", "openSubPageCalendar('" + e.Row.FindControl("txtEditCreateDate").ClientID + "' )");
            hl.Attributes.Add("style", "cursor: hand");
        }
        // 新增項目 (Footer)
        if (hl != null && e.Row.FindControl("txtAddCreateDate") != null) {
            hl.Attributes.Add("onclick", "openSubPageCalendar('" + e.Row.FindControl("txtAddCreateDate").ClientID + "' )");
            hl.Attributes.Add("style", "cursor: hand");
        }


        // 不是來自管理的路徑 (功能 hidden)
        if (Request.Url.ToString().ToUpper().IndexOf("SEST/MAINTENANCE/") < 0) {
            btnAddNew.Visible = false;                  //新增按鈕
            GridView1.Columns[8].Visible = false;       //刪除,編輯
        }

    }
}
