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_Duty : 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) {
        this.Title = Resources.SiteMapLocalizations.TEC + " - " + Resources.SiteMapLocalizations.TEC_Duty;
        //this.EnableViewState = false;   //清除 table 的狀態 (雖然 re add HtmlRow 但之前的狀態依然 hold 住)
        tblTitle.EnableViewState = false;
        tblContents.EnableViewState = false; //清除 table 的狀態 (雖然 re add HtmlRow 但之前的狀態依然 hold 住)
        
        HtmlGenericControl body = (HtmlGenericControl)Master.FindControl("masterbody");
        TreeView treeview = (TreeView)Master.FindControl("TreeView1");
        //以下程式碼為 fix absoult 的範例
        //body.Attributes.Add("onLoad", "fix()");
        //body.Attributes.Add("onScroll", "fix()");
        //body.Attributes.Add("onResize", "fix()");

        //// onload and onscroll 時表格的位置 --------------------------------
        //body.Attributes.Add("onLoad", "fix2('" + tblTitle.ClientID + "','" + tblContents.ClientID + "')");
        //treeview.Attributes.Add("onclick", "fix2('" + tblTitle.ClientID + "','" + tblContents.ClientID + "')");
        //Panel1.Attributes.Add("onScroll", "fix2('" + tblTitle.ClientID + "','" + tblContents.ClientID + "')");
        //// ----------------------------------------------------------------

        if (!IsPostBack) {
            txtDate.Text = DateTime.Today.ToString("yyyy/MM");
            tblComment.Rows[0].Cells[0].BgColor = "#FFA8A8"; tblComment.Rows[0].Cells[1].InnerText = Resources.Universal.Duty_WhiteBoardSingle;
            tblComment.Rows[0].Cells[2].BgColor = "#CC9898"; tblComment.Rows[0].Cells[3].InnerText = Resources.Universal.Duty_WhiteBoardMulti;
            tblComment.Rows[0].Cells[4].BgColor = "#A8A8FF"; tblComment.Rows[0].Cells[4].Attributes.Add("Style", "background-position: center center; background-image: url(../Imanges/phone.jpg)"); 
            tblComment.Rows[0].Cells[5].InnerText = Resources.Universal.OnCall;
            tblComment.Rows[0].Cells[6].BgColor = "#A8A8FF"; tblComment.Rows[0].Cells[6].Attributes.Add("Style", "background-repeat : no-repeat; background-position: center center; background-image: url(../Imanges/phone2.jpg)"); 
            tblComment.Rows[0].Cells[7].InnerText = Resources.Universal.OnCall_Sub;
            tblComment.Rows[0].Cells[8].BgColor = "#000000"; tblComment.Rows[0].Cells[9].InnerText = Resources.Universal.Duty_WhiteBoardAndOnCall;
        }

        // ========================= 建立表格 ==================================================
        HtmlTableRow htr = new HtmlTableRow();
        DateTime dtStart;
        DateTime dtEnd;
        DateTime dtTemp;

        // 月份的 row --------------------------------
        // Name
        htr.Cells.Add(getCell(1, "", "#EEEEEE", ""));
        tblTitle.Rows.Add(htr);

        // Content (show month at title
        try {
            dtStart = DateTime.Parse(txtDate.Text + "/01"); //.AddMonths(-1);
        }
        catch {
            txtDate.Text = DateTime.Today.ToString("yyyy/MM");
            dtStart = DateTime.Parse(txtDate.Text + "/01"); //.AddMonths(-1);
        }
        dtEnd = dtStart.AddMonths(4).AddDays(-1);
        dtTemp = dtStart;
        int iMonthIndex = 0;
        htr = new HtmlTableRow();
        while (dtTemp <= dtEnd) {
            htr.Cells.Add(getCell(dtTemp.AddMonths(1).AddDays(-1).Day, dtTemp.ToString("yyyy/MM"), "#DDDDFF", "color: red"));
            dtTemp = dtTemp.AddMonths(1);
            iMonthIndex++;
        }
        tblContents.Rows.Add(htr);
        // -------------------------------------------

        // Rows without title (month)
        string[] arGroupingColor = { "#BBEECC", "#AADDFE", "#DDDDCC", "#DDC866", "#CC99FF", "#FFDEAD", "#40E0D0", "#F0FFF0",
            "#BBEECC", "#AADDFE", "#DDDDCC", "#DDC866", "#CC99FF", "#FFDEAD", "#40E0D0", "#F0FFF0"};
        string sTempGrouping = "";
        int iGroupIndex = -1;
        DataTable dtEmp = new HR_EmployeesData().SelectDutyFormEmployeeExcludeLeave();
        for (int i=-1; i< dtEmp.Rows.Count; i ++){

            // Employee Name Field
            if (i == -1) {
                htr = new HtmlTableRow();
                htr.Cells.Add(getCell(1, "", "#EEEEEE", ""));
                tblTitle.Rows.Add(htr);
            }
            else {
                htr = new HtmlTableRow();
                htr.Cells.Add(getCell(1, dtEmp.Rows[i]["Name"].ToString(), "#DDF8EE", ""));
                tblTitle.Rows.Add(htr);
            }

            // Content
            htr = new HtmlTableRow();
            dtStart = DateTime.Parse(txtDate.Text + "/01"); //.AddMonths(-1);
            dtEnd = dtStart.AddMonths(4).AddDays(-1);
            dtTemp = dtStart;
            while (dtTemp <= dtEnd) {
                // iRowIndex = 0 時顯示日期 (因為在取得的工程師名字時有一空白在第一筆資料,所以不用補上)
                if (i == -1) {   // 日期列
                    if (dtTemp.ToString("yyyy/MM/dd") == DateTime.Today.ToString("yyyy/MM/dd"))  //今日
                        htr.Cells.Add(getCell(1, dtTemp.ToString("dd"), "#FFFF00", "font-size: 7pt"));
                    else if ((int)dtTemp.DayOfWeek == 0) // 周日
                        htr.Cells.Add(getCell(1, dtTemp.ToString("dd"), "#FF6666", "font-size: 7pt"));
                    else
                        htr.Cells.Add(getCell(1, dtTemp.ToString("dd"), "#EEFEFF", "font-size: 7pt"));
                }
                else { // 內容列
                    if (dtTemp.ToString("yyyy/MM/dd") == DateTime.Today.ToString("yyyy/MM/dd"))  //今日
                        htr.Cells.Add(getCell(1, "", "#FFFF00", "font-size: 7pt"));
                    else if ((int)dtTemp.DayOfWeek == 0) // 周日
                        htr.Cells.Add(getCell(1, "", "#FF6666", ""));
                    else {
                        //if (dtEmp.Rows[i]["DeptID"].ToString().Trim() == "HD")
                        //    htr.Cells.Add(getCell(1, "", "#BBEECC", ""));
                        //else if (dtEmp.Rows[i]["DeptID"].ToString().Trim() == "OS")
                        //    htr.Cells.Add(getCell(1, "", "#AADDFE", ""));
                        //else if (dtEmp.Rows[i]["DeptID"].ToString().Trim() == "SW" || dtEmp.Rows[i]["DeptID"].ToString().Trim() == "PLC" ||
                        //       dtEmp.Rows[i]["DeptID"].ToString().Trim() == "PC")
                        //    htr.Cells.Add(getCell(1, "", "#DDDDCC", ""));
                        //else if (dtEmp.Rows[i]["DeptID"].ToString().Trim() == "TS")
                        //    htr.Cells.Add(getCell(1, "", "#DDC866", ""));
                        if (dtEmp.Rows[i]["Grouping"].ToString().Trim() != sTempGrouping) {
                            iGroupIndex ++;
                            sTempGrouping = dtEmp.Rows[i]["Grouping"].ToString().Trim();
                        }

                        if (iGroupIndex < 0 || iGroupIndex >= arGroupingColor.Length)
                            htr.Cells.Add(getCell(1, "", "#F6F6F6", ""));
                        else
                            htr.Cells.Add(getCell(1, "", arGroupingColor[iGroupIndex], ""));
                    }
                }
                dtTemp = dtTemp.AddDays(1);
            }

            tblContents.Rows.Add(htr);
        }
        // ====================================================================================================


        //  ========================= 表格內容變更 (WhiteBoard)  ==================================================
        // Content (show month at title)
        dtStart = DateTime.Parse(txtDate.Text + "/01");//.AddMonths(-1);
        dtEnd = dtStart.AddMonths(4).AddDays(-1);
        dtTemp = dtStart;
        int iOffset = 0;    // 日期的位移
        string sContents; // 待處理的 Contents 欄位(資料庫中的名稱)
        string sTitleString ; //目前處理項目中要顯示的內容
        string sCellString;
        string sCellTitle ; // 真正要顯示在 Cell title 的內容 (可以有多筆項目)
        bool bChangeCellColor ;
        while (dtTemp <= dtEnd) {
            // 以月為單位找尋資料庫的資料
            DataTable dt = new TEC_WhiteBoardData().Select( dtTemp.Year, dtTemp.Month);
            // 再以個人 show 出資料 (前二列為 月 和 日期, 所以不處理)
            for ( int i=2; i<tblTitle.Rows.Count; i++){
                DataRow[] arDR = dt.Select("Contents like '%" + tblTitle.Rows[i].Cells[0].InnerText + "%'","Day");
                foreach( DataRow dr in arDR){
                    sContents = dr["Contents"].ToString(); sTitleString = ""; sCellTitle = ""; sCellString = ""; bChangeCellColor = false;
                    // 目前項目欲顯示的內容 (title & innerText)
                    if (sContents.IndexOf("=>") > 0 && sContents.IndexOf(":") > 0) {
                        sTitleString = sContents.Substring(sContents.IndexOf("=>") + 3, sContents.IndexOf(" : ") - sContents.IndexOf("=>") - 3);
                        if (sContents.IndexOf("@") > -1) {
                            sTitleString += "  " + sContents.Substring(sContents.IndexOf("@"));
                            bChangeCellColor = true;
                        }

                        sCellString = getShortInfo(sTitleString);
                    }
                    else {
                        if (sContents.IndexOf("@") > -1) {
                            sTitleString = sContents.Substring(sContents.IndexOf("@"));
                            bChangeCellColor = true;
                            
                            sCellString = sTitleString.Substring(1,1); 
                        }
                        else
                            sTitleString = sContents;
                    }
                    if (sTitleString.Length > 50) sTitleString = sTitleString.Substring(0, 50);

                    // Cell 完整的顯示內容
                    if (tblContents.Rows[i].Cells[int.Parse(dr["Day"].ToString()) + iOffset - 1].Attributes["title"] != null) { //已有資料
                        sCellTitle = tblContents.Rows[i].Cells[int.Parse(dr["Day"].ToString()) + iOffset - 1].Attributes["title"] + "\r\n" + sTitleString;
                        tblContents.Rows[i].Cells[int.Parse(dr["Day"].ToString()) + iOffset - 1].BgColor = "#CC9898";
                    }
                    else {
                        sCellTitle = sTitleString;
                        tblContents.Rows[i].Cells[int.Parse(dr["Day"].ToString()) + iOffset - 1].BgColor = "#FFA8A8";
                    }
                    // 變更 cell 的屬性 -----------------
                    if (sCellString != "" && // 不要指定沒有文字的內容 (也許前一個項目有文字) 或是前一個內容中的字顏色被 highlight (有註解事件)
                        tblContents.Rows[i].Cells[int.Parse(dr["Day"].ToString()) + iOffset - 1].Attributes["style"].IndexOf("#0088F0") < 0) 
                        tblContents.Rows[i].Cells[int.Parse(dr["Day"].ToString()) + iOffset - 1].InnerText = sCellString;
                        tblContents.Rows[i].Cells[int.Parse(dr["Day"].ToString()) + iOffset - 1].Attributes.Add("title", sCellTitle);
                    if (bChangeCellColor) 
                        tblContents.Rows[i].Cells[int.Parse(dr["Day"].ToString()) + iOffset - 1].Attributes.Add("style", "cursor: hand; color: #0000FF; font-size: 7pt");
                    else
                        tblContents.Rows[i].Cells[int.Parse(dr["Day"].ToString()) + iOffset - 1].Attributes.Add("style", "cursor: hand; color: #0088F0; font-size: 7pt");
                    // ----------------------------------
                }
            }
            dtTemp = dtTemp.AddMonths(1);
            iOffset += dtTemp.AddDays(-1).Day;
        }
        // ====================================================================================================

        //  ========================= 表格內容變更 (OnCall) =======================================================
        // Content (show month at title
        dtTemp = dtStart;
        iOffset = 0;    // 日期的位移
        string sEmpName;
        while (dtTemp <= dtEnd) {
            // 以月為單位找尋資料庫的資料
            DataTable dt = new TEC_OnCallData().Select(dtTemp.Year, dtTemp.Month);
            // 再以個人 show 出資料 (前二列為 月 和 日期, 所以不處理)
            for (int i = 2; i < tblTitle.Rows.Count; i++) {
                sEmpName = tblTitle.Rows[i].Cells[0].InnerText;
                DataRow[] arDR = dt.Select("MM like '%" + sEmpName + "%' or " +
                    "MS like '%" + sEmpName + "%' or " +
                    "EM like '%" + sEmpName + "%' or " +
                    "ES like '%" + sEmpName + "%'", "Day");
                foreach (DataRow dr in arDR) {
                    sTitleString = ""; sCellTitle = "";
                    // 目前項目欲顯示的內容
                    if (dr["MM"].ToString() == sEmpName)
                        sTitleString += "," + dr["Area"].ToString() + " MM oncall";
                    if (dr["MS"].ToString() == sEmpName)
                        sTitleString += "," + dr["Area"].ToString() + " MS oncall";
                    if (dr["EM"].ToString() == sEmpName)
                        sTitleString += "," + dr["Area"].ToString() + " EM oncall";
                    if (dr["ES"].ToString() == sEmpName)
                        sTitleString += "," + dr["Area"].ToString() + " ES oncall";
                    if (sTitleString.Length > 0) sTitleString = sTitleString.Substring(1);

                    // Cell 完整的顯示內容
                    // -- 已有 whiteboard 的內容值
                    if (tblContents.Rows[i].Cells[int.Parse(dr["Day"].ToString()) + iOffset - 1].Attributes["title"] != null) {
                        sCellTitle = tblContents.Rows[i].Cells[int.Parse(dr["Day"].ToString()) + iOffset - 1].Attributes["title"] + "\r\n" + sTitleString;
                        tblContents.Rows[i].Cells[int.Parse(dr["Day"].ToString()) + iOffset - 1].BgColor = "#000000";   // 背景設為黑色
                        if (tblContents.Rows[i].Cells[int.Parse(dr["Day"].ToString()) + iOffset - 1].Attributes["style"].IndexOf("#0088F0") > -1) // 在whiteboard 有資料 但沒有 @說明
                            tblContents.Rows[i].Cells[int.Parse(dr["Day"].ToString()) + iOffset - 1].Attributes.Add("style", "cursor: hand; color: #0088F0; font-size: 7pt");
                        else
                            tblContents.Rows[i].Cells[int.Parse(dr["Day"].ToString()) + iOffset - 1].Attributes.Add("style", "cursor: hand; color: #FFFFFF; font-size: 7pt");
                    }
                    else {  // -- 沒有 whtieboar 的內容
                        sCellTitle = sTitleString;
                        tblContents.Rows[i].Cells[int.Parse(dr["Day"].ToString()) + iOffset - 1].BgColor = "#A8A8FF";
                        if (sTitleString.IndexOf("MM") > -1 || sTitleString.IndexOf("EM") > -1) // 主 oncall
                            tblContents.Rows[i].Cells[int.Parse(dr["Day"].ToString()) + iOffset - 1].Attributes.Add("Style",
                                "cursor: hand; color: white; font-size: 6pt;background-repeat : no-repeat;  background-position: center center; background-image: url(../Imanges/phone.jpg)");
                        else // 副 oncall
                            tblContents.Rows[i].Cells[int.Parse(dr["Day"].ToString()) + iOffset - 1].Attributes.Add("Style",
                                "cursor: hand; color: white; font-size: 6pt;background-repeat : no-repeat;  background-position: center center; background-image: url(../Imanges/phone2.jpg)");
                    }

                    // 變更 cell 的屬性
                    tblContents.Rows[i].Cells[int.Parse(dr["Day"].ToString()) + iOffset - 1].Attributes.Add("title", sCellTitle);
                }
            }
            dtTemp = dtTemp.AddMonths(1);
            iOffset += dtTemp.AddDays(-1).Day;
        }
        // ====================================================================================================
    }



    HtmlTableCell getCell(int ColSpan, string innerText, string BgColor, string Style) {
        HtmlTableCell htc = new HtmlTableCell();

        htc.ColSpan = ColSpan;
        if ( innerText == "")
            htc.InnerHtml = "&nbsp;";
        else
            htc.InnerText = innerText;

        htc.Height = "15px";
        //htc.Width = "15px";
        htc.NoWrap = true;
        htc.Align = "Center";
        htc.BgColor = BgColor;
        htc.Attributes.Add("style", Style);

        return htc;
    }

    string getShortInfo(string sCellTitle) { 
        if (sCellTitle.IndexOf("_") < 0) return "@";
        string sTmp = sCellTitle.Substring(sCellTitle.IndexOf("_")+1);
        if (sTmp.IndexOf("_") < 0) return "@";
        sTmp = sTmp.Substring(0, sTmp.IndexOf("_"));

        string[] ar = new Customer_FABData().SelectDistinct("Abbreviation", "FABID like '" + sTmp + "%'");
        if (ar.Length <= 0)
            return "XX";
        else
            return ar[0];

        //if (sCellTitle.IndexOf("PSC12A") > -1)
        //    return "PA";
        //if (sCellTitle.IndexOf("PSC12B") > -1)
        //    return "PB";
        //if (sCellTitle.IndexOf("PSC12C") > -1)
        //    return "PC";
        //if (sCellTitle.IndexOf("PSC12M") > -1)
        //    return "PM";
        //if (sCellTitle.IndexOf("WEC-4") > -1)
        //    return "W4";
        //if (sCellTitle.IndexOf("WEC-5") > -1)
        //    return "W5";
        //if (sCellTitle.IndexOf("WEC-6") > -1)
        //    return "W6";
        //if (sCellTitle.IndexOf("MXIC2") > -1)
        //    return "M2";
        //if (sCellTitle.IndexOf("NTC-1") > -1)
        //    return "N1";
        //if (sCellTitle.IndexOf("NTC-2") > -1)
        //    return "N2";
        //if (sCellTitle.IndexOf("NTC-3") > -1)
        //    return "N3";
        //if (sCellTitle.IndexOf("UMC8A") > -1)
        //    return "UA";
        //if (sCellTitle.IndexOf("UMC8C") > -1)
        //    return "UC";
        //if (sCellTitle.IndexOf("UMC8D") > -1)
        //    return "UD";
        //if (sCellTitle.IndexOf("UMC8E") > -1)
        //    return "UE";
        //if (sCellTitle.IndexOf("UMC8F") > -1)
        //    return "UF";
        //if (sCellTitle.IndexOf("UMC12A") > -1)
        //    return "U12";
        //if (sCellTitle.IndexOf("TSMC12A") > -1)
        //    return "T12";
        //if (sCellTitle.IndexOf("TSMC8A") > -1)
        //    return "T8";

        //return "XX";
    }
}
