using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using TABS.MailCarrier.WebSDK;
using TABS.MailCarrier.WebSDK.Approval;
using TABS.MailCarrier.WebSDK.User;

public partial class Approval_List : System.Web.UI.Page
{
    protected string _paramType;
    private ApprovalDocuments.EnumDocumentType _documentType;
    private Guid _id;

    protected override void InitializeCulture()
    {
        string defLang = WebUser.CurrentUser.UiLanguage;
        Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(defLang);
        Thread.CurrentThread.CurrentUICulture = new CultureInfo(defLang);
        base.InitializeCulture();
    }

    protected void Page_Init(object sender, EventArgs e)
    {
        WebUtil.SetMcCommonCss(Page.Header);
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        _paramType = WebParam.GetStrParamValue("type");
        _documentType = ApprovalUtil.GetDocumentType(_paramType);
        _id = WebParam.GetGuidParamValue("id");
        Page.Title = AppSetting.GetTitleInfo(Request).Title;

        if (!IsPostBack)
        {
            if (!AppSetting.UseApproval || DomainUser.IncludedInAccessGroup(WebUser.CurrentUser.DomainUserID, "전자결재사용금지"))
            {
                Response.Redirect("~/Error.aspx?code=0", true);
                return;
            }

            SwichListByType(DocPersonDataSource, _documentType);
            ApvDocGridView.Columns[0].HeaderText = ApprovalUtil.GetFolderName(_documentType, _id);
            // 결재할 문서함만 읽지 않은 문서 개수 출력
            if (_documentType == ApprovalDocuments.EnumDocumentType.APPROVAL)
            {
                ApprovalDocuments documents = new ApprovalDocuments(WebUser.CurrentUser.DomainID, WebUser.CurrentUser.UserAccount);
                documents.LoadApprovalPersonCount();
                int unread = documents.GetApprovalPersonCount(ApprovalDocuments.EnumDocumentType.APPROVAL);
                if (unread > 0)
                    ApvDocGridView.Columns[0].HeaderText += string.Format(" <span class='badge mc-badge'>{0}</span>", unread);
            }
        }
    }

    protected void ApvDocGridView_PreRender(object sender, EventArgs e)
    {
        GridView gv = (GridView)sender;
        if ((gv.ShowHeader == true && gv.Rows.Count > 0) || (gv.ShowHeaderWhenEmpty == true))
        {
            gv.HeaderRow.TableSection = TableRowSection.TableHeader;
        }
        if (gv.ShowFooter == true && gv.Rows.Count > 0)
        {
            gv.FooterRow.TableSection = TableRowSection.TableFooter;
        }
    }

    protected void SearchButton_Click(object sender, EventArgs e)
    {
        string keyword = KeywordTextBox.Text.Trim();
        if (keyword != "")
        {
            ApvDocGridView.DataSourceID = "SearchedDocPersonDataSource";
            ApvDocGridView.PageIndex = 0;

            SwichListByType(SearchedDocPersonDataSource, _documentType);

            SearchedDocPersonDataSource.SelectParameters.Add("category", System.Data.DbType.Int32, CategoryList.SelectedValue);
            SearchedDocPersonDataSource.SelectParameters.Add("searchKeywords", System.Data.DbType.String, keyword);

            ApvDocGridView.DataBind();
            searchPanel.Attributes.Add("class", "collapse in");
        }
        else
        {
            ApvDocGridView.DataSourceID = "DocPersonDataSource";
            SwichListByType(DocPersonDataSource, _documentType);
            ApvDocGridView.PageIndex = 0;
            ApvDocGridView.DataBind();
        }
    }

    protected void SearchCancelButton_Click(object sender, EventArgs e)
    {
        ApvDocGridView.DataSourceID = "DocPersonDataSource";
        SwichListByType(DocPersonDataSource, _documentType);
        ApvDocGridView.PageIndex = 0;
        ApvDocGridView.DataBind();

        KeywordTextBox.Text = "";
        CategoryList.SelectedIndex = 1;
        searchPanel.Attributes.Add("class", "collapse");
    }

    private void SwichListByType(ObjectDataSource dataSource, ApprovalDocuments.EnumDocumentType documentType)
    {
        dataSource.SelectParameters.Clear();
        dataSource.SelectParameters.Add("domainId", System.Data.DbType.Guid, WebUser.CurrentUser.DomainID.ToString());
        dataSource.SelectParameters.Add("user", System.Data.DbType.String, WebUser.CurrentUser.UserAccount);
        dataSource.SelectParameters.Add("documentType", System.Data.DbType.Int32, ((int)documentType).ToString());
        dataSource.SelectParameters.Add("parentId", System.Data.DbType.Guid, WebParam.GetStrParamValue("id"));
    }


    #region ApvDocGridView Methods

    protected string GetClickEventFunction(Guid apdId, Guid appId)
    {
        return string.Format("ViewDocument('{0}', '{1}', '{2}')", apdId, appId, WebParam.GetStrParamValue("type"));
    }

    protected string GetSubject(Guid apdId, Guid appId, string subject, DateTime readDate)
    {
        return (readDate == DateTime.MinValue) ? string.Format("<strong>{0}</strong>", Server.HtmlEncode(subject)) : Server.HtmlEncode(subject);
    }

    protected string GetAttachmentImage(int attachNum)
    {
        return MailUtil.GetAttachFontIcon(attachNum);
    }

    protected string GetStatus(Guid documentId, int apdStatus, int completeStep, int personStep, int rights)
    {
        string displayStatus = "-";

        ApprovalPerson.AppRights appRights = (ApprovalPerson.AppRights)rights;

        // 결재문서 폴더-결재할 문서함인 경우
        if (_documentType == ApprovalDocuments.EnumDocumentType.APPROVAL)
        {
            if (rights == 4) displayStatus = Resources.Approval.AppStatus_Forwarding;       // 참조
            else if (completeStep == personStep - 1) displayStatus = Resources.Approval.AppStatus_ToApprove;        // 결재가능
            else displayStatus = Resources.Approval.AppStatus_Waiting;      // 결재대기

            if (appRights == ApprovalPerson.AppRights.Refer)
            {
                displayStatus = Resources.Approval.AppStatus_Forwarding;        // 참조
            }
            else if ((ApprovalDocument.ApdStatus)apdStatus == ApprovalDocument.ApdStatus.Suspended)
            {
                displayStatus = Resources.Approval.AppStatus_Suspended;         // 보류
            }
            else if (completeStep == personStep - 1)
            {
                if (appRights == ApprovalPerson.AppRights.Decision)
                {
                    ApprovalDocument document = new ApprovalDocument(documentId);
                    ApprovalPerson[] apvPersons = document.GetApprovalPersons();
                    // 동일 결재선상에서 승인되지 않은 결재권자를 찾는다.
                    int spareCount = 0;
                    foreach (ApprovalPerson person in apvPersons)
                    {
                        if (person.Step == personStep &&
                            person.Rights == ApprovalPerson.AppRights.Collaboration &&
                            person.Status < ApprovalPerson.AppStatus.Apply)
                            spareCount++;
                    }
                    if (spareCount == 0)
                        displayStatus = Resources.Approval.AppStatus_ToApprove;        // 결재가능
                    else
                        displayStatus = Resources.Approval.AppStatus_Waiting;      // 결재대기
                }
                else
                {
                    // 결재권자가 아닌 협조자는 결재가능을 출력
                    displayStatus = Resources.Approval.AppStatus_ToApprove;        // 결재가능
                }
            }
            else
            {
                displayStatus = Resources.Approval.AppStatus_Waiting;      // 결재대기
            }

            if (displayStatus == Resources.Approval.AppStatus_ToApprove)
            {
                displayStatus = string.Format("<span class='label label-info'>{0}</span>", displayStatus);
            }
            else
            {
                displayStatus = string.Format("<small>{0}</small>", displayStatus);
            }
        }
        else
        {
            ApprovalDocument.ApdStatus status =
                (ApprovalDocument.ApdStatus)apdStatus;

            switch (status)
            {
                case ApprovalDocument.ApdStatus.Edit:
                    displayStatus = Resources.Approval.AppStatus_Prepared;      // 보류
                    break;
                case ApprovalDocument.ApdStatus.Wait:
                    displayStatus = Resources.Approval.AppStatus_Waiting;       // 대기
                    break;
                case ApprovalDocument.ApdStatus.Apply:
                    displayStatus = Resources.Approval.AppStatus_Approved;      // 승인
                    break;
                case ApprovalDocument.ApdStatus.Reject:
                    displayStatus = Resources.Approval.AppStatus_Declined;      // 반려
                    break;
                case ApprovalDocument.ApdStatus.Cancel:
                    displayStatus = Resources.Approval.AppStatus_Canceled;      // 취소
                    break;
                case ApprovalDocument.ApdStatus.Suspended:
                    displayStatus = Resources.Approval.AppStatus_Suspended;     // 보류
                    break;
            }
            displayStatus = "<small>" + displayStatus + "</small>";
        }
        return displayStatus;
    }

    #endregion
}