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 TEC_Forms_WorkRecord : 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) {
        try {
            if (!IsPostBack) {
                // 依據 URL 中的屬性取得工單的內容
                if (Request["WorkID"] != null) {
                    txtWorkID.Text = Request["WorkID"].ToString();
                    DataTable dt = new TEC_MainWorksData().Select("WorkID='" + txtWorkID.Text.Replace("''", "").Replace("--", "") + "'", "WorkID");
                    if (dt.Rows.Count > 0) {
                        txtJobNo.Text = dt.Rows[0]["JobNo"].ToString();
                        txtFABID.Text = dt.Rows[0]["FABID"].ToString();
                        txtToolID.Text = dt.Rows[0]["SES_ToolNo"].ToString();
                        txtDescription.Text = dt.Rows[0]["Description"].ToString();
                    }
                    DataTable tbSchedule;
                    if (Request["ScheduleID"] != null) 
                        tbSchedule = new TEC_MainWorkSchedulesData().SelectByScheduleID(Request["ScheduleID"].ToString());
                    else
                        tbSchedule = new TEC_MainWorkSchedulesData().SelectByWorkID( txtWorkID.Text);

                    if ( tbSchedule.Rows.Count == 1){
                        txtResponsibility.Text = tbSchedule.Rows[0]["Responsibility"].ToString();
                        if (txtWorkStartDate.Visible == true)
                            txtWorkStartDate.Text = tbSchedule.Rows[0]["ExpectStartDate"].ToString();
                        if (txtWorkEndDate.Visible == true)
                            txtWorkEndDate.Text = tbSchedule.Rows[0]["ExpectEndDate"].ToString();
                    }

                    
                    btnSubmit.Visible = true;
                    btnUpdate.Visible = false;
                    btnNext.Visible = false;
                }
                else {
                    // hide 
                    trContents.Visible = false;    // record content
                    trResponsibility.Visible = false; // description
                    trDescription.Visible = false; // description
                    trAddFiles.Visible = false;    // attach files
                    

                    btnSubmit.Visible = false;
                    btnUpdate.Visible = false;
                    btnNext.Visible = true;
                }

                // 如果是 AJW , AJM, AZZ 要新增紀錄時會秀出施工時間, 待紀錄時會去判斷 schedule & whiteboard 是不是有該筆記錄
                // 如果沒有則新增
                string sJobNoHeader = "";
                if (txtJobNo.Text.Length >=3 )
                    sJobNoHeader = txtJobNo.Text.ToUpper().Substring(0, 3);
                if (Request["ShowDate"] != null && (sJobNoHeader == "AJW" || sJobNoHeader == "AJM" || sJobNoHeader == "AZZ")) {
                    trWorkDate.Visible = true;
                    //txtWorkStartDate.Text = DateTime.Today.ToString("yyyy/MM/dd");
                    //txtWorkEndDate.Text = DateTime.Today.ToString("yyyy/MM/dd");
                }
                else
                    trWorkDate.Visible = false;
            }
            lblTitle.Text = Resources.Universal.Msg_Title_WorkRcord + " (" + Resources.Universal.Data_AddNew + ")";
            btnAddNew.Visible = false;


            hlJobNo.Attributes.Add("onclick", "openSubJobNo('" + txtJobNo.ClientID + "','" + txtFABID.ClientID + "','','Unassigned')");
            hlJobNo.Attributes.Add("onmouseover", "this.style.cursor='hand'");

            // **** 工番可對應多個廠別
            //hlFABID.Attributes.Add("onclick", "openSubPageFABID('" + txtFABID.ClientID + "')");
            hlFABID.Attributes.Add("onclick", "txtFAB_onclick('" + txtFABID.ClientID + "','" + txtJobNo.ClientID + "')");//,'" + e.Row.FindControl("txtTools").ClientID + "')");
            hlFABID.Attributes.Add("onmouseover", "this.style.cursor='hand'");

            hlToolID.Attributes.Add("onclick", "openSubPageToolID('" + txtToolID.ClientID + "', " + txtFABID.ClientID + ",'False' )");
            hlToolID.Attributes.Add("onmouseover", "this.style.cursor='hand'");

            hlResponsibility.Attributes.Add("onclick", "openSubPageEmployee('" + txtResponsibility.ClientID + "')");
            hlResponsibility.Attributes.Add("style", "cursor: hand");

            txtJobNo.Attributes.Add("onchange", txtWorkID.ClientID + ".value=''");
            txtFABID.Attributes.Add("onchange", txtWorkID.ClientID + ".value=''");
            txtToolID.Attributes.Add("onchange", txtWorkID.ClientID + ".value=''");

            if (txtWorkStartDate.Visible == true && txtWorkEndDate.Visible) {
                btnNext.Attributes.Add("onclick", "return (checkExpectDate('" + txtWorkStartDate.ClientID + "','" + txtWorkEndDate.ClientID + "', true) && checkResponsibilityValue('" + txtResponsibility.ClientID + "')); ");
                btnSubmit.Attributes.Add("onclick", "return (checkExpectDate('" + txtWorkStartDate.ClientID + "','" + txtWorkEndDate.ClientID + "', true) && checkResponsibilityValue('" + txtResponsibility.ClientID + "')); ");
            }

            // 新增 file upload 的 component
            FileSaveToServer.Attributes.Add("onchange", "addFile2('" + tdMyFiles.ClientID + "'," + Convert.ToInt32(FileSaveToServer.Width.Value) + ")");

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


    protected void txtApplicant_PreRender(object sender, EventArgs e) {
        if (Profile.UserName.Length <= 15) {
            txtRecorder.Text = new HR_EmployeesData().getUserNameByAccount(Profile.UserName);
        }
    }

    protected void btnNext_Click(object sender, EventArgs e) {
        // 取得新增的值
        //string sWriter = txtRecorder.Text;
        //string sWorkID = txtWorkID.Text;
        string sJobNo = txtJobNo.Text;
        string sFABID = txtFABID.Text;
        string sToolID = txtToolID.Text;
        //string sContents = txtContents.Text;
        if (sJobNo == "" || sFABID == "" || sToolID == "")
            return;

        Response.Redirect("WorkRecordDetail.aspx?JobNo=" + sJobNo + "&FABID=" + sFABID + "&ToolID=" + sToolID);
    }



    protected void gvAttachFile_RowDataBound(object sender, GridViewRowEventArgs e) {
        // 資料庫只存 physical path ,所以需將其轉成 URL
        if (e.Row.FindControl("hyLink") != null) {
            ((HyperLink)e.Row.FindControl("hyLink")).NavigateUrl = ((HyperLink)e.Row.FindControl("hyLink")).NavigateUrl.Replace(
                            ConfigurationManager.ConnectionStrings["FilesStoragePath"].ConnectionString,
                            ConfigurationManager.ConnectionStrings["FilesStorageURL"].ConnectionString.Replace("60.251.203.79", Request.Url.DnsSafeHost)).Replace(@"\", @"/");
            ((HyperLink)e.Row.FindControl("hyLink")).NavigateUrl =
                ((HyperLink)e.Row.FindControl("hyLink")).NavigateUrl.Replace("60.251.203.79", Request.Url.DnsSafeHost);
        }
    }
    protected void gvAttachFile_RowDeleting(object sender, GridViewDeleteEventArgs e) {
        // 刪除檔案
        string sFile = ((HyperLink)gvAttachFile.Rows[e.RowIndex].FindControl("hyLink")).NavigateUrl.Replace(
                            ConfigurationManager.ConnectionStrings["FilesStorageURL"].ConnectionString.Replace("60.251.203.79", Request.Url.DnsSafeHost),
                            ConfigurationManager.ConnectionStrings["FilesStoragePath"].ConnectionString).Replace(@"/", @"\");
        System.IO.File.Delete(sFile);
    }


    protected void btnAddNew_Click(object sender, EventArgs e) {
        // 變更顯示元件
        btnSubmit.Visible = true;
        btnUpdate.Visible = false;
        gvAttachFile.Visible = false;
        btnAddNew.Visible = false;
        string sJobNoHeader = "";
        if (txtJobNo.Text.Length >= 3)
            sJobNoHeader = txtJobNo.Text.ToUpper().Substring(0, 3);
        if (Request["ShowDate"] != null && (sJobNoHeader == "AJW" || sJobNoHeader == "AJM" || sJobNoHeader == "AZZ")) {
            trWorkDate.Visible = true;
            trResponsibility.Visible = true;
        }


        // 新增時將內容清空
        txtContents.Text = "";
        GridView1.SelectedIndex = -1;

        // 更變 style
        string style= "border-right: #3399ff 3px solid;border-top: #3399ff 3px solid; border-left: #3399ff 3px solid; border-bottom: #3399ff 3px solid;background-color: #cbd2ff";
        tblForm.Attributes.Add("style", style);
        lblTitle.Text = Resources.Universal.Msg_Title_WorkRcord + " (" + Resources.Universal.Data_AddNew + ")";
    }
    protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) {
        // 變更顯示元件
        btnAddNew.Visible = true;
        btnSubmit.Visible = false;
        btnUpdate.Visible = true;
        gvAttachFile.Visible = true;
        trWorkDate.Visible = false;
        trResponsibility.Visible = false;

        // 更變 style
        string style= "border-right: #3399ff 3px solid;border-top: #3399ff 3px solid; border-left: #3399ff 3px solid; border-bottom: #3399ff 3px solid;background-color: #ffd2dc";
        tblForm.Attributes.Add("style", style);
        lblTitle.Text = Resources.Universal.Msg_Title_WorkRcord + " (" + Resources.Universal.Data_Update + ")";

        // 顯示內容值以供修改, 同時取得所附加的檔案
        string sWorkRecordID = GridView1.SelectedRow.Cells[1].Text.Trim();
        txtContents.Text = GridView1.SelectedRow.Cells[4].Text.Trim();

        ObjectDataSource2.SelectParameters["PageKeys"].DefaultValue = sWorkRecordID;
        gvAttachFile.DataBind();
    }




    protected void btnSubmit_Click(object sender, EventArgs e) {
        try {
            string sStartDate = "", sEndDate = "", sWorkID = "", sJobNo = "", sFABID = "", sToolID = "", sDescription = "", 
                sResponsibilities = "", sGroups = "", sError = "";
            // 判斷是不是有該筆的 schedule & whiteboard, 如果沒有的話則新增
            if (trWorkDate.Visible == true) {
                sStartDate = txtWorkStartDate.Text;
                sEndDate = txtWorkEndDate.Text;

                try {
                    DateTime.Parse(sStartDate);
                    DateTime.Parse(sEndDate);
                }
                catch {
                    Response.Redirect("/SEST/Common/ErrorPage.aspx?BackPageCount=-1&ErrorMessage=" + Resources.Universal.Err_DateFormatIncorrect);
                    return;
                }

                sWorkID = txtWorkID.Text;
                sJobNo = txtJobNo.Text;
                sFABID = txtFABID.Text;
                sToolID = txtToolID.Text;
                sDescription = txtDescription.Text;
                sResponsibilities = txtResponsibility.Text;

                if (sWorkID == "")
                    sError += "=>WorkID ?? ";
                if (sResponsibilities == "")
                    sError += "=>" + Resources.Universal.WorksList_Responsibility + " ?? ";
                if (sJobNo == "")
                    sError += "=>" + Resources.Universal.JobNo_ID + " ?? ";
                if (sFABID == "")
                    sError += "=>" + Resources.Universal.Comm_FABID + " ?? ";
                if (sToolID == "")
                    sError += "=>" + Resources.Universal.SES_ToolNo + " ?? ";

                // 有遺失資料
                if (sError != "") {
                    throw new Exception(sError);
                }


                // 取得負責人所對應的 Group
                sGroups = SES_Common.getMatchGroup(sResponsibilities);

                // 新增 schedule & add to whiteboard
                string sWhiteBoardContent = "[" + sWorkID + "] => " + sJobNo + "_" + sFABID + "_" + sToolID + " : " +
                        sDescription + "(" + sResponsibilities.Replace("\r\n", ",") + ")";
                try { // 重覆的時間內不執行底下的動作
                    SES_Common.saveScheduleAndWhiteBoard2(sWorkID, sStartDate, sEndDate, sResponsibilities, sGroups, sWhiteBoardContent);
                }
                catch { }
            }


            // 新增至工作記錄
            InsertOrUpdate("Insert");

            // 往前移一頁(避免重新整理時再執行一次)再重新載入
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Back", SES_Common.BackScript(Request.Url.ToString(), -1));
        }
        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 {
            InsertOrUpdate("Update");

            // 往前移一頁(避免重新整理時再執行一次)再重新載入
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Back", SES_Common.BackScript(Request.Url.ToString(), -1));
        }
        catch (Exception ex) {
            Response.Redirect("/SEST/Common/ErrorPage.aspx?BackPageCount=-1&ErrorMessage=" + ex.Message.Replace("\r\n", "=>"));
        }
    }
    void InsertOrUpdate(string ModifyType) {
        string sWriter = "", sWorkID = "", sJobNo = "", sFABID = "", sToolID = "", sContents = "", sError = "";
        DateTime dtNow = DateTime.Now;

        // 取得值
        sWriter = txtRecorder.Text;
        sWorkID = txtWorkID.Text;
        sJobNo = txtJobNo.Text;
        sFABID = txtFABID.Text;
        sToolID = txtToolID.Text;
        sContents = txtContents.Text;

        if (sWorkID != "") {
            if (sJobNo == "")
                sError += "=>" + Resources.Universal.JobNo_ID + " ?? ";
            if (sFABID == "")
                sError += "=>" + Resources.Universal.Comm_FABID + " ?? ";
            if (sToolID == "")
                sError += "=>" + Resources.Universal.SES_ToolNo + " ?? ";
            if (sContents == "")
                sError += "=>" + Resources.Universal.Comm_Contents + " ?? ";

            // 有遺失資料
            if (sError != "") {
                throw new Exception(sError);
            }


            // 新增或更新 WorkRecord table
            string sWorkRecordID = "";
            if (ModifyType == "Insert")
                sWorkRecordID = (new TEC_WorkRecordData().Insert(sWorkID, dtNow.ToString("yyyy/MM/dd HH:mm:ss"), sWriter, sContents)).ToString();
            else if (ModifyType == "Update") {
                sWorkRecordID = GridView1.SelectedRow.Cells[1].Text.Trim();
                new TEC_WorkRecordData().Update(sWorkID, dtNow.ToString("yyyy/MM/dd HH:mm:ss"), sWriter, sContents, sWorkRecordID);
            }
            else
                return;


            // 1.儲存檔案至 SERVER, 2.儲存路徑至資料庫 ( <<<<< 實際儲存位置 >>>>> )
            HttpFileCollection uploadedFiles = Request.Files;
            string sTemp = "", sSingleFilePath = "", sFileName = "";
            Common_FilesStorageData file = new Common_FilesStorageData();
            for (int i = 0; i < uploadedFiles.Count; i++) {
                HttpPostedFile userPostedFile = uploadedFiles[i];
                if (userPostedFile.ContentLength > 0) {
                    sTemp = Root.Text.pcString.AddBackSlash(System.Configuration.ConfigurationManager.ConnectionStrings["FilesStoragePath"].ConnectionString);
                    sTemp = Root.Storage.pcDirFile.CreateFolderByDate(sTemp, System.DateTime.Today, Root.Storage.pcDirFile.CreateFolderType.Cascade, Root.Storage.pcDirFile.CreateDateBase.Day, false);
                    // file name
                    sFileName = System.IO.Path.GetFileName(userPostedFile.FileName);
                    sSingleFilePath = System.IO.Path.Combine(sTemp + sFileName);

                    if (sSingleFilePath != "") {
                        // 1.儲存檔案至 SERVER (同檔名會覆蓋)
                        userPostedFile.SaveAs(sSingleFilePath);//filepath + "\\" + System.IO.Path.GetFileName(userPostedFile.FileName));
                        // 2.儲存路徑至資料庫 (先刪除再儲存)
                        file.Delete("WorkRecord", sWorkRecordID, sFileName);
                        file.Insert("WorkRecord", sWorkRecordID, sFileName, sSingleFilePath, "", "");
                    }
                }
            }

            // update MainWork
            new TEC_MainWorksData().UpdateWorkRecord(sContents, dtNow, sWorkID);

            ObjectDataSource2.SelectParameters["PageKeys"].DefaultValue = sWorkRecordID;
            GridView1.DataBind();
            gvAttachFile.DataBind();
            Response.Clear();

        }
        else {
            throw new Exception("Miss WorkID");
        }
    }
    protected void GridView1_DataBound(object sender, EventArgs e) {
        GridView gv = (GridView) sender;
        int iColIdx = -1;
        string sUserName = new HR_EmployeesData().getUserNameByAccount(Profile.UserName);

        for (int i = 0; i < gv.Columns.Count; i++) {
            if (gv.Columns[i].HeaderText == Resources.Universal.Msg_Writer) { 
                iColIdx = i;
                break;
            }
        }
        if (iColIdx > -1) {
            for (int i = 0; i < gv.Rows.Count; i++) {
                if (gv.Rows[i].Cells[iColIdx].Text != sUserName) {
                    ((LinkButton)gv.Rows[i].Cells[0].Controls[0]).Enabled = false;
                }
            }
        }
    }
}
