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

public partial class Approval_View : System.Web.UI.Page
{
    protected string _paramType;
    protected Guid _documentId = Guid.Empty;
    protected Guid _personId = Guid.Empty;
    protected ApprovalDocuments.EnumDocumentType _type;
    private ApprovalPerson[] _absentPersons = null;    // 결재선 상에서 부재자 정보
    protected string _approveButtonText = "";
    protected string _declineButtonText = "";

    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");
        _documentId = WebParam.GetGuidParamValue("document");
        _personId = WebParam.GetGuidParamValue("person");
        _type = ApprovalUtil.GetDocumentType(_paramType);
        Page.Title = AppSetting.GetTitleInfo(Request).Title;

        if (!IsPostBack)
        {
            _approveButtonText = Resources.Approval.Approval_Approve_Button;
            _declineButtonText = Resources.Approval.Approval_Decline_Button;
            if (AppSetting.ApvSuspendedStatus)
            {
                suspendToolButton.Attributes["style"] = "";
            }

            ApprovalDocument document = new ApprovalDocument(_documentId);
            document.Load();

            LoadApvDocument(document);
        }
    }

    private void LoadApvDocument(ApprovalDocument document)
    {
        DocTypeLabel.Text = GetTemplateCategory(document.Code);
        CreateDateLabel.Text = WebUser.CurrentUser.ToLocalTime(document.CreateDate).ToString("d");
        CodeLabel.Text = document.Code;
        int keepDays = document.KeepDays;
        if (keepDays == -1)
        {
            KeepDaysLabel.Text = Resources.Approval.Retention_Permanent;
        }
        else
        {
            KeepDaysLabel.Text = string.Format(Resources.Approval.Retention_Year, (keepDays / 365).ToString());
        }
        SubjectLabel.Text = document.Subject;
        // 인라인 이미지 처리.
        if (document.Inlines.Count > 0)
        {
            foreach (Attachment inline in document.Inlines)
            {
                if (inline.FileName != "")
                {
                    string fileName = "ViewInlineFile.ashx?fileName=" + inline.FileName;
                    string downlink = "ViewInlineFile.ashx?id=" + inline.ID;
                    document.Content = document.Content.Replace(fileName, downlink);
                }
            }
        }
        MsgBodyHolder.Controls.Add(new LiteralControl(document.Content));
        LoadAttachedFiles(document.ID, document.Attachments);

        ApprovalPerson me = null;
        ApprovalPerson[] apvPersons = document.GetApprovalPersons();
        // _personId에 해당하는 결재 참여자를 찾는다.
        foreach (ApprovalPerson person in apvPersons)
        {
            if (person.Id == _personId)
            {
                me = person;
                break;
            }
        }

        // 올바른 person이 지정되어 있지 않으면 권한 부족으로 처리한다.
        if (me == null)
        {
            Response.Redirect("~/Error.aspx?code=0", true);
            return;
        }

        // 부재중 표시는 결재할/결재중 문서함과 기안한 문서함에만 적용한다.
        if (_type == ApprovalDocuments.EnumDocumentType.APPROVAL || _type == ApprovalDocuments.EnumDocumentType.APPROVAL_ING || _type == ApprovalDocuments.EnumDocumentType.DRAFT)
            _absentPersons = document.GetAbsentPersons();

        if (_type == ApprovalDocuments.EnumDocumentType.APPROVAL)
        {
            // 결재할 문서함인 경우 승인, 반려, 협조 추가 버튼 활성, 비활성화 처리
            int personStep = me.Step;
            int spareCount = 0;
            // 동일 결재선상에서 승인되지 않은 결재권자를  찾는다.
            foreach (ApprovalPerson person in apvPersons)
            {
                if (person.Step == personStep &&
                    person.Rights == ApprovalPerson.AppRights.Collaboration &&
                    person.Status < ApprovalPerson.AppStatus.Apply)
                    spareCount++;
            }
            // 이전 결재단계까지 결재가 진행된 경우에만 승인, 반려가 활성화된다.
            if ((me.Status < ApprovalPerson.AppStatus.Apply) && (document.Status < ApprovalDocument.ApdStatus.Apply))
            {
                if ((me.Step - 1) == document.CompleteStep)
                {
                    if (me.Rights == ApprovalPerson.AppRights.Collaboration)
                    {
                        EnableBootstrapButton(approveToolButton);
                        EnableBootstrapButton(declineToolButton);
                        _approveButtonText = Resources.Approval.Approval_Approve4Collabo_Button;
                        _declineButtonText = Resources.Approval.Approval_Decline4Collabo_Button;
                    }
                    else if (me.Rights == ApprovalPerson.AppRights.Decision && spareCount == 0)
                    {
                        EnableBootstrapButton(approveToolButton);
                        EnableBootstrapButton(declineToolButton);
                        EnableBootstrapButton(suspendToolButton);       // 승인권자만 보류 가능
                    }
                }
            }
        }

        // 읽은 시각(app_readtime) 변경
        me.SetReadDate(DateTime.UtcNow);
        // 결재할 문서의 오픈 시각(app_opendate) 및 상태 변경 (미확인 => 대기)
        me.SetOpenDate(DateTime.UtcNow);

        // (결재, 협조), 참조 분류 및 참조권자 정보 출력
        List<ApprovalPerson> decisions = new List<ApprovalPerson>();
        for (int i = 0; i < apvPersons.Length; i++)
        {
            if (apvPersons[i].Rights == ApprovalPerson.AppRights.Refer)
            {
                if (RefereeLabel.Text.Length > 0) RefereeLabel.Text += ", " + apvPersons[i].Name;
                else RefereeLabel.Text = apvPersons[i].Name;
            }
            else if (apvPersons[i].Rights == ApprovalPerson.AppRights.Circulation)
            {
                if (CirculationLabel.Text.Length > 0) CirculationLabel.Text += ", " + apvPersons[i].Name;
                else CirculationLabel.Text = apvPersons[i].Name;
            }
            else if (apvPersons[i].Rights == ApprovalPerson.AppRights.Draft || apvPersons[i].Rights == ApprovalPerson.AppRights.Decision ||
                apvPersons[i].Rights == ApprovalPerson.AppRights.Collaboration)
            {
                decisions.Add(apvPersons[i]);
            }
        }
        if (RefereeLabel.Text.Length > 0) BootstrapUtil.CollapseControl(RefereePanel, false);
        if (CirculationLabel.Text.Length > 0) BootstrapUtil.CollapseControl(CirculationPanel, false);

        // 결재 진행 단계 로드
        ApvStepRepeater.DataSource = decisions;
        ApvStepRepeater.DataBind();
    }

    private string GetTemplateCategory(string code)
    {
        string[] s = code.Split('-');
        ApprovalTemplates templates = new ApprovalTemplates(WebUser.CurrentUser.DomainID);
        foreach (ApprovalTemplate template in templates.GetAllTemplates())
        {
            if (template.Code == s[1]) return template.Name;
        }
        return "&nbsp;";
    }

    private void LoadAttachedFiles(Guid documentId, List<Attachment> attachments)
    {
        int attachCount = 0;
        long attachSize = 0;
        ExtIconMap iconMap = new ExtIconMap();
        StringBuilder attchSb = new StringBuilder();
        foreach (Attachment attachment in attachments)
        {
            if (attachment.Type == Attachment.AttachType.Attachment)
            {
                string link =
                    string.Format("<a href=\"Download.ashx?document={4}&attach={1}\" class='list-group-item'><img src='../Images/Ext/{0}'/>{2} ({3}) {5}</a>",
                    iconMap.GetIconName(attachment.FileName), attachment.ID.ToString(), attachment.FileName, WebUtil.GetFormattedFileSize(attachment.Size), 
                    documentId.ToString(), (attachment.Owner != "") ? string.Format("[{0}]", attachment.Owner) : "");
                attchSb.Append(link);
                attachCount++;
                attachSize += attachment.Size;
            }
        }
        if (attachCount > 0)
        {
            AttachListTag.Text = attchSb.ToString();
            AttachSummaryLabel.Text = string.Format(GetLocalResourceObject("AttachSummary").ToString(), attachCount, WebUtil.GetFormattedFileSize(attachSize));
            BootstrapUtil.CollapseControl(attachPanel, false);     // 첨부 판넬 출력
        }
    }

    private void EnableBootstrapButton(HtmlButton button)
    {
        button.Attributes.Remove("disabled");
    }

    #region Approval Line Grid Display

    protected string GetApvDate(DateTime decisionDate)
    {
        if (decisionDate == DateTime.MinValue) return "";
        return WebUser.CurrentUser.ToLocalTime(decisionDate).ToString("g");
    }
    
    protected string GetRight(int appRights, int step)
    {
        ApprovalPerson.AppRights rights = (ApprovalPerson.AppRights)appRights;

        switch (rights)
        {
            case ApprovalPerson.AppRights.Draft:
                return Resources.Approval.AppRightsPerson_Draft;
            case ApprovalPerson.AppRights.Decision:
                return string.Format(string.Format("{0} ({1})", Resources.Approval.AppRightsPerson_Decision, Resources.Approval.AppStep), step);
            case ApprovalPerson.AppRights.Collaboration:
                return string.Format(string.Format("{0} ({1})", Resources.Approval.AppRightsPerson_Collaboration, Resources.Approval.AppStep), step);                
            case ApprovalPerson.AppRights.Refer:
                return string.Format(string.Format("{0} ({1})", Resources.Approval.AppRightsPerson_Forwarding, Resources.Approval.AppStep), step);                
            case ApprovalPerson.AppRights.Circulation:
                return Resources.Approval.AppRightsPerson_Routing;
        }
        return "-";
    }

    protected string GetName(Guid personId, string name , string department)
    {
        string label = "";
        if (name.Length > 0 && department.Length > 0)
            label = name + "/" + department;
        else if (name.Length > 0)
            label = name;
        label = Server.HtmlEncode(label);
        if (_absentPersons != null)
        {
            foreach (ApprovalPerson p in _absentPersons)
            {
                if (p.Id == personId)
                {
                    label += " <span class='label label-danger'>" + GetLocalResourceObject("Missed").ToString() + "</span>";
                    break;
                }
            }
        }
        return label;        
    }

    protected string GetStatus(int appRights, int appStatus)
    {
        ApprovalPerson.AppStatus status = (ApprovalPerson.AppStatus)appStatus;
        ApprovalPerson.AppRights rights = (ApprovalPerson.AppRights)appRights;

        if (rights == ApprovalPerson.AppRights.Draft)
        {
            return string.Format("<span class='apv-status-submitted'>{0}</span>", Resources.Approval.AppStatus_Submitted);
        }
        else if (rights > ApprovalPerson.AppRights.Collaboration)
        {
            if (status == ApprovalPerson.AppStatus.Defer)
            {
                return "<span class='apv-status-defer'>" + Resources.Approval.AppStatus_Defer + "</span>";
            }
            else
            {
                return "<span class='apv-status-opened'>" + Resources.Approval.AppStatus_Opened + "</span>";
            }
        }
        else
        {
            switch (status)
            {
                case ApprovalPerson.AppStatus.Defer:
                    return "<span class='apv-status-defer'>" + Resources.Approval.AppStatus_Defer + "</span>";
                case ApprovalPerson.AppStatus.Wait:
                    return "<span class='apv-status-wait'>" + Resources.Approval.AppStatus_Waiting + "</span>";                
                case ApprovalPerson.AppStatus.Apply:
                    return (rights == ApprovalPerson.AppRights.Collaboration) ?
                        "<span class='apv-status-apply'>" + Resources.Approval.AppStatus_Approved_4Collabo + "</span>" :
                        "<span class='apv-status-apply'>" + Resources.Approval.AppStatus_Approved + "</span>";
                case ApprovalPerson.AppStatus.Reject:
                    return (rights == ApprovalPerson.AppRights.Collaboration) ?
                        "<span class='apv-status-reject'>" + Resources.Approval.AppStatus_Declined_4Collabo + "</span>" :
                        "<span class='apv-status-reject'>" + Resources.Approval.AppStatus_Declined + "</span>";
                case ApprovalPerson.AppStatus.Replaced:
                    return "<span class='apv-status-replaced'>" + Resources.Approval.AppStatus_Replaced + "</span>";
                case ApprovalPerson.AppStatus.Suspended:
                    return "<span class='apv-status-suspended'>" + Resources.Approval.AppStatus_Suspended + "</span>";
            }
        }
        return "-";
    }

    protected string GetReject(string reject)
    {
        return (reject != "") ? string.Format("<tr><td colspan='3'>{0}</td></tr>", WebUtil.GetFormattedPlainText(reject, true)) : "";
    }

    #endregion
}