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;
using System.Web.Mail;
//using System.Net.Mail;


public partial class Maintenance_TEC_WorksListDetail : 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");
        }
    }



    private string sWorkID = "";
    protected void Page_PreRender(object sender, EventArgs e) {

        string sDefaultSelected = "Processing";
        if (!IsPostBack) {
            //Status 的設定
            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());
                }

                ddlStatus.Items.Add(li);
            }
        }


        if (Request["WorkID"] != null)
            sWorkID = Request["WorkID"].ToString();
        else
            tblAdditional.Visible = false;

        // 不同的呼叫來源
        if (sWorkID != "") { // 修改
            lblTitle.Text = "Work List Detail ( Edit )";

            // ----- 取得工作記錄的子項目, 同時有附加檔案時顯示超連結在 textbox 底下
            DataTable dt = new TEC_WorkRecordData().Select("WorkID='" + sWorkID + "'");
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            string sWorkRecordID = "";
            foreach (DataRow dr in dt.Rows) {
                // index 0 -> WorkID, index 1 -> DateTime, index 2 -> journalist, index 3 -> record text, index 4 -> attach file
                sb.AppendFormat("{0}({1}) >> {2}\r\n", Convert.ToDateTime(dr["RecordDateTime"]).ToString("yyMMddHHmm"), dr["Journalist"].ToString(), dr["Action"].ToString());
                sWorkRecordID += "," + dr["WorkRecordID"].ToString();
            }
            this.txtActionRecords.Text = sb.ToString();
            if (sWorkRecordID != "") {
                HyperLink hl;
                string sURL = "";
                
                sWorkRecordID = "'" + sWorkRecordID.Substring(1).Replace(",","','") + "'";
                dt = new Common_FilesStorageData().SelectMultiKeys("WorkRecord", sWorkRecordID);
                foreach (DataRow dr in dt.Rows) {
                    hl = new HyperLink();
                    hl.ImageUrl = @"~\imanges\attachfile.gif";
                    hl.Target = "_blank";
                    //sURL = dr["PhysicalPath"].ToString().Replace(
                    //    ConfigurationManager.ConnectionStrings["FilesStoragePath"].ConnectionString,
                    //    ConfigurationManager.ConnectionStrings["FilesStorageURL"].ConnectionString).Replace(@"\", "/");
                    sURL = dr["PhysicalPath"].ToString().Replace(@"\", "/");
                    sURL = sURL.Substring(sURL.IndexOf("SES-T_FilesStorage"));
                    sURL = sURL.Replace("SES-T_FilesStorage", @"http://" + Request.Url.DnsSafeHost + @"/Storage");

                    hl.NavigateUrl = sURL;
                    hl.ToolTip = sURL.Substring(sURL.LastIndexOf("/") + 1);      // 將日期顯示在 ToolTip
                    // 將附加檔案的超連結加入至 panel 控制項裡
                    this.pnlRecordFiles.Controls.Add(hl);
                    this.pnlRecordFiles.Visible = true;
                }
            }
            // ----- 

            // ----- 取得工作記錄的資料
            dt = new TEC_MainWorksData().Select("WorkID='" + sWorkID.Replace("''", "").Replace("--", "") + "'", "");
            if (dt.Rows.Count > 0) {
                lblWorkID.Text = dt.Rows[0]["WorkID"].ToString();

                this.txtJobNo.Text = dt.Rows[0]["JobNo"].ToString();
                this.txtCreateDate.Text = Convert.ToDateTime(dt.Rows[0]["CreateDate"]).ToString("yyyy/MM/dd HH:mm:ss");
                this.txtCreateFrom.Text = dt.Rows[0]["CreateFrom"].ToString();
                this.txtProposer.Text = dt.Rows[0]["Proposer"].ToString();
                this.txtFABID.Text = dt.Rows[0]["FABID"].ToString();
                this.txtSESToolNo.Text = dt.Rows[0]["SES_ToolNo"].ToString();
                this.txtDescription.Text = dt.Rows[0]["Description"].ToString();
                this.txtRootCause.Text = dt.Rows[0]["RootCause"].ToString();
                string sStatusValue = dt.Rows[0]["Status"].ToString();
                for (int iStatus = 0 ; iStatus < ddlStatus.Items.Count; iStatus++){
                    if (ddlStatus.Items[iStatus].Value == sStatusValue) { 
                        ddlStatus.Items[iStatus].Selected = true;
                        break;
                    }
                }
                if (sStatusValue == "Discard" && (Request.Url.ToString().ToUpper().IndexOf("SEST/MAINTENANCE/") >= 0))
                    btnDelete.Visible = true;
                else
                    btnDelete.Visible = false;

                //this.ddlStatus.SelectedIndex = this.ddlStatus.Items.IndexOf(new ListItem(dt.Rows[0]["Status"].ToString()));
                this.txtFinishDate.Text = dt.Rows[0]["FinishDate"].ToString();
                this.txtDeliveryReportDate.Text = dt.Rows[0]["DeliveryReportDate"].ToString();
                this.txtTroubleNo.Text = dt.Rows[0]["TroubleNo"].ToString();
                this.txtComment.Text = dt.Rows[0]["Comment"].ToString();
            }
            else
                Response.Redirect("/SEST/Common/ErrorPage.aspx?BackPageCount=-1&ErrorMessage=" + Resources.Universal.Msg_MissData);
            // ----- 
        }
        else { //新增
            lblTitle.Text = "Work List Detail ( Add New )";

            txtCreateDate.Text = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss");
            txtCreateFrom.Text = "meeting";
            txtProposer.Text = new HR_EmployeesData().getUserNameByAccount(Profile.UserName);
            lblProposer.Enabled = false; txtProposer.Enabled = false;
            ddlStatus.SelectedIndex = ddlStatus.Items.IndexOf(new ListItem("Processing"));

            //btnInsert.Visible = true;
            lblActionRecords.Enabled = true;
            txtActionRecords.Enabled = true;
        }



        if (!IsPostBack) {
            if (txtDate.Text == "")
                txtDate.Text = DateTime.Today.ToString("yyyy/MM");

            // 來自管理的路徑
            if (Request.Url.ToString().ToUpper().IndexOf("SEST/MAINTENANCE/") >= 0) {
                Page.Title = Resources.SiteMapLocalizations.TEC_WorkListDetail;


                btnUpdateSchedule.Visible = true;
            }
            else { // 不是來自管理的路徑 (功能 hidden)
                Page.Title = Resources.SiteMapLocalizations.Maintenance_WorkListEditDetail;

                gvAttachFile.Columns.RemoveAt(0); // 不能刪除
                gvAttachFile.Columns[0].Visible = false;
                ////btnUpdate.Visible = false; (可以更新 Comment)

                lblJobNo.Enabled = false; txtJobNo.Enabled = false;
                lblProposer.Enabled = false; txtProposer.Enabled = false;
                lblFABID.Enabled = false; txtFABID.Enabled = false;
                lblToolID.Enabled = false; txtSESToolNo.Enabled = false;
                lblDescription.Enabled = false; //txtDescription.Enabled = false;
                lblRootCause.Enabled = false; //txtRootCause.Enabled = false;
                lblStatus.Enabled = false; ddlStatus.Enabled = false;
                lblFinishDate.Enabled = false; txtFinishDate.Enabled = false;
                lblAttachFiles.Enabled = false; FileSaveToServer.Enabled = false;
                lblDeliveryReportDate.Enabled = false; txtDeliveryReportDate.Enabled = false;
                lblTroubleNo.Enabled = false; txtTroubleNo.Enabled = false;
                
                // focus Comment (only to modify)
                lblComment.Font.Bold = true; lblComment.ForeColor = System.Drawing.Color.Red;
                lblComment.Focus();

                tdAddAttachFilesForm.Visible = false;
                tdAddAttachFilesButton.Visible = false;
                btnUpdateSchedule.Visible = false;
            }
        }
        if (sWorkID != "") // 不是新增
            showResponsibilityTable("Manager", "DB");


        // Set the attribut to open sub page 
        hlJobNo.Attributes.Add("onclick", "openSubJobNo('" + txtJobNo.ClientID + "','" + txtFABID.ClientID + "','" + txtDescription.ClientID + "','Unassigned')"); 
        hlJobNo.Attributes.Add("style", "cursor: hand");
        hlFABID.Attributes.Add("onclick", "openSubPageFABID('" + txtFABID.ClientID + "'," + txtFABID.ClientID + "," + txtJobNo.ClientID + ")");
        hlFABID.Attributes.Add("style", "cursor: hand");
        hlSES_ToolNo.Attributes.Add("onclick", "openSubPageToolIDFromWorkListDetail('" + txtSESToolNo.ClientID + "'," + txtFABID.ClientID + "," + txtJobNo.ClientID + ")");
        hlSES_ToolNo.Attributes.Add("style", "cursor: hand");
        ////hlGroupID.Attributes.Add("onclick", "openSubPageEmployee('" + txtGroupID.ClientID + "')");
        ////hlGroupID.Attributes.Add("style", "cursor: hand");
        //hlResponsibility.Attributes.Add("onclick", "openSubPageEmployee('" + txtResponsibility.ClientID + "')");
        //hlResponsibility.Attributes.Add("style", "cursor: hand");

        //hlExpectStartDate.Attributes.Add("onclick", "openSubPageCalendar('" + txtExpectStartDate.ClientID + "')");
        //hlExpectStartDate.Attributes.Add("style", "cursor: hand");
        //hlExpectEndDate.Attributes.Add("onclick", "openSubPageCalendar('" + txtExpectEndDate.ClientID + "')");
        //hlExpectEndDate.Attributes.Add("style", "cursor: hand");
        hlFinishDate.Attributes.Add("onclick", "openSubPageCalendar('" + txtFinishDate.ClientID + "')");
        hlFinishDate.Attributes.Add("style", "cursor: hand");
        hlDeliveryReportDate.Attributes.Add("onclick", "openSubPageCalendar('" + txtDeliveryReportDate.ClientID + "')");
        hlDeliveryReportDate.Attributes.Add("style", "cursor: hand");

        //txtExpectStartDate.Attributes.Add("onclick","getCalendarFor(document.form1." + txtExpectStartDate.ClientID + ")");

        //// 判斷 Expect date
        //btnAddSchedule.Attributes.Add("onclick", "return checkExpectDate('" + txtExpectStartDate.ClientID + "','" + txtExpectEndDate.ClientID + "', false)");
        //btnInsert.Attributes.Add("onclick", "return checkExpectDate('" + txtExpectStartDate.ClientID + "','" + txtExpectEndDate.ClientID + "', false)");

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


        this.Page.Form.DefaultFocus = txtDate.ClientID;
        this.Page.Form.DefaultButton = btnSearch.ClientID;
        btnSearch.Focus();
    }
    void showResponsibilityTable(string Type, string ValueSource) {
        //Show history data by month
        string[] arHistory = new TEC_MainWorkSchedulesData().SelectHistoryDataByMonth(sWorkID);
        Button btnHis;
        pnlHistoryData.Controls.Clear();
        if (arHistory != null) {
            foreach (string s in arHistory) {
                btnHis = new Button();
                btnHis.Text = s;
                btnHis.OnClientClick = "javascript: " + txtDate.ClientID + ".value='" + s + "';";
                btnHis.Click += new EventHandler(btnSearch_Click);
                pnlHistoryData.Controls.Add(btnHis);
            }
        }

        // remove rows of table
        for (int i = tblContents.Rows.Count - 1; i >= 0; i--) {
            tblContents.Rows[i].Controls.Clear();
            tblContents.Rows.RemoveAt(i);
        }
        

        // show table
        TableRow tr = new TableRow();
        tr.Cells.Add(getCell("", "background:#EEEEEE"));
        int iMaxDayOfMonth = 0;
        try{
            iMaxDayOfMonth = Convert.ToDateTime(txtDate.Text + "/01").AddMonths(1).AddDays(-1).Day;
        }
        catch{ return;}
        // get first sumday this month
        int WeekOfFirstDay = (int)Convert.ToDateTime(txtDate.Text + "/01").DayOfWeek;

        //The date row of top
        for (int i=1; i<= iMaxDayOfMonth; i++){
            tr.Cells.Add(getCell(i.ToString("00"), "background:#88CAFF; HEIGHT: 8px; FONT-SIZE: 10pt; color: #3030AA"));
        }
        tblContents.Rows.Add(tr);

        DataTable dtEmp = new HR_EmployeesData().SelectDutyFormEmployeeExcludeLeave(sWorkID, Convert.ToDateTime(txtDate.Text + "/01"));
        TableCell cell;
        string sColor;
        CheckBox chk;
        string[] arGroupingColor = { "#BBEECC", "#AADDFE", "#DDDDCC", "#DDC866", "#CC99FF", "#FFDEAD", "#40E0D0", "#F0FFF0",
        "#BBEECC", "#AADDFE", "#DDDDCC", "#DDC866", "#CC99FF", "#FFDEAD", "#40E0D0", "#F0FFF0"};
        string sTempGrouping = "";
        int iGroupIndex = -1;
        for (int i = 0; i < dtEmp.Rows.Count; i++) {
            //if (i%2 == 0)
            //    sColor = "#ffcc66";
            //else
            //    sColor = "#ff99cc";
            if (dtEmp.Rows[i]["Grouping"].ToString().Trim() != sTempGrouping) {
                iGroupIndex++;
                sTempGrouping = dtEmp.Rows[i]["Grouping"].ToString().Trim();
            }
            if (iGroupIndex < 0 || iGroupIndex >= arGroupingColor.Length)
                sColor = "#F6F6F6";
            else
                sColor = arGroupingColor[iGroupIndex];


            tr = new TableRow();
            tr.Cells.Add(getCell(dtEmp.Rows[i]["Name"].ToString(), "background:" + sColor + ";HEIGHT: 8px; FONT-SIZE: 10pt; color: #3030AA"));
            for (int j = 1; j <= iMaxDayOfMonth; j++) {
                if ((j % 7) == ((7 - WeekOfFirstDay + 1) % 7)) {
                    cell = getCell("", "HEIGHT: 8px; FONT-SIZE: 10pt");
                    cell.BackColor = System.Drawing.Color.FromName("#f8a853");
                }
                else {
                    cell = getCell("", "HEIGHT: 8px; FONT-SIZE: 10pt");
                    cell.BackColor = System.Drawing.Color.FromName(sColor);
                }
                chk = new CheckBox();
                chk.ID = "chkDuty" + (i+1).ToString("00") + j.ToString("00");

                cell.Controls.Add(chk);
                cell.EnableViewState = false;
                tr.Cells.Add( cell );
            }

            tblContents.Rows.Add(tr);
        }

        //The date row of bottom
        tr = new TableRow();
        tr.Cells.Add(getCell("", "background:#EEEEEE")); 
        for (int i = 1; i <= iMaxDayOfMonth; i++) {
            tr.Cells.Add(getCell(i.ToString("00"), "background:#88CAFF; HEIGHT: 8px; FONT-SIZE: 10pt; color: #3030AA"));
        }
        tblContents.Rows.Add(tr);

        ViewState["TableRows"] = dtEmp.Rows.Count;
        ViewState["TableColumns"] = iMaxDayOfMonth;


        //assign value to check box
        if (ValueSource == "DB") {
            DataTable dtSchedule = new TEC_MainWorkSchedulesData().SelectByWorkID(sWorkID);
            int iDay = 0;
            string[] arResponsibility;
            string sResponsibility;
            for (int i = 0; i < dtSchedule.Rows.Count; i++) {
                if ((Convert.ToDateTime(dtSchedule.Rows[i]["ExpectStartDate"]).Year != Convert.ToDateTime(txtDate.Text).Year) ||
                    (Convert.ToDateTime(dtSchedule.Rows[i]["ExpectStartDate"]).Month != Convert.ToDateTime(txtDate.Text).Month))
                    continue;   // 判斷日期
                iDay = Convert.ToDateTime(dtSchedule.Rows[i]["ExpectStartDate"]).Day;   //column
                arResponsibility = dtSchedule.Rows[i]["Responsibility"].ToString().Replace("\r", "").Split("\n".ToCharArray());
                for (int j = 0; j < arResponsibility.Length; j++) {
                    sResponsibility = arResponsibility[j];
                    for (int z = 1; z < tblContents.Rows.Count; z++) {
                        if (tblContents.Rows[z].Cells[0].Text == sResponsibility) {
                            ((CheckBox)tblContents.Rows[z].Cells[iDay].FindControl("chkDuty" + z.ToString("00") + iDay.ToString("00"))).Checked = true;
                            tblContents.Rows[z].Cells[iDay].BackColor = System.Drawing.Color.Fuchsia;
                            //continue;
                        }
                    }
                }
            }
        }
        else if (ValueSource == "WEBFORM") {
            for (int i = 0; i < Request.Params.Count; i++) {
                if (Request.Params.AllKeys[i].IndexOf("chkDuty") >= 0) {
                    int iRowIndex = int.Parse(Request.Params.AllKeys[i].Substring(7, 2));
                    int iCellIndex = int.Parse(Request.Params.AllKeys[i].Substring(9, 2));
                    ((CheckBox)tblContents.Rows[iRowIndex].Cells[iCellIndex].FindControl(
                        "chkDuty" + iRowIndex.ToString("00") + iCellIndex.ToString("00"))).Checked = true;
                    tblContents.Rows[iRowIndex].Cells[iCellIndex].BackColor = System.Drawing.Color.Red;
                }
            }
        }

    }
    TableCell getCell(string innerText, string Style) {
        TableCell htc = new TableCell();

        if (innerText == "")
            htc.Text = "";
        else
            htc.Text = innerText;


        htc.Attributes.Add("style", Style);

        return htc;
    }



    protected void btnInsert_Click(object sender, EventArgs e) {
        //string sWorkID = InsertOrUpdateClick("Insert", "");

        //Response.Redirect("WorksListDetail.aspx?WorkID=" + sWorkID);

        //Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Back", SES_Common.BackScript(Request.Url.ToString(), -1));
    }
    protected void btnUpdate_Click(object sender, EventArgs e) {
        string sWorkID = "";
        try {
            if (Request["WorkID"] != null) {
                sWorkID = Request["WorkID"].ToString();
                InsertOrUpdateClick("Update", Request["WorkID"].ToString());
            }
            else {
                sWorkID = InsertOrUpdateClick("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", "=>"));
        }

        // 往前移一頁(避免重新整理時再執行一次)再重新載入
        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Back", SES_Common.BackScript(Request.Url.ToString(), -2));
        Response.Redirect("WorksListDetail.aspx?WorkID=" + sWorkID);
    }
    protected void btnDelete_Click(object sender, EventArgs e) {
        try {
            if (sWorkID == "" && Request["WorkID"] != null) {
                sWorkID = Request["WorkID"].ToString();
            }

            if (sWorkID != "") {
                // 刪除工單的 schedule
                new TEC_MainWorkSchedulesData().DeleteByWorkID(sWorkID);

                // 刪除白版上的資料
                new TEC_WhiteBoardData().DeleteByWorkID(sWorkID);

                // 刪除工作紀錄
                new TEC_WorkRecordData().DeleteByWorkID(sWorkID);

                // 刪除工單
                new TEC_MainWorksData().Delete(sWorkID);
            }
            else {
                Response.Redirect("/SEST/Common/ErrorPage.aspx?BackPageCount=-2&ErrorMessage=Miss WorkID");
            }
        }
        catch (Exception ex) {
            Response.Redirect("/SEST/Common/ErrorPage.aspx?BackPageCount=-2&ErrorMessage=" + ex.Message.Replace("\r\n", "=>"));
        }

        // 往前移一頁(避免重新整理時再執行一次)再重新載入
        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Back", SES_Common.BackScript(Request.Url.ToString(), -1));
        Response.Redirect("WorksList.aspx");
    }

    protected string InsertOrUpdateClick(string Type, string WorkID) {
        string sJobNo = "", sFABs = "", sTools = "", sDescription = "", sRootCause = "",
        sGroups = "", sResponsibilities = "", sExpectStartDate = "", sExpectEndDate = "", sStatus = "", sFinishedDate = "",
        sDeliveryReportDate = "", sTroubleNo = "", sFilePath = "", sComment = "";

        // ----------------- Top of 取得資料和附加檔案 -------------------------------
        // ========= 由 javascript 所產生的值無法直接由 aspnet 的 code取得
        if (Request[txtJobNo.ClientID] != null)
            sJobNo = Request[txtJobNo.ClientID].ToString();
        if (Request[txtSESToolNo.ClientID] != null)
            sTools = Request[txtSESToolNo.ClientID].ToString();
        // 取得機台所對應的 FABs
        string[] arTempTools = null, arTempFABs = null;
        string sTempTools = "", sTempCondition = "";
        if (sTools != "") {
            arTempTools = sTools.Replace("\r","").Split("\n".ToCharArray());
            for (int i = 0; i < arTempTools.Length; i++) {
                if (arTempTools[i].Trim() != "")
                    sTempTools += ",'" + arTempTools[i].Trim() + "'";
            }

            if (sTempTools != "") {
                sTempCondition = "SES_ToolNo in (" + sTempTools.Substring(1) + ")";
                arTempFABs = new TEC_ToolsData().SelectDistinct("FABID", sTempCondition);
                for (int i = 0; i < arTempFABs.Length; i++) {
                    sFABs += "\r\n" + arTempFABs[i];
                }
                if (sFABs != "")
                    sFABs = sFABs.Substring(2);
            }
        }
        if (Request[txtFABID.ClientID] != null) { 
            if (Request[txtFABID.ClientID].ToString() != sFABs)
                throw new Exception("mismatch FABID and ToolID");
        }
            
        if (Request[txtDescription.ClientID] != null)
            sDescription = Request[txtDescription.ClientID].ToString();
        if (Request[txtRootCause.ClientID] != null)
            sRootCause = Request[txtRootCause.ClientID].ToString();
        //if (Request[txtResponsibility.ClientID] != null)
        //    sResponsibilities = Request[txtResponsibility.ClientID].ToString();
        if (Request[ddlStatus.ClientID] != null)
            sStatus = Request[ddlStatus.ClientID].ToString();
        if (Request[txtFinishDate.ClientID] != null)
            sFinishedDate = Request[txtFinishDate.ClientID].ToString();
        if (Request[txtDeliveryReportDate.ClientID] != null)
            sDeliveryReportDate = Request[txtDeliveryReportDate.ClientID].ToString();
        if (Request[txtTroubleNo.ClientID] != null)
            sTroubleNo = Request[txtTroubleNo.ClientID].ToString();
        

        if (Request[txtComment.ClientID] != null)
            sComment = Request[txtComment.ClientID].ToString();
        // ----------------- Bottom of 取得資料和附加檔案 -------------------------------


        // ----------------- Top Of 儲存資料 --------------------------------------------
        int iErr = 0;
        try {
            sResponsibilities = sResponsibilities.Replace(" \r\n",""); // 取消空項目

            // ---------------Top 先處理附加檔案再處理實際的檔案 ------------------------
            
            // ---------------Bottom 先處理附加檔案再處理實際的檔案 ------------------------


            // 新增
            iErr++;
            if (Type == "Insert")
                WorkID = (new TEC_MainWorksData().Insert(sJobNo, txtCreateDate.Text, txtCreateFrom.Text, txtProposer.Text, sFABs, sTools,
                    sDescription, sRootCause, sStatus, sFinishedDate == "" ? null : sFinishedDate, 
                    sDeliveryReportDate == "" ? null : sDeliveryReportDate, sTroubleNo, sComment)).ToString();
            // 更新
            iErr++;
            if (Type == "Update") {
                if (Request.Url.ToString().ToUpper().IndexOf("SEST/MAINTENANCE/") >= 0) // 來自管理路徑
                    new TEC_MainWorksData().Update(sJobNo, txtCreateDate.Text, txtCreateFrom.Text, txtProposer.Text, sFABs, sTools,
                        sDescription, sRootCause, sStatus, sFinishedDate == "" ? null : sFinishedDate, 
                        sDeliveryReportDate == "" ? null : sDeliveryReportDate, sTroubleNo, sComment, WorkID);
                else    // 非來自管理路徑 (只能更新 Comment)
                    new TEC_MainWorksData().UpdateCommentOnly(sComment, WorkID);
            }

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

        return WorkID;
    }


    protected void btnFinish_Click(object sender, EventArgs e) {
        new TEC_MainWorksData().UpdateComplete( DateTime.Now, lblWorkID.Text);

        string sType = "";
        if (Request["Type"] != null)
            sType = Request["Type"].ToString();
        else
            return;

        // 往前移一頁(避免重新整理時再執行一次)再重新載入
        //Page_Load(this, new EventArgs());
        string sScript = "";
        sScript = "<script language='javascript' type='text/javascript'>\r\n";
        sScript += "window.history.back();";
        sScript += "</script>\r\n";
        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Back", sScript);
        Response.Redirect("WorksListDetail.aspx?WorkID=" + Request["Workid"].ToString() + "&Type=" + sType);
    }


    protected void btnAddSchedule_Click(object sender, EventArgs e) {
        string sWorkID = "", sResponsibilities = "", sGroups = "", sExpectStartDate = "", sExpectEndDate = "";
        string sJobNo = "", sFABs = "", sTools = "", sDescription = "";   // for white board content

        try {
            if (Request[txtJobNo.ClientID] != null)
                sJobNo = Request[txtJobNo.ClientID].ToString();
            if (Request[txtSESToolNo.ClientID] != null)
                sTools = Request[txtSESToolNo.ClientID].ToString();
            // 取得機台所對應的 FABs
            string[] arTempTools = null, arTempFABs = null;
            string sTempTools = "", sTempCondition = "";
            if (sTools != "") {
                arTempTools = sTools.Replace("\r", "").Split("\n".ToCharArray());
                for (int i = 0; i < arTempTools.Length; i++) {
                    if (arTempTools[i].Trim() != "")
                        sTempTools += ",'" + arTempTools[i].Trim() + "'";
                }

                if (sTempTools != "") {
                    sTempCondition = "SES_ToolNo in (" + sTempTools.Substring(1) + ")";
                    arTempFABs = new TEC_ToolsData().SelectDistinct("FABID", sTempCondition);
                    for (int i = 0; i < arTempFABs.Length; i++) {
                        sFABs += "\r\n" + arTempFABs[i];
                    }
                    if (sFABs != "")
                        sFABs = sFABs.Substring(2);
                }
            }
            if (Request[txtDescription.ClientID] != null)
                sDescription = Request[txtDescription.ClientID].ToString();
            //if (Request[txtResponsibility.ClientID] != null)
            //    sResponsibilities = Request[txtResponsibility.ClientID].ToString();
            // 取得負責人所對應的 Group
            sGroups = SES_Common.getMatchGroup(sResponsibilities);

            //if (Request[txtExpectStartDate.ClientID] != null)
            //    sExpectStartDate = Request[txtExpectStartDate.ClientID].ToString();
            //if (Request[txtExpectEndDate.ClientID] != null)
            //    sExpectEndDate = Request[txtExpectEndDate.ClientID].ToString();

            if (Request["WorkID"] != null) {
                // ----------------- Top:更新表單的 Schedule -------------------------------------------
                sWorkID = Request["WorkID"].ToString();
                // ----------------- Bottom:更新表單的 Schedule -------------------------------------------
            }
            else {
                // ----------------- Top:新建表單時的 Schedule -------------------------------------------
                sWorkID = InsertOrUpdateClick("Insert", "");
                // ----------------- Bottom:新建表單時的 Schedule -------------------------------------------
            }
            if (sWorkID == "") {
                Response.Redirect("/SEST/Common/ErrorPage.aspx?BackPageCount=-1&Unknow WorkID");
                return;
            }

            // JobNo or FAB or Tool can not assign empty
            if (sJobNo == "" || sFABs == "" || sTools == "")
                throw new Exception("JobNo or FAB or Tool is empty");


            // [176] => AZZ00200_UMC8E-E_O-2216 : ARM Safty Wire Detect時動作變更改造工事 (賴皇佑 林志偉 邱建瀚 馬仲威)
            string sWhiteBoardContent = "[" + sWorkID + "] => " + sJobNo + "_" + sFABs + "_" + sTools + " : " +
                    sDescription + "(" + sResponsibilities.Replace("\r\n", ",") + ")";
            // 儲存至 MainWorkSchedule and WhiteBoard
            SES_Common.saveScheduleAndWhiteBoard(sWorkID, sExpectStartDate, sExpectEndDate, sResponsibilities, sGroups, sWhiteBoardContent);

            
            if (Request["WorkID"] == null) {
                // 如果是新增,則往前移二頁再導至有 WorkID 引數的網址
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Back", SES_Common.BackScript(- 2));
            }
            else {
                // 往前移一頁(避免重新整理時再執行一次)再重新載入
                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", "=>"));
            return;
        }

        ////Send mail to responsibility
        //if (chkSendMail.Checked) {
        //    SendMail(sWorkID, sJobNo, sFABs, sTools, sDescription, sResponsibilities, sExpectStartDate, sExpectEndDate, "Add");
        //}

        // <<<<<<< 無法放在 try 裡面 >>>>>>>
        Response.Redirect("WorksListDetail.aspx?WorkID=" + sWorkID);
    }
    protected void gvSchedule_RowDeleting(object sender, GridViewDeleteEventArgs e) {
        // 刪除白板的內容
        string sWorkID = e.Values[0].ToString();
        string sExpectStartDate = e.Values[1] == null ? "" : e.Values[1].ToString();
        string sExpectEndDate = e.Values[2] == null ? "" : e.Values[2].ToString();
        DateTime dtStart = DateTime.MaxValue;
        DateTime dtEnd = DateTime.MinValue;
        if (sExpectStartDate != "" && sExpectEndDate != "") {
            dtStart = DateTime.Parse(sExpectStartDate);
            dtEnd = DateTime.Parse(sExpectEndDate);
            DateTime dtCurrentProcess = dtStart;
            TEC_WhiteBoardData whiteboard = new TEC_WhiteBoardData();
            while (dtCurrentProcess <= dtEnd) {
                int iYear = dtCurrentProcess.Year;
                int iMonth = dtCurrentProcess.Month;
                int iDay = dtCurrentProcess.Day;

                whiteboard.Delete(iYear, iMonth, iDay, sWorkID);
                dtCurrentProcess = dtCurrentProcess.AddDays(1);
            }
        }
        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Back", SES_Common.BackScript(Request.Url.ToString(), -1));

        ////Send mail to responsibility
        //// 沒有辦法直接由 e 取得
        //if (chkSendMail.Checked) {
        //    string sResponsibility = ((Label)gvSchedule.Rows[e.RowIndex].FindControl("lblResponsibility")).Text.ToLower().Replace("<br>", "\r\n");
        //    SendMail(Request["WorkID"].ToString(), txtJobNo.Text, txtFABID.Text, txtSESToolNo.Text, txtDescription.Text,
        //        sResponsibility, sExpectStartDate, sExpectEndDate, "Cancel");
        //}
    }
    protected void gvSchedule_RowUpdating(object sender, GridViewUpdateEventArgs e) {
        //e.NewValues[3] = SES_Common.getMatchGroup( e.NewValues[2].ToString()); // 取得相對應的 Group
        //Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Back", SES_Common.BackScript(Request.Url.ToString(), -1));
    }
    void SendMail(string sWorkID, string sJobNo, string sFABs, string sTools, string sDescription, string sResponsibilities,
        string sExpectStartDate, string sExpectEndDate, string AddOrCancel) {

        if (sJobNo == "" || sFABs == "" || sTools == "" || sResponsibilities == "" || sExpectStartDate == "" || sExpectEndDate == "" || AddOrCancel == "")
            return;

        string sSubject = "";
        if ( AddOrCancel == "Add")
            sSubject = Resources.Universal.NewWorkNotification_Subject;
        else if (AddOrCancel == "Cancel")
            sSubject = Resources.Universal.CancelWorkNotification_Subject;
        else
            return;

        string sTmpURL = ConfigurationManager.ConnectionStrings["RootURL"].ConnectionString + @"/TEC/WorksListDetail.aspx?WorkID=" + sWorkID;
        string sBody = "<HTML><BODY><TABLE>";
        sBody += "<TR><TD>" + Resources.Universal.JobNo_ID + "</TD><TD>" + sJobNo + "</TD></TR><br>";
        sBody += "<TR><TD>" + Resources.Universal.Comm_FABID + "</TD><TD>" + sFABs + "</TD></TR><br>";
        sBody += "<TR><TD>" + Resources.Universal.SES_ToolNo + "</TD><TD>" + sTools + "</TD></TR><br>";
        sBody += "<TR><TD>" + Resources.Universal.Comm_Description + "</TD><TD>" + sDescription + "</TD></TR><br>";
        sBody += "<TR><TD>" + Resources.Universal.WorksList_Responsibility + "</TD><TD>" + sResponsibilities.Replace("\r", "").Replace("\n", ", ") + "</TD></TR><br>";
        sBody += "<TR><TD>" + Resources.Universal.WorksList_ExpectStartDate + "</TD><TD>" + sExpectStartDate + "</TD></TR><br>";
        sBody += "<TR><TD>" + Resources.Universal.WorksList_ExpectEndDate + "</TD><TD>" + sExpectEndDate + "</TD></TR><br>";
        sBody += "</TABLE>";
        sBody += "<a href=" + sTmpURL + ">" + sTmpURL + "</a></BODY></HTML>";

        //Root.pcMail mail = new Root.pcMail(ConfigurationManager.ConnectionStrings["MailServer"].ConnectionString);
        //mail.Format = Root.pcMail.mailFormat.Html;
        //mail.Sender = "SESTW System";
        //mail.From = "roy_lai@ses-corp.co.jp";
        //mail.SendSmtpMail(SES_Common.getMatchMail(sResponsibilities), sSubject, sBody);


        //string[] ar = SES_Common.getMatchMail(sResponsibilities).Split(";".ToCharArray());
        //foreach (string sTo in ar) {
        //    MailAddress from = new MailAddress("roy@ses-taiwan.com.tw", "SESTW System");
        //    MailAddress to = new MailAddress(sTo, "");

        //    MailMessage msgMail = new MailMessage(from, to);
        //    msgMail.Subject = sSubject;
        //    msgMail.SubjectEncoding = System.Text.Encoding.Unicode;
        //    msgMail.IsBodyHtml = true;
        //    msgMail.Body = sBody;

        //    SmtpClient client = new SmtpClient("172.16.10.5");
        //    client.Send(msgMail);
        //}


        MailMessage msgMail = new MailMessage();

        msgMail.To = SES_Common.getMatchMail(sResponsibilities);
        //msgMail.From = @"""" + "SESTW System" + @""" " + "roy@ses-taiwan.com.tw";
        msgMail.From = @"""" + "SESTW System" + @""" " + "roy_system@jet-semi.com.tw";
        msgMail.Subject = sSubject;

        msgMail.BodyFormat = MailFormat.Html;
        msgMail.Body = sBody;
        //msgMail.Attachments.Add(new MailAttachment("c:\\temp\\annual-report.pdf"));
        ////MailAttachment maAttach = new MailAttachment("c:\\temp\\annual-report.pdf");
        ////IList msgAttachments = msgMail.Attachments;
        ////msgAttachments.Add(maAttach);

        SmtpMail.SmtpServer = "smtp.gmail.com:587";// "172.16.10.5";
        SmtpMail.Send(msgMail);

    }

    protected void btnAddAttachFile_Click(object sender, EventArgs e) {
        string sWorkID = "";
        try {
            if (Request["WorkID"] != null) {
                // ----------------- Top:更新表單的 Schedule -------------------------------------------
                sWorkID = Request["WorkID"].ToString();
                // ----------------- Bottom:更新表單的 Schedule -------------------------------------------
            }
            else {
                // ----------------- Top:新建表單時的 Schedule -------------------------------------------
                sWorkID = InsertOrUpdateClick("Insert", "");
                // ----------------- Bottom:新建表單時的 Schedule -------------------------------------------
            }
            if (sWorkID == "") {
                Response.Redirect("/SEST/Common/ErrorPage.aspx?BackPageCount=-1&Unknow WorkID");
                return;
            }

            // 1.儲存檔案至 SERVER, 2.儲存路徑至資料庫 ( <<<<< 實際儲存位置 >>>>> )
            HttpFileCollection uploadedFiles = Request.Files;
            string sTemp = "", sSingleFilePath = "", sFileName = "";
            Common_FilesStorageData file = new Common_FilesStorageData();
            if (uploadedFiles.Count <= 0)
                return;
            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("MainWorks", sWorkID, sFileName);
                        file.Insert("MainWorks", sWorkID, sFileName, sSingleFilePath, "", "");
                    }
                }
            }

            // <<<<<<< 無法放在 try 裡面 >>>>>>>
            if (Request["WorkID"] == null) {
                // 如果是新增,則往前移二頁再導至有 WorkID 引數的網址
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Back", SES_Common.BackScript(-2));
                Response.Redirect("WorksListDetail.aspx?WorkID=" + sWorkID);
            }
            else {
                // 往前移一頁(避免重新整理時再執行一次)再重新載入
                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", "=>"));
            return;
        }
    }
    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);

        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Back", SES_Common.BackScript(Request.Url.ToString(), -1));
    }


    protected void btnSearch_Click(object sender, EventArgs e) {
        try {
            Convert.ToDateTime(txtDate.Text + "/01");
            showResponsibilityTable("", "DB");
        }
        catch { }

        btnSearch.Focus();
    }

    protected void btnUpdateSchedule_Click(object sender, EventArgs e) {
        string sResponsibilities = "", sGroups = "", sExpectStartDate = "", sExpectEndDate = "";
        string sJobNo = "", sFABs = "", sTools = "", sDescription = "";   // for white board content

        try {

            if (sWorkID == "")
                sWorkID = Request["WorkID"].ToString();
            if (sWorkID == "")
                throw new Exception("Missing WorkID");

            //if (tblContents.Rows.Count < 2 || tblContents.Rows[0].Cells.Count < 2)
            //    return;
            showResponsibilityTable ( "", "WEBFORM");
            //return;

            DateTime dtDate = DateTime.Parse(txtDate.Text + "/01");

            //string cbReference = ClientScript.GetCallbackEventReference(this, "arg", "RecieveServerData", "context");


            if (Request[txtJobNo.ClientID] != null)
                sJobNo = Request[txtJobNo.ClientID].ToString();
            if (Request[txtSESToolNo.ClientID] != null)
                sTools = Request[txtSESToolNo.ClientID].ToString();
            // 取得機台所對應的 FABs
            string[] arTempTools = null, arTempFABs = null;
            string sTempTools = "", sTempCondition = "";
            if (sTools != "") {
                arTempTools = sTools.Replace("\r", "").Split("\n".ToCharArray());
                for (int i = 0; i < arTempTools.Length; i++) {
                    if (arTempTools[i].Trim() != "")
                        sTempTools += ",'" + arTempTools[i].Trim() + "'";
                }

                if (sTempTools != "") {
                    sTempCondition = "SES_ToolNo in (" + sTempTools.Substring(1) + ")";
                    arTempFABs = new TEC_ToolsData().SelectDistinct("FABID", sTempCondition);
                    for (int i = 0; i < arTempFABs.Length; i++) {
                        sFABs += "\r\n" + arTempFABs[i];
                    }
                    if (sFABs != "")
                        sFABs = sFABs.Substring(2);
                }
            }
            // JobNo or FAB or Tool can not assign empty
            if (sJobNo == "" || sFABs == "" || sTools == "")
                throw new Exception("JobNo or FAB or Tool is empty");

            if (Request[txtDescription.ClientID] != null)
                sDescription = Request[txtDescription.ClientID].ToString();

            // 先刪除白版上的內容
            TEC_WhiteBoardData whiteboard = new TEC_WhiteBoardData();
            whiteboard.Delete(dtDate.Year , dtDate.Month , sWorkID);

            // 新增至資料庫 (scheduling & whiteboard)
            for (int iCell = 1; iCell < tblContents.Rows[0].Cells.Count; iCell++) {
                sResponsibilities = "";
                for (int iRow = 1; iRow < tblContents.Rows.Count-1; iRow++) {
                    if (((CheckBox)tblContents.Rows[iRow].Cells[iCell].FindControl("chkDuty" + iRow.ToString("00") + iCell.ToString("00"))).Checked)
                        sResponsibilities += "\r\n" + tblContents.Rows[iRow].Cells[0].Text.Trim();
                }
                sExpectStartDate = txtDate.Text + "/" + iCell.ToString();
                sExpectEndDate = txtDate.Text + "/" + iCell.ToString();
                if (sResponsibilities == "")
                    new TEC_MainWorkSchedulesData().Delete(sWorkID, txtDate.Text + "/" + iCell.ToString());
                else {
                    sResponsibilities = sResponsibilities.Substring(2);
                    // 取得負責人所對應的 Group
                    sGroups = SES_Common.getMatchGroup(sResponsibilities);

                    // 儲存至 WhiteBoard
                    // [176] => AZZ00200_UMC8E-E_O-2216 : ARM Safty Wire Detect時動作變更改造工事 (賴皇佑 林志偉 邱建瀚 馬仲威)
                    string sWhiteBoardContent = "[" + sWorkID + "] => " + sJobNo + "_" + sFABs + "_" + sTools + " : " +
                            sDescription + "(" + sResponsibilities.Replace("\r\n", ",") + ")";
                    // 儲存至 MainWorkSchedule and WhiteBoard
                    SES_Common.saveScheduleAndWhiteBoard(sWorkID, sExpectStartDate, sExpectEndDate, sResponsibilities, sGroups, sWhiteBoardContent);
                }
            }


            //// 往前移一頁(避免重新整理時再執行一次)再重新載入
            //Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "Back", SES_Common.BackScript(Request.Url.ToString(), -1));

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

        ////Send mail to responsibility
        //if (chkSendMail.Checked) {
        //    SendMail(sWorkID, sJobNo, sFABs, sTools, sDescription, sResponsibilities, sExpectStartDate, sExpectEndDate, "Add");
        //}

        //// <<<<<<< 無法放在 try 裡面 >>>>>>>
        //Response.Redirect("WorksListDetail.aspx?WorkID=" + sWorkID);
        showResponsibilityTable("", "DB");
    }
}
    