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_WeeklyPayment : 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_LoadComplete(object sender, EventArgs e) {
        if (txtStartDate.Text == "" && txtEndDate.Text == "") {
            txtStartDate.Text = DateTime.Today.AddMonths(-1).ToString("yyyy/MM/dd");
            txtEndDate.Text = DateTime.Today.ToString("yyyy/MM/dd");
        }
    }

    protected void btnPreView_Click(object sender, EventArgs e) {
        try {
            //if (FileUpload1.PostedFile.FileName != "") {
            if ( FileUpload1.FileName != ""){
                // upload file
                string 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);
                string sFilePath = System.IO.Path.Combine(sTemp + FileUpload1.FileName);
                FileUpload1.PostedFile.SaveAs( sFilePath); // file path on the server


                //read file and save to DB on the server
                DataTable dt = SES_Common.parseExcelFile(sFilePath, "Page1$"); //(FileUpload1.PostedFile.FileName, "Page1$");
                DataTable dtReal = new DataTable();
                dtReal.Columns.Add(Resources.Universal.Employee_Name);
                dtReal.Columns.Add(Resources.Universal.Comm_Item);
                dtReal.Columns.Add(Resources.Universal.PettyCash_ReceiptDate);
                dtReal.Columns.Add(Resources.Universal.PettyCash_PayDate);
                dtReal.Columns.Add(Resources.Universal.PettyCash_Amount);
                foreach (DataRow dr in dt.Rows) { 
                    string sAmount = dr[1].ToString(); // amount
                    string sReceiptDate = dr[2].ToString(); 
                    string[] arContents = dr[3].ToString().Split(",".ToCharArray());
                    string sPayDate = arContents[0];
                    string sUserName = arContents[1];
                    string sItem = arContents[2];

                    sReceiptDate = sReceiptDate.Replace(".","/").Trim();
                    string sTmp = sReceiptDate.Substring(0, sReceiptDate.IndexOf("/"));
                    if (sTmp.Length < 4)
                        sReceiptDate = (int.Parse(sTmp) + 1911).ToString() + sReceiptDate.Replace(sTmp, "");
                    sPayDate = sPayDate.Replace(".","/").Trim();
                    sTmp = sPayDate.Substring(0, sPayDate.IndexOf("/")  );
                    if (sTmp.Length < 4)
                        sPayDate = (int.Parse(sTmp) + 1911).ToString() + sPayDate.Replace(sTmp, "");

                    try {
                        DateTime.Parse(sReceiptDate);
                        DateTime.Parse(sPayDate);
                    }
                    catch {
                        Response.Redirect("/SEST/Common/ErrorPage.aspx?BackPageCount=-1&ErrorMessage=Incorrect DateTime");
                        return;
                    }
                    dtReal.Rows.Add(new string[] { sUserName, sItem, sReceiptDate, sPayDate, sAmount});
                }

                GridView2.DataSource = dtReal;
                GridView2.DataBind();
            }
        }
        catch (Exception ex) {
            Response.Redirect("/SEST/Common/ErrorPage.aspx?BackPageCount=-1&ErrorMessage=" + ex.Message.Replace("\r\n", "=>"));
        }
    }
    protected void btnUpload_Click(object sender, EventArgs e) {
        try {
            //if (FileUpload1.PostedFile.FileName != "") {
            if (FileUpload1.FileName != "") {
                string 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);

                // 因為在 web.config 中有設定 identity, 所以不用了
                //hyNetUse net = new hyNetUse();
                //try
                //{
                //    net.ConnectToRemote(
                //        @"\\172.16.27.10\D$\SEST\SES-T_FilesStorage\",
                //        "Administrator",
                //        "Jet$S01");
                //}
                //catch { }
                if (!System.IO.Directory.Exists(sTemp))
                {
                    System.Security.AccessControl.DirectorySecurity sec = new System.Security.AccessControl.DirectorySecurity();
                    //sec.SetAccessRule(new System.Security.AccessControl.FileSystemAccessRule("Administrator", System.Security.AccessControl.FileSystemRights.CreateDirectories, 
                    //    System.Security.AccessControl.AccessControlType.Allow));
                    System.IO.Directory.CreateDirectory(sTemp);
                }

                // upload file
                //sTemp = Root.Storage.pcDirFile.CreateFolderByDate(sTemp, System.DateTime.Today, Root.Storage.pcDirFile.CreateFolderType.Cascade, Root.Storage.pcDirFile.CreateDateBase.Day, false);
                string sFilePath = System.IO.Path.Combine(sTemp + FileUpload1.FileName);
                FileUpload1.PostedFile.SaveAs(sFilePath); // file path on the server


                //read file and save to DB on the server
                DataTable dt = SES_Common.parseExcelFile(sFilePath, "Page1$"); //(FileUpload1.PostedFile.FileName, "Page1$");
                foreach (DataRow dr in dt.Rows) {
                    string sAmount = dr[1].ToString(); // amount
                    string sReceiptDate = dr[2].ToString();
                    string[] arContents = dr[3].ToString().Split(",".ToCharArray());
                    string sPayDate = arContents[0];
                    string sUserName = arContents[1];
                    string sItem = arContents[2];

                    sReceiptDate = sReceiptDate.Replace(".", "/").Trim();
                    string sTmp = sReceiptDate.Substring(0, sReceiptDate.IndexOf("/"));
                    if (sTmp.Length < 4)
                        sReceiptDate = (int.Parse(sTmp) + 1911).ToString() + sReceiptDate.Replace(sTmp, "");
                    sPayDate = sPayDate.Replace(".", "/").Trim();
                    sTmp = sPayDate.Substring(0, sPayDate.IndexOf("/"));
                    if (sTmp.Length < 4)
                        sPayDate = (int.Parse(sTmp) + 1911).ToString() + sPayDate.Replace(sTmp, "");

                    try {
                        DateTime.Parse(sReceiptDate);
                        DateTime.Parse(sPayDate);
                    }
                    catch {
                        Response.Redirect("/SEST/Common/ErrorPage.aspx?BackPageCount=-1&ErrorMessage=Incorrect DateTime");
                        return;
                    }
                    new HR_PettyCashData().Insert(sUserName, sItem, sReceiptDate, sPayDate, sAmount);
                }
            }
            else
                Response.Redirect("/SEST/Common/ErrorPage.aspx?BackPageCount=-1&ErrorMessage=No FIleName");
        }
        catch (Exception ex) {
            Response.Redirect("/SEST/Common/ErrorPage.aspx?BackPageCount=-1&ErrorMessage=" + ex.Message.Replace("\r\n", "=>"));
        }
    }

    protected void Page_Load(object sender, EventArgs e) {
    }

    protected void rdoFunction_CheckedChanged(object sender, EventArgs e) {
        trAddNewPanel.Visible = false;
        trSearchPanel.Visible = false;
        if (rdoAddNew.Checked)
            trAddNewPanel.Visible = true;
        if (rdoSearch.Checked)
            trSearchPanel.Visible = true;
    }
    protected void btnSearch_Click(object sender, EventArgs e) {
        string sUserName = txtUserName.Text.Trim().Replace("''","").Replace("--","");
        string sStartDate = txtStartDate.Text.Trim();
        string sEndDate = txtEndDate.Text.Trim();
        try{
            if (sStartDate.Length > 0)
                DateTime.Parse(sStartDate);
            if (sEndDate.Length > 0)
                DateTime.Parse(sEndDate);
        }
        catch{
            Response.Redirect("/SEST/Common/ErrorPage.aspx?BackPageCount=-1&ErrorMessage=Incorrect DateTime");
            return;
        }

        string sCondition = "";
        if (sUserName.Length > 0 )
            sCondition += " and UserName like '%" + sUserName + "%' ";
        if (sStartDate.Length > 0 )
            sCondition += " and ReceiptDate>='" + sStartDate + "'";
        if (sEndDate.Length > 0)
            sCondition += " and ReceiptDate<='" + sEndDate + "'";

        if ( sCondition.Length > 0)
            sCondition = sCondition.Substring(5);
        else
            sCondition = "1=1";

        ObjectDataSource1.SelectParameters.Clear();
        ObjectDataSource1.SelectParameters.Add("Condition",sCondition);

    }



}
