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_HR_Organization : System.Web.UI.Page {
    //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");
        }
    }

    
    
    protected void Page_Load(object sender, EventArgs e) {
        if (Request["Organization"] != null) { 
            string sOrganization = Request["Organization"].ToString();
            string sCName = "", sEName = "", sManager = "", sDeputy = "", sManagerTitle = "", sDeputyTitle = "", sParent = "", sDescription = "";

            while (sOrganization != "") {
                string sTemOrg = "";
                if (sOrganization.IndexOf("/") > -1)
                    sTemOrg = sOrganization.Substring(0, sOrganization.IndexOf("/"));
                else 
                    sTemOrg = sOrganization;


                sTemOrg = sTemOrg.Replace("--","").Replace("'","");
                DataTable dt = new HR_OrganizationData().Select("OrganizationID='" + sTemOrg + "'");
                if (dt.Rows.Count > 0) {
                    sCName = dt.Rows[0]["CName"].ToString();
                    sEName = dt.Rows[0]["EName"].ToString();
                    sManager = dt.Rows[0]["Manager"].ToString();
                    sManagerTitle = dt.Rows[0]["ManagerTitle"].ToString();
                    sDeputy = dt.Rows[0]["Deputy"].ToString();
                    sDeputyTitle = dt.Rows[0]["DeputyTitle"].ToString();
                    sParent = dt.Rows[0]["Parent"].ToString();
                    sDescription = dt.Rows[0]["Description"].ToString();

                    showDepartment(sTemOrg, sCName, sEName, sManager, sManagerTitle, sDeputy, sDeputyTitle, sParent, sDescription);
                }

                if (  sOrganization.IndexOf("/") > -1)
                    sOrganization = sOrganization.Substring( sOrganization.IndexOf("/") + 1);
                else
                    sOrganization = "";
            }

            if ( Request["ParentOfNew"] != null)
                showAddNewTable( Request["ParentOfNew"].ToString());
        }
    }


    void showDepartment(string sID, string sCName, string sEName, string sManager, string sManagerTitle, 
        string sDeputy, string sDeputyTitle, string sParent, string sDescription) {
        Table tbl = new Table();
        tbl.Width = Unit.Percentage(100);
        tbl.BackColor = System.Drawing.Color.CornflowerBlue;

        // Add Header
        TableHeaderRow thr = new TableHeaderRow();
        thr.BackColor = System.Drawing.Color.Honeydew;
        TableHeaderCell thc = new TableHeaderCell();
        //thc.Width = Unit.Percentage(100);
        thc.ColumnSpan = 5;
        thc.Text = sCName + " (" + sEName + ")";
        thr.Cells.Add(thc);
        tbl.Rows.Add(thr);
        
        // --------- First Row ----------------
        TableRow tr = new TableRow();
        tr.BackColor = System.Drawing.Color.Bisque;
        // ID Label
        TableCell tc = new TableCell();
        tc.Width = Unit.Pixel(80);
        tc.Controls.Add(createLabel(Resources.Universal.Organization_ID));
        tr.Cells.Add(tc);
        // ID TextBox
        tc = new TableCell();
        tc.Width = Unit.Pixel(160);
        tc.Controls.Add(createTextBox("txtID_" + sID, Unit.Pixel(158), FontUnit.XSmall, sID , false));
        tr.Cells.Add(tc);
        // ---------
        // Parent Label
        tc = new TableCell();
        tc.Width = Unit.Pixel(80);
        tc.Controls.Add(createLabel(Resources.Universal.Organization_ParentOrganization));
        tr.Cells.Add(tc);
        // Parent id
        tc = new TableCell();
        tc.Width = Unit.Pixel(160);
        tc.Controls.Add(createTextBox("txtParent_" + sID, Unit.Pixel(158), FontUnit.XSmall, sParent, true));
        tr.Cells.Add(tc);
        // ---------
        //Add Content
        tc = new TableCell();
        tc.RowSpan = 4;
        tc.Wrap = true;
        DataTable dt = new HR_OrganizationData().Select("Parent='" + sID + "'");
        Panel pnl = new Panel();
        pnl.Width = Unit.Percentage(100);
        pnl.Height = Unit.Percentage(100);
        pnl.ID = "pnlContent_" + sID;
        //Button btn;
        string sGrade;
        foreach (DataRow dr in dt.Rows) {
            HyperLink hl = new HyperLink();
            string sOrganizationID = dr["OrganizationID"].ToString();
            sGrade = getGrade(sOrganizationID);
            hl.ID = "SubDepartment_" + dr["OrganizationID"].ToString();
            // Request.Path --> /SEST/Maintenance/HR/Organization.aspx
            hl.NavigateUrl = Request.Path + "?Organization=" + sGrade;
            hl.Text = " <" + dr["CName"].ToString() + "> ";

            tc.Controls.Add(hl);
        }
        //tc.Controls.Add(pnl);
        tr.Cells.Add(tc);
        tbl.Rows.Add(tr);

        // --------- Second Row ----------------
        // CName Label
        tr = new TableRow();
        tr.BackColor = System.Drawing.Color.Bisque;
        tc = new TableCell();
        tc.Width = Unit.Pixel(80);
        tc.Controls.Add(createLabel(Resources.Universal.Organization_CName));
        tr.Cells.Add(tc);
        // CName name
        tc = new TableCell();
        tc.Wrap = false;
        tc.Width = Unit.Pixel(160);
        tc.Controls.Add(createTextBox("txtCName_" + sID, Unit.Pixel(158), FontUnit.XSmall, sCName, false));
        tr.Cells.Add(tc);
        //----------
        // EName Label
        tc = new TableCell();
        tc.Width = Unit.Pixel(80);
        tc.Controls.Add(createLabel(Resources.Universal.Organization_EName));
        tr.Cells.Add(tc);
        // CName name
        tc = new TableCell();
        tc.Wrap = false;
        tc.Width = Unit.Pixel(160);
        tc.Controls.Add(createTextBox("txtEName_" + sID, Unit.Pixel(158), FontUnit.XSmall, sEName, true));
        tr.Cells.Add(tc);
        tbl.Rows.Add(tr);

        // --------- Third Row ----------------
        // Manager Label
        tr = new TableRow();
        tr.BackColor = System.Drawing.Color.Bisque;
        tc = new TableCell();
        tc.Width = Unit.Pixel(80);
        tc.Controls.Add(createLabel(Resources.Universal.Comm_Manager));
        tr.Cells.Add(tc);
        // Manager name and title
        tc = new TableCell();
        tc.Wrap = false;
        tc.Width = Unit.Pixel(160);
        //tc.Controls.Add(createTextBox("txtManager_" + sID, Unit.Pixel(72), FontUnit.XSmall, sManager, true));
        tc.Controls.Add(createManagerUserList("ddlManager_" + sID, Unit.Pixel(72), FontUnit.XSmall, sManager));
        tc.Controls.Add(createJobTitleList("ddlManagerTitle_" + sID, Unit.Pixel(82), FontUnit.XSmall, sManagerTitle));
        tr.Cells.Add(tc);
        // ---------
        // Add Deputy
        tc = new TableCell();
        tc.Width = Unit.Pixel(80);
        tc.Controls.Add(createLabel(Resources.Universal.Comm_Deputy));
        tr.Cells.Add(tc);
        // Manager name and title
        tc = new TableCell();
        tc.Wrap = false;
        tc.Width = Unit.Pixel(160);
        //tc.Controls.Add(createTextBox("txtDeputy_" + sID, Unit.Pixel(72), FontUnit.XSmall, sDeputy, true));
        tc.Controls.Add(createManagerUserList("ddlDeputy_" + sID, Unit.Pixel(72), FontUnit.XSmall, sDeputy));
        tc.Controls.Add(createJobTitleList("ddlDeputyTitle_" + sID, Unit.Pixel(82), FontUnit.XSmall, sDeputyTitle));
        tr.Cells.Add(tc);
        tbl.Rows.Add(tr);

        // --------- Fourth Row ---------
        // Description Label
        tr = new TableRow();
        tr.BackColor = System.Drawing.Color.Bisque;
        tc = new TableCell();
        tc.Width = Unit.Pixel(80);
        tc.Controls.Add(createLabel(Resources.Universal.Comm_Description));
        tr.Cells.Add(tc);
        // Description Content
        tc = new TableCell();
        tc.ColumnSpan = 3;
        tc.Wrap = false;
        tc.Controls.Add(createTextBox("txtDescription_" + sID, Unit.Percentage(98), FontUnit.XSmall, sDescription, true));
        tr.Cells.Add(tc);
        tbl.Rows.Add(tr);

        // Command
        tr = new TableRow();
        tr.BackColor = System.Drawing.Color.GhostWhite;
        tc = new TableCell();
        tc.ColumnSpan = 5;
        sGrade = getGrade(sID);
        Button btnAddNew = new Button();
        btnAddNew.ID = "btnAddNew_" + sID;
        btnAddNew.Text = Resources.Universal.Data_AddNew;
        btnAddNew.ToolTip = sGrade;
        btnAddNew.Click += new EventHandler(btnAddNew_Click);
        tc.Controls.Add(btnAddNew);
        //
        Button btnUpdate = new Button();
        btnUpdate.ID = "btnUpdate_" + sID;
        btnUpdate.Text = Resources.Universal.Data_Update;
        btnUpdate.ToolTip = sGrade;
        btnUpdate.Click += new EventHandler(btnUpdate_Click);
        tc.Controls.Add(btnUpdate);
        //
        Button btnDelete = new Button();
        btnDelete.ID = "btnDelete_" + sID;
        btnDelete.Text = Resources.Universal.Data_Delete;
        btnDelete.ToolTip = sGrade;
        btnDelete.Click += new EventHandler(btnDelete_Click);
        tc.Controls.Add(btnDelete);
        tr.Cells.Add(tc);
        tbl.Rows.Add(tr);

        pnlContent.Controls.Add(tbl);
    }
    TableCell createTableCell() { 
        return null;
    }
    Label createLabel(string Text) { 
        Label lbl = new Label();
        lbl.Text = Text;
        
        return lbl;
    }
    TextBox createTextBox(string ID, Unit Width, FontUnit FontSize, string Text, bool Enabled ) {
        TextBox btn = new TextBox();
        btn.ID = ID;
        btn.Width = Width;
        btn.Font.Size = FontSize;
        btn.Text = Text;
        btn.Enabled = Enabled;

        return btn;
    }
    DropDownList createManagerUserList(string ID, Unit Width, FontUnit FontSize, string SelectName) {
        DropDownList ddl = new DropDownList();
        string[] ar = new HR_EmployeesData().getManagerUsersName();

        ddl.ID = ID;
        ddl.Width = Width;
        ddl.Font.Size = FontSize;
        ddl.DataSource = ar;
        ddl.DataBind();
        if ( ar != null && ddl.Items[0].Text != "")
            ddl.Items.Insert(0, "");

        ddl.SelectedValue = SelectName;

        return ddl;
    }
    DropDownList createJobTitleList(string ID, Unit Width, FontUnit FontSize, string SelectName) {
        DropDownList ddl = new DropDownList();
        string[] ar = new HR_JobTitleData().SelectTitleName();

        ddl.ID = ID;
        ddl.Width = Width;
        ddl.Font.Size = FontSize;
        ddl.DataSource = ar;
        ddl.DataBind();
        ddl.Items.Insert(0, "");

        ddl.SelectedValue = SelectName;

        return ddl;
    }
    string getGrade(string OrganizationID) {
        DataTable dt = new HR_OrganizationData().Select("OrganizationID='" + OrganizationID + "'");
        string sRtn = OrganizationID;
        while ( dt.Rows.Count > 0 && dt.Rows[0]["Parent"].ToString() != "") { 
            sRtn = dt.Rows[0]["Parent"].ToString() + "/" + sRtn;
            dt = new HR_OrganizationData().Select("OrganizationID='" + dt.Rows[0]["Parent"].ToString() + "'");
        }

        return sRtn;
    }
    // 新增按鈕 (show add new table)
    public void btnAddNew_Click(object sender, EventArgs e) {
        string sOrganizationID;
        if ( ((Button)sender).ToolTip.ToString().IndexOf("/") > -1)
            sOrganizationID = ((Button)sender).ToolTip.ToString().Substring(((Button)sender).ToolTip.ToString().LastIndexOf("/") + 1);
        else
            sOrganizationID = ((Button)sender).ToolTip.ToString();

        Response.Redirect(Request.Path + "?Organization=" + ((Button)sender).ToolTip.ToString() + "&ParentOfNew=" + sOrganizationID);
        
    }
    void showAddNewTable(string Parent) {
        Table tbl = new Table();
        tbl.Width = Unit.Percentage(80);
        tbl.BackColor = System.Drawing.Color.CornflowerBlue;

        // --------- First Row ----------------
        TableRow tr = new TableRow();
        tr.BackColor = System.Drawing.Color.Violet;
        // ID Label
        TableCell tc = new TableCell();
        tc.Width = Unit.Pixel(80);
        tc.Controls.Add(createLabel(Resources.Universal.Organization_ID));
        tr.Cells.Add(tc);
        // ID TextBox
        tc = new TableCell();
        tc.Width = Unit.Pixel(160);
        TextBox txtID = new TextBox();
        tc.Controls.Add(createTextBox("txtAddNewID", Unit.Pixel(158), FontUnit.XSmall, "", true));
        tr.Cells.Add(tc);
        // ---------
        // Parent Label
        tc = new TableCell();
        tc.Width = Unit.Pixel(80);
        tc.Controls.Add(createLabel(Resources.Universal.Organization_ParentOrganization));
        tr.Cells.Add(tc);
        // Parent id
        tc = new TableCell();
        tc.Width = Unit.Pixel(160);
        tc.Controls.Add(createTextBox("txtAddNewParent", Unit.Pixel(158), FontUnit.XSmall, Parent, false));
        tr.Cells.Add(tc);
        tbl.Rows.Add(tr);

        // --------- Second Row ----------------
        // CName Label
        tr = new TableRow();
        tr.BackColor = System.Drawing.Color.Violet;
        tc = new TableCell();
        tc.Width = Unit.Pixel(80);
        tc.Controls.Add(createLabel(Resources.Universal.Organization_CName));
        tr.Cells.Add(tc);
        // CName name
        tc = new TableCell();
        tc.Wrap = false;
        tc.Width = Unit.Pixel(160);
        tc.Controls.Add(createTextBox("txtAddNewCName", Unit.Pixel(158), FontUnit.XSmall, "", true));
        tr.Cells.Add(tc);
        //----------
        // EName Label
        tc = new TableCell();
        tc.Width = Unit.Pixel(80);
        tc.Controls.Add(createLabel(Resources.Universal.Organization_EName));
        tr.Cells.Add(tc);
        // CName name
        tc = new TableCell();
        tc.Wrap = false;
        tc.Width = Unit.Pixel(160);
        tc.Controls.Add(createTextBox("txtAddNewEName", Unit.Pixel(158), FontUnit.XSmall, "", true));
        tr.Cells.Add(tc);
        tbl.Rows.Add(tr);

        // --------- Third Row ----------------
        // Manager Label
        tr = new TableRow();
        tr.BackColor = System.Drawing.Color.Violet;
        tc = new TableCell();
        tc.Width = Unit.Pixel(80);
        tc.Controls.Add(createLabel(Resources.Universal.Comm_Manager));
        tr.Cells.Add(tc);
        // Manager name and title
        tc = new TableCell();
        tc.Wrap = false;
        tc.Width = Unit.Pixel(160);
        //tc.Controls.Add(createTextBox("txtAddNewManager", Unit.Pixel(72), FontUnit.XSmall, "", true));
        tc.Controls.Add(createManagerUserList("ddlAddNewManager", Unit.Pixel(72), FontUnit.XSmall, ""));
        tc.Controls.Add(createJobTitleList("ddlAddNewManagerTitle", Unit.Pixel(82), FontUnit.XSmall, ""));
        tr.Cells.Add(tc);
        // ---------
        // Add Deputy
        tc = new TableCell();
        tc.Width = Unit.Pixel(80);
        tc.Controls.Add(createLabel(Resources.Universal.Comm_Deputy));
        tr.Cells.Add(tc);
        // Manager name and title
        tc = new TableCell();
        tc.Wrap = false;
        tc.Width = Unit.Pixel(160);
        //tc.Controls.Add(createTextBox("txtAddNewDeputy", Unit.Pixel(72), FontUnit.XSmall, "", true));
        tc.Controls.Add(createManagerUserList("ddlAddNewDeputy", Unit.Pixel(72), FontUnit.XSmall, ""));
        tc.Controls.Add(createJobTitleList("ddlAddNewDeputyTitle", Unit.Pixel(82), FontUnit.XSmall, ""));
        tr.Cells.Add(tc);
        tbl.Rows.Add(tr);


        // --------- Fourth Row ------------
        // Description Label
        tr = new TableRow();
        tr.BackColor = System.Drawing.Color.Violet;
        tc = new TableCell();
        tc.Width = Unit.Pixel(80);
        tc.Controls.Add(createLabel(Resources.Universal.Comm_Description));
        tr.Cells.Add(tc);
        // Description Content
        tc = new TableCell();
        tc.ColumnSpan = 3;
        tc.Wrap = false;
        tc.Controls.Add(createTextBox("txtAddNewDescription", Unit.Percentage(98), FontUnit.XSmall, "", true));
        tr.Cells.Add(tc);
        tbl.Rows.Add(tr);


        // Command
        tr = new TableRow();
        tr.BackColor = System.Drawing.Color.Gray;
        tc = new TableCell();
        tc.ColumnSpan = 4;
        Button btnAddNew = new Button();
        btnAddNew.ID = "btnInsert";
        btnAddNew.Text = Resources.Universal.Data_Submit;
        btnAddNew.Click += new EventHandler(btnInsert_Click);
        tc.Controls.Add(btnAddNew);
        tr.Cells.Add(tc);
        tbl.Rows.Add(tr);

        pnlContent.Controls.Add(tbl);
    }
    // 插入按鈕 (insert data to database)
    public void btnInsert_Click(object sender, EventArgs e) {
        string sID = ((TextBox)pnlContent.FindControl("txtAddNewID")).Text;
        string sParent = ((TextBox)pnlContent.FindControl("txtAddNewParent")).Text;
        string sCName = ((TextBox)pnlContent.FindControl("txtAddNewCName")).Text;
        string sEName = ((TextBox)pnlContent.FindControl("txtAddNewEName")).Text;
        string sManager = ((DropDownList)pnlContent.FindControl("ddlAddNewManager")).Text;
        string sManagerTitle = ((DropDownList)pnlContent.FindControl("ddlAddNewManagerTitle")).Text;
        string sDeputy = ((DropDownList)pnlContent.FindControl("ddlAddNewDeputy")).Text;
        string sDeputyTitle = ((DropDownList)pnlContent.FindControl("ddlAddNewDeputyTitle")).Text;
        string sDescription = ((TextBox)pnlContent.FindControl("txtAddNewDescription")).Text;

        try {
            new HR_OrganizationData().Insert(sID, sCName, sEName, sManager, sManagerTitle, sDeputy, sDeputyTitle, sParent, sDescription);
        }
        catch (Exception ex) {
            Response.Redirect("/SEST/Common/ErrorPage.aspx?BackPageCount=-1&ErrorMessage=" + ex.Message.Replace("\r\n", "=>"));
        }

        Response.Redirect(Request.Url.ToString().Substring(0, Request.Url.ToString().IndexOf("&")));
    }


    // 更新按鈕 (update data)
    public void btnUpdate_Click(object sender, EventArgs e) {
        string sOrganizationID;
        if (((Button)sender).ToolTip.ToString().IndexOf("/") > -1)
            sOrganizationID = ((Button)sender).ToolTip.ToString().Substring(((Button)sender).ToolTip.ToString().LastIndexOf("/") + 1);
        else
            sOrganizationID = ((Button)sender).ToolTip.ToString();

        string sID = ((TextBox)pnlContent.FindControl("txtID_" + sOrganizationID)).Text;
        string sParent = ((TextBox)pnlContent.FindControl("txtParent_" + sOrganizationID)).Text;
        string sCName = ((TextBox)pnlContent.FindControl("txtCName_" + sOrganizationID)).Text;
        string sEName = ((TextBox)pnlContent.FindControl("txtEName_" + sOrganizationID)).Text;
        //string sManager = ((TextBox)pnlContent.FindControl("txtManager_" + sOrganizationID)).Text;
        string sManager = ((DropDownList)pnlContent.FindControl("ddlManager_" + sOrganizationID)).Text;
        string sManagerTitle = ((DropDownList)pnlContent.FindControl("ddlManagerTitle_" + sOrganizationID)).Text;
        string sDeputy = ((DropDownList)pnlContent.FindControl("ddlDeputy_" + sOrganizationID)).Text;
        string sDeputyTitle = ((DropDownList)pnlContent.FindControl("ddlDeputyTitle_" + sOrganizationID)).Text;
        string sDescription = ((TextBox)pnlContent.FindControl("txtDescription_" + sOrganizationID)).Text;


        try {
            new HR_OrganizationData().Update(sID, sCName, sEName, sManager, sManagerTitle, sDeputy, sDeputyTitle, sParent, sDescription, sID);
        }
        catch (Exception ex) {
            Response.Redirect("/SEST/Common/ErrorPage.aspx?BackPageCount=-1&ErrorMessage=" + ex.Message.Replace("\r\n", "=>"));
        }
        if ( Request.Url.ToString().IndexOf("&") > -1)
            Response.Redirect(Request.Url.ToString().Substring(0, Request.Url.ToString().IndexOf("&")));
        else
             Response.Redirect(Request.Url.ToString());
    }


    // 刪除按鈕
    public void btnDelete_Click(object sender, EventArgs e) {
        string sOrganizationID;
        if (((Button)sender).ToolTip.ToString().IndexOf("/") > -1)
            sOrganizationID = ((Button)sender).ToolTip.ToString().Substring(((Button)sender).ToolTip.ToString().LastIndexOf("/") + 1);
        else
            sOrganizationID = ((Button)sender).ToolTip.ToString();

        if (new HR_OrganizationData().Count("Parent='" + sOrganizationID + "'") > 0)
            Response.Redirect("/SEST/Common/ErrorPage.aspx?BackPageCount=-1&ErrorMessage=Can not delete because it is not tail item");
        else {
            HR_OrganizationData orga =  new HR_OrganizationData();
            orga.Delete(sOrganizationID);
            orga = null;

            if (Request.Url.ToString().IndexOf("/") > -1)
                Response.Redirect(Request.Url.ToString().Substring(0, Request.Url.ToString().LastIndexOf("/")));
            else
                Response.Redirect(Request.FilePath);
        }
    }
}
