using System;
using System.Collections.Generic;
using System.Globalization;
using System.Threading;
using System.IO;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.UI;
using System.Web.UI.WebControls;
using TABS.MailCarrier.WebSDK;
using TABS.MailCarrier.WebSDK.Approval;

public partial class Approval_ApplyApproval : System.Web.UI.Page
{
    protected string _approveButtonText = Resources.Approval.Approval_Approve_Button;

    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_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Page.Title = AppSetting.GetTitleInfo(Request).Title;
            _approveButtonText = WebParam.GetStrParamValue("btext", Resources.Approval.Approval_Approve_Button);

            ApprovalPerson person = new ApprovalPerson(WebParam.GetGuidParamValue("person"));
            person.Load();
            AcceptTextBox.Value = person.Reject;
        }
    }

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

    protected void AcceptButton_Click(object sender, EventArgs e)
    {
        Guid personId = WebParam.GetGuidParamValue("person");
        string acceptComment = AcceptTextBox.Value;
        ApprovalPerson person = new ApprovalPerson(personId);
        person.Load();
        
        if (person.Status != ApprovalPerson.AppStatus.Wait)
        {
            // 이미 결재 문서를 처리했습니다.
            ShowWarningMessage(GetLocalResourceObject("Msg03").ToString());
            return;
        }        

        // 승인전 승인 조건을 검사한 후 진행한다.
        //  - 승인과 협조자 추가가 브라우저 팝업에서 각각 실행될 수 있으므로 승인전 검사가 필요하다.
        //  - 결재권자의 경우 동일 스텝의 모든 협조 결재가 완료되어야 승인을 할 수 있다.
        if (person.Rights == ApprovalPerson.AppRights.Decision)
        {
            ApprovalDocument document = new ApprovalDocument(person.DocumentId);
            ApprovalPerson[] apvPersons = document.GetApprovalPersons();
            int spareCount = 0;
            foreach (ApprovalPerson apvPerson in apvPersons)
            {
                if (apvPerson.Step == person.Step &&
                    apvPerson.Rights == ApprovalPerson.AppRights.Collaboration &&
                    apvPerson.Status < ApprovalPerson.AppStatus.Apply)
                    spareCount++;
            }
            if (spareCount > 0)
            {
                // 모든 협조 결재자가 승인한 문서에 대해서만 결재를 진행할 수 있습니다.
                ShowWarningMessage(GetLocalResourceObject("Msg02").ToString());
                return;
            }
        }

        person.WebsiteAppUrl = WebParam.GetCurrentWebAppUrl();
        person.WebsiteAppUrl1 = AppSetting.GetTitleInfo(Request)["website1"];
        // WebSDK로 리소스 용어 전달
        person.AppResource.AppRightsPerson_Draft = Resources.Approval.AppRightsPerson_Draft;
        person.AppResource.AppRightsPerson_Decision = Resources.Approval.AppRightsPerson_Decision;
        person.AppResource.AppRightsPerson_Collaboration = Resources.Approval.AppRightsPerson_Collaboration;
        person.AppResource.AppRightsPerson_Forwarding = Resources.Approval.AppRightsPerson_Forwarding;
        person.AppResource.AppRightsPerson_Routing = Resources.Approval.AppRightsPerson_Routing;
        person.AppResource.AppStep = Resources.Approval.AppStep;
        if (AppSetting.ApvCollaboration != 1)
        {
            person.SetStatusUpdate2(ApprovalPerson.AppStatus.Apply, acceptComment, DateTime.UtcNow, AppSetting.NewApprovalNotificationTemplateFile, AppSetting.ApplyApprovalNotificationTemplateFile, AppSetting.ApplyApprovalType);
        }
        else
        {
            person.SetStatusUpdate(ApprovalPerson.AppStatus.Apply, acceptComment, DateTime.UtcNow, AppSetting.NewApprovalNotificationTemplateFile, AppSetting.ApplyApprovalNotificationTemplateFile, AppSetting.ApplyApprovalType);
        }

        JavaScriptSerializer json = new JavaScriptSerializer();
        List<JsonUploadFile> jsonRecipientList = json.Deserialize<List<JsonUploadFile>>(JsonUploadFilesHidden.Value);
        if (jsonRecipientList != null)
        {
            List<Attachment> attachments = new List<Attachment>();
            foreach (JsonUploadFile upfile in jsonRecipientList)
            {
                string filePath = string.Format("{0}\\{1}{2}", GlobalConfig.WebTempPath, upfile.Uid, upfile.Extension);
                attachments.Add(new Attachment(upfile.Name, filePath));
            }

            if (attachments.Count > 0)
            {
                ApprovalDocument document = new ApprovalDocument(person.DocumentId);
                document.Load();
                document.Update(attachments, null, person.Name);
            }
        }

        Response.Redirect("List.aspx?type=" + AppFolderDataSource.APPROVAL_FOLDERID);
    }

    private void ShowWarningMessage(string msg)
    {
        MsgBox.Visible = true;
        MsgBox.CssClass = "alert alert-danger";
        MsgBoxLabel.Text = msg;
    }
}