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_EmployeeDetail : 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");
        }
    }
    
    
    private string sDepartmentID = "", sOriginalID = "";
    protected void Page_Load(object sender, EventArgs e) {
        if (!IsPostBack) {
            if (Request["AddNew"] == null) {
                queryData();

                // disabled button
                btnAddNew.Visible = false;
            }
            else {
                lblTitle.Text = Resources.Universal.Data_AddNew;

                // disabled button
                btnUpdate.Visible = false;
                btnDelete.Visible = false;
            }
        }
        else { 
            //更新或刪除的動作 (IsPostBack)
        }

        // back button script
        if (ViewState["BackPageCount"] != null)
            ViewState["BackPageCount"] = int.Parse(ViewState["BackPageCount"].ToString()) + 1;
        else
            ViewState["BackPageCount"] = 1;

        btnBack.OnClientClick = "javascript: window.history.go(-" + ViewState["BackPageCount"].ToString() + "); return false";

        // delete button script
        btnDelete.OnClientClick = "javascript: " + Resources.Universal.Msg_DelConfirm ;

        // 不是來自管理的路徑 (功能 hidden)
        if (Request.Url.ToString().ToUpper().IndexOf("SEST/MAINTENANCE/") < 0) {
            btnAddNew.Visible = false;
            btnUpdate.Visible = false;
            btnDelete.Visible = false;

            ddlJobGrade.SelectedValue = "";
        }
    }

    void queryData() {
        if (Request["EmployeeID"] != null) {
            string sEmployeeID = Request["EmployeeID"].ToString().Replace("'", "").Replace("--", "");
            DataTable dtEmployee = new HR_EmployeesData().SelectIncludeLeaveJoinOrgaName("EmployeeID='" + sEmployeeID + "'");
            if (dtEmployee.Rows.Count > 0) {
                sOriginalID = dtEmployee.Rows[0]["EmployeeID"].ToString();
                lblTitle.Text = sOriginalID + " - " + dtEmployee.Rows[0]["Name"].ToString();

                txtID.Text = sOriginalID;
                txtName.Text = dtEmployee.Rows[0]["Name"].ToString();
                ddlSex.SelectedValue = dtEmployee.Rows[0]["Sex"].ToString();
                ddlBlood.SelectedValue = dtEmployee.Rows[0]["Blood"].ToString();
                txtIdentityNo.Text = dtEmployee.Rows[0]["IdentityNo"].ToString();
                txtPassportNo.Text = dtEmployee.Rows[0]["PassportNo"].ToString();
                txtFirstName.Text = dtEmployee.Rows[0]["FirstName"].ToString();
                txtLastName.Text = dtEmployee.Rows[0]["LastName"].ToString();
                txtSettleAddress.Text = dtEmployee.Rows[0]["F_Address"].ToString();
                txtSettlePhone.Text = dtEmployee.Rows[0]["F_PhoneNo"].ToString();
                txtLiveAddress.Text = dtEmployee.Rows[0]["L_Address"].ToString();
                txtLivePhone.Text = dtEmployee.Rows[0]["L_PhoneNo"].ToString();
                txtCellPhone1.Text = dtEmployee.Rows[0]["CellPhone"].ToString();
                txtCellPhone2.Text = dtEmployee.Rows[0]["CellPhone2"].ToString();
                txtEmail1.Text = dtEmployee.Rows[0]["EMail"].ToString();
                txtEmail2.Text = dtEmployee.Rows[0]["EMail2"].ToString();
                sDepartmentID = dtEmployee.Rows[0]["DeptID"].ToString().Trim();
                ddlJobTitle.SelectedValue = dtEmployee.Rows[0]["JobTitle"].ToString();
                ddlJobGrade.SelectedValue = dtEmployee.Rows[0]["Grade"].ToString();
                txtLeaveDate.Text = dtEmployee.Rows[0]["LeaveDate"].ToString();
                txtHireDate.Text = dtEmployee.Rows[0]["HireDate"].ToString();
                //TimeSpan ts1 = new TimeSpan(DateTime.Parse(txtHireDate.Text).Ticks);
                //TimeSpan ts2 = new TimeSpan(DateTime.Now.Ticks);
                //TimeSpan ts = ts1.Subtract(ts2).Duration();
                
                DateTime dFrom = DateTime.MinValue, dTo = DateTime.MinValue;
                if (txtHireDate.Text == "1990/1/1" || txtHireDate.Text == "")
                    lblSeniority.Text = "NA";
                else if (txtLeaveDate.Text != "") {
                    dFrom = DateTime.Parse(txtHireDate.Text);
                    dTo = DateTime.Parse(txtLeaveDate.Text);

                    lblSeniority.Text = (dTo.Year - dFrom.Year).ToString() + Resources.Universal.Comm_Year +
                        (dTo.Month - dFrom.Month).ToString() + Resources.Universal.Comm_Month;
                }
                else {
                    dFrom = DateTime.Parse(txtHireDate.Text);
                    dTo = DateTime.Today;

                    lblSeniority.Text = (dTo.Year - dFrom.Year).ToString() + Resources.Universal.Comm_Year +
                        (dTo.Month - dFrom.Month).ToString() + Resources.Universal.Comm_Month;
                }
                txtComment.Text = dtEmployee.Rows[0]["Comment"].ToString();

            }
            else {
                // 找不到資料
                lblTitle.Text = "No Data";
            }
        }
        else {
            lblTitle.Text = Resources.Universal.Data_AddNew;
        }
    }

    protected void ddlDepartment_DataBound(object sender, EventArgs e) { 
        DropDownList ddl = (DropDownList) sender;
        foreach (ListItem li in ddl.Items) {
            li.Text = li.Text.Substring(li.Value.IndexOf(" - ") + 3);
            li.Value = li.Value.Substring(0, li.Value.IndexOf(" - "));
            if ( li.Value == sDepartmentID)
                li.Selected = true;
        } 
    }

    protected void btnAddNew_Click(object sender, EventArgs e) {
        try {
            HR_EmployeesData emp = new HR_EmployeesData();
            emp.Insert(txtID.Text, txtName.Text, ddlSex.SelectedValue, ddlBlood.SelectedValue, txtIdentityNo.Text, txtPassportNo.Text,
                txtFirstName.Text, "", txtLastName.Text, txtSettleAddress.Text, txtSettlePhone.Text, txtLiveAddress.Text,
                txtLivePhone.Text, txtCellPhone1.Text, txtCellPhone2.Text, txtEmail1.Text, txtEmail2.Text, ddlDepartment.SelectedValue,
                ddlJobTitle.SelectedValue, ddlJobGrade.SelectedValue, "", txtHireDate.Text, txtLeaveDate.Text, txtComment.Text);
            emp = null;

        }
        catch (Exception ex) {
            Response.Redirect("/SEST/Common/ErrorPage.aspx?BackPageCount=-1&ErrorMessage=" + ex.Message.Replace("\r\n", "=>"));
        }
    }


    protected void btnUpdate_Click(object sender, EventArgs e) {
        try {
            HR_EmployeesData emp = new HR_EmployeesData();
            emp.Update(txtID.Text, txtName.Text, ddlSex.SelectedValue, ddlBlood.SelectedValue, txtIdentityNo.Text, txtPassportNo.Text,
                txtFirstName.Text, "", txtLastName.Text, txtSettleAddress.Text, txtSettlePhone.Text, txtLiveAddress.Text,
                txtLivePhone.Text, txtCellPhone1.Text, txtCellPhone2.Text, txtEmail1.Text, txtEmail2.Text, ddlDepartment.SelectedValue,
                ddlJobTitle.SelectedValue, ddlJobGrade.SelectedValue, "", txtHireDate.Text, txtLeaveDate.Text, txtComment.Text, sOriginalID);
            emp = null;

        }
        catch (Exception ex) {
            Response.Redirect("/SEST/Common/ErrorPage.aspx?BackPageCount=-1&ErrorMessage=" + ex.Message.Replace("\r\n", "=>"));
        }
    }


    protected void btnDelete_Click(object sender, EventArgs e) {
        new HR_EmployeesData().Delete(txtID.Text);

        // back
        Literal BackScript = new Literal();
        //string sTmpURL = Request.Url.ToString().Substring(0, Request.Url.ToString().IndexOf("?")); // 沒有參數
        //sTmpURL = sTmpURL.Substring(0, sTmpURL.LastIndexOf("/") + 1) + "Employee.aspx";
        //BackScript.Text = "<script>window.history.go('" + sTmpURL + "')</script>" + "<BR/>";
        BackScript.Text = "<script>window.history.go(-2)</script>" + "<BR/>";
        //BackScript.Text = "<script>document.location.replace('" + sTmpURL + "')</script>" + "<BR/>";
        Page.Controls.Add(BackScript);
    }
}

