#region Copyright © 2015 CLIPSOFT Co.,Ltd. All Rights Reserved.
//
// All rights are reserved. Reproduction or transmission in whole or in part, 
// in any form or by any means, electronic, mechanical or otherwise, is 
// prohibited without the prior written consent of the copyright owner.
//
// Filename:ConsentSelectTabPageConsentSet.cs
//
#endregion
using System;
using System.ComponentModel;
using System.Windows.Forms;
using CLIP.eForm.Consent.UI.HospitalSvcRef;
using ClipSoft.eForm.Base.Dialog;

namespace CLIP.eForm.Consent.UI {
  /// <summary>
  /// 동의서 SET 탭 클래스
  /// </summary>
  /// <remarks>
  /// <p>[설계자]</p>
  /// <p>  클립소프트 연구소 홍지철 (jchong@clipsoft.co.kr)</p>
  /// <p>[원본 작성자]</p>
  /// <p>  클립소프트 기술부 4팀 이창훈 (chlee@clipsoft.co.kr)</p>
  /// <p>[수정 작성자]</p>
  /// <p>  클립소프트 기술부 이인희</p>
  /// <p>----------------------------------------------------------------------------------------</p>
  /// <p>[HISTORY]</p>
  /// <p> 2016-06-28 : 최초작성</p>
  /// <p>----------------------------------------------------------------------------------------</p>
  /// </remarks>  
  public partial class ConsentSelectTabPageConsentSet : UserControl {
    private HospitalSvcRef.HospitalSvcSoapClient hospitalWebService = null;
    private IConsentMain consentMain = null;
    private ConsentCommandCtrl commandControl = null;

    public ConsentSelectTabPageConsentSet() {
      InitializeComponent();
    }

    private void initResources() {
      consentMain = ConsentMainControl.GetConsentMainInterface(this);
      commandControl = consentMain.ConsentCommandCtrl as ConsentCommandCtrl;
      hospitalWebService = WebMethodCommon.GetHospitalWebService(consentMain.PluginExecuteInfo["hospitalSvcUrl"]);
    }

    private void ConsentSelectTabPageConsentSet_Load(object sender, EventArgs e) {
      if (this.DesignMode || LicenseManager.UsageMode == LicenseUsageMode.Designtime) {
        return;
      }

      consentMain = ConsentMainControl.GetConsentMainInterface(this);
      commandControl = consentMain.ConsentCommandCtrl as ConsentCommandCtrl;
      hospitalWebService = WebMethodCommon.GetHospitalWebService(consentMain.PluginExecuteInfo["hospitalSvcUrl"]);

      if (commandControl.CurrentEndUser != null) {
        InitConsentSetTreeView();
      }
    }

    /// <summary>
    /// 즐겨찾기 트리 노드 생성 (개인 SET)
    /// </summary>
    public void InitConsentSetTreeView() {
      if (consentMain == null || commandControl == null || hospitalWebService == null) {
        initResources();
      }
      //개인SET과 진료과SET인 경우
      //ConsentSetVO[] arrayData = this.hospitalWebService.GetConsentSetList(commandControl.CurrentEndUser.UserNo,
      //                                                                     commandControl.CurrentEndUser.DeptCode);
      // 동의서 SET 조회
      ConsentFormListVO[] arrayData = this.hospitalWebService.GetConsentSetList(commandControl.CurrentEndUser.UserNo, consentMain.ConsentExecuteInfo["dutinstcd"]);

      this.treeViewConsentSet.Nodes.Clear();

      TreeNode personalTreeNode = AddFirstChildNodeOfTreeView("PERS", "개인 SET", 1);
      //TreeNode deptTreeNode = AddFirstChildNodeOfTreeView("DEPT", "진료과 SET", 2);            

      // 조회 결과를 동의서 node 에 추가
      if (arrayData != null) {
        foreach (ConsentFormListVO vo in arrayData) {
          //if (vo.SetAuth.Equals("PERS_SET"))
          {
            AddConsentNode(personalTreeNode, vo);
          }
          //else if (vo.SetAuth.Equals("DEPT_SET"))
          //{
          //    AddDeptsConsentSet(vo);
          //}
        }
      }

      this.treeViewConsentSet.Nodes["PERS"].ExpandAll();
      //this.treeViewConsentSet.Nodes["DEPT"].Expand();

      //사용자의 부서에 해당하는 동의서들만 펼친다.
      //if (this.treeViewConsentSet.Nodes["DEPT"].Nodes.ContainsKey(commandControl.CurrentEndUser.DeptCode))
      //{
      //    this.treeViewConsentSet.Nodes["DEPT"].Nodes[commandControl.CurrentEndUser.DeptCode].ExpandAll();
      //}
    }

    /// <summary>
    /// 동의서 미리보기
    /// </summary>
    private void ExecutePreviewWithSelectedConsent() {
      ConsentFormListVO vo = this.treeViewConsentSet.SelectedNode.Tag as ConsentFormListVO;

      if (vo == null) {
        return;
      }

      if (!consentMain.checkOperationDocument(vo.formCd)) {
        return;
      }

      if (consentMain == null) consentMain = ConsentMainControl.GetConsentMainInterface(this);
      if (commandControl == null) commandControl = consentMain.ConsentCommandCtrl as ConsentCommandCtrl;

      // 선택된 동의서가 현재 보여지고 있는 동의서와 다른 경우, 임시 저장 여부 확인
      if (!consentMain.ConsentExecuteInfo["readOnly"].Equals("Y") &&
          !string.IsNullOrEmpty(commandControl.CurrentTargetPatient.PatientCode) &&
          commandControl.CurrentPreviewConsent != null && !commandControl.CurrentPreviewConsent.formRid.Equals(vo.formRid.ToString()) &&
          (commandControl.CurrentPreviewConsent.consentState == string.Empty || commandControl.CurrentPreviewConsent.consentState == "TEMP")) {
        // dbs227, 임시저장 팝업 사용 안함
        //DialogResult result = MessageBox.Show(string.Format(Properties.Resources.msg_confirm_tempsave)
        //                            , string.Format(Properties.Resources.msg_caption_confirm),
        //                            MessageBoxButtons.YesNo, MessageBoxIcon.Information);

        //if (result == DialogResult.Yes) {
        //    consentMain.TempSave();
        //}
      }

      consentMain.preParamClean();

      PatientInfoCtrl patient = consentMain.PatientInfoCtrl as PatientInfoCtrl;

      Cursor currentCursor = this.Cursor;
      this.Cursor = Cursors.WaitCursor;

      commandControl.CurrentPreviewConsent = new PreviewConsent {
        formRid = vo.formRid.ToString(),
        formGuid = vo.formGuid,
        formCd = vo.formCd.ToString(),
        FormName = vo.formName,
        formPrintName = vo.formPrntNm,
        prntCnt = vo.printCnt,
        consentMstRid = "-1",
        consentState = string.Empty,
        inputId = commandControl.CurrentEndUser.UserNo,
        inputNm = commandControl.CurrentEndUser.UserName,
        ReissueConsentMstRid = 0,
        RewriteConsentMstRid = 0,
        ocrtagPrntyn = vo.ocrTagPrntYn,
        userDrFlag = vo.userDrFlag,
        printOnly = vo.printOnly,
        opDiagName = vo.opDiagNm,
        ocrCode = "",
        opName = vo.opNm,
        drOnly = vo.DrOnly,
        // 즐겨찾기에서 Linkcd 호출 되지 않는 현상 수정
        linkFormCd = vo.linkFormCd
      };

      //동의서 맵핑 정보를 상단의 선택된 진료일과 작성자 정보로 한다.
      consentMain.PatientInfoCtrl.SetBasicPatientInfo();
      consentMain.PatientInfoCtrl.SetConsentDocumentName(vo.formName);
      commandControl.PreviewConsent(consentMain);

      this.Cursor = currentCursor;
    }

    #region 트리 노드 추가        
    /// <summary>
    /// parent node 를 생성하여 treeViewConsentSet 에 추가한다
    /// </summary>
    /// <param name="treeNodeName">Name of the tree node.</param>
    /// <param name="treeNodeLabel">The tree node label.</param>
    /// <param name="imageIndex">Index of the image.</param>
    /// <returns></returns>
    private TreeNode AddFirstChildNodeOfTreeView(string treeNodeName, string treeNodeLabel, int imageIndex) {
      TreeNode parentNode = new TreeNode(treeNodeLabel);
      parentNode.Name = treeNodeName;
      parentNode.ImageIndex = imageIndex;
      parentNode.SelectedImageIndex = imageIndex;
      this.treeViewConsentSet.Nodes.Add(parentNode);
      return parentNode;
    }

    /// <summary>
    /// 주어진 parentTreeNode에 자식노드를 추가한다
    /// </summary>
    /// <param name="parentTreeNode">부모 노드</param>
    /// <param name="consentSet">추가할 자식 노드</param>
    private void AddConsentNode(TreeNode parentTreeNode, ConsentFormListVO consentSet) {
      TreeNode childTreeNode = new TreeNode();
      childTreeNode.Text = consentSet.formName; // + "[" + consentSet.FormCd + "]";
      childTreeNode.ImageIndex = 0;
      childTreeNode.SelectedImageIndex = 0;
      childTreeNode.Tag = consentSet;
      parentTreeNode.Nodes.Add(childTreeNode);

      ContextMenuStrip strip = new ContextMenuStrip();

      ToolStripMenuItem setItemDelete = new ToolStripMenuItem();
      setItemDelete.Text = "즐겨찾기 삭제";
      strip.Items.Add(setItemDelete);
      setItemDelete.Click += new EventHandler(setItemDelete_Click);

      childTreeNode.ContextMenuStrip = strip;
    }
    /*
    private void AddDeptsConsentSet(ConsentSetVO vo)
    {
        TreeNode deptNode = this.treeViewConsentSet.Nodes["DEPT"];

        if (deptNode.Nodes.ContainsKey(vo.DeptCd))
        {
            AddConsentNode(deptNode.Nodes[vo.DeptCd], vo);
        }
        else
        {
            //해당 부서코드 노드를 생성 한다.
            TreeNode deptSubNode = new TreeNode(vo.DeptNm);
            deptSubNode.Name = vo.DeptCd;
            deptSubNode.ImageIndex = 3;
            deptSubNode.SelectedImageIndex = 3;
            deptNode.Nodes.Add(deptSubNode);

            //부서코드 노드에 동의서들을 추가한다.
            AddConsentNode(deptSubNode, vo);
        }
    }
    */
    #endregion

    #region 트리 컨트롤 이벤트            
    /// <summary>
    /// treeViewConsentSet 더블 클릭 이벤트
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="TreeNodeMouseClickEventArgs"/> instance containing the event data.</param>
    private void treeViewConsentSet_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e) {

      if (this.treeViewConsentSet.SelectedNode.Tag != null) {
        // 환자정보 체크
        // 환자정보가 없을 때 서버 request 후 오류 발생 후 프로그램 종료 발생
        if (commandControl == null) commandControl = consentMain.ConsentCommandCtrl as ConsentCommandCtrl;

        var visitType = commandControl.CurrentTargetPatient?.VisitType ?? null;

        // 방문 타입이 없다면 메시지 박스를 보여준다
        if (visitType == null) {
          MessageBoxDlg.Show(this, string.Format(Properties.Resources.msg_error_no_patient),
              string.Format(Properties.Resources.msg_caption_warn),
              MessageBoxButtons.OK,
              MessageBoxIcon.Information);
          return;
        }

        string electrVisble = ConsentMainControl.SETTING_DATA["ELECTR_CMP"];
        if (commandControl.CurrentTargetPatient.VisitType.Equals("O")) {
          if (electrVisble.Equals("Y")) {
            commandControl.setCompleteSaveButton(true);
          }
        } else {
          if (electrVisble.Equals("Y") && commandControl.CurrentEndUser.JobKindCd.Substring(0, 2).Equals("03")) {
            commandControl.setCompleteSaveButton(true);
          } else {
            commandControl.setCompleteSaveButton(false);
          }
        }

        //if (commandControl.CurrentTargetPatient.VisitType.Equals("O")) {
        //  commandControl.setCompleteSaveButton(true);
        //} else {
        //  if (ConsentMainControl.SETTING_DATA["ELECTR_CMP"].Equals("Y") && commandControl.CurrentEndUser.JobKindCd.Substring(0, 2).Equals("03")) {
        //    commandControl.setCompleteSaveButton(true);
        //  } else {
        //    commandControl.setCompleteSaveButton(false);
        //  }

        //}

        //의사가 아니면 확인저장 비활성화
        //if (!commandControl.CurrentEndUser.JobKindCd.Substring(0, 2).Equals("03")) {
        //  commandControl.setCompleteSaveButton(false);
        //}

        // 미리보기 수행
        ExecutePreviewWithSelectedConsent();
        RunConsentDualView();
        commandControl.SetEnableConsentIssueCommands(true);
        /*
        ConsentSetVO vo = this.treeViewConsentSet.SelectedNode.Tag as ConsentSetVO;

        if (vo != null)
        {
            RunConsentDualView();
        }
        */
      }
    }

    /// <summary>
    /// 트리 노드 선택해서 SET 삭제
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
    private void setItemDelete_Click(object sender, EventArgs e) {
      ConsentFormListVO vo = this.treeViewConsentSet.SelectedNode.Tag as ConsentFormListVO;

      if (vo == null) {
        return;
      }

      IConsentMain consentMain = ConsentMainControl.GetConsentMainInterface(this);
      Cursor currentCursor = this.Cursor;
      try {
        this.Cursor = Cursors.WaitCursor;

        // 동의서 SET에 추가하는 웹서비스 콜
        hospitalWebService.DelUserFormSetList(commandControl.CurrentEndUser.UserNo, vo.formCd, consentMain.ConsentExecuteInfo["dutinstcd"]);

        this.Cursor = currentCursor;
      } catch (Exception ex) {

        throw ex;
      } finally {
        InitConsentSetTreeView();
        this.Cursor = currentCursor;

      }
      MessageBox.Show(string.Format(Properties.Resources.msg_consent_set_deleted)
          , string.Format(Properties.Resources.msg_caption_confirm), MessageBoxButtons.OK, MessageBoxIcon.Information);
    }

    private void RunConsentDualView() {
      if (this.consentMain == null) consentMain = ConsentMainControl.GetConsentMainInterface(this);
      if (this.commandControl == null) commandControl = consentMain.ConsentCommandCtrl as ConsentCommandCtrl;

      commandControl.RunConsentDualView();
    }

    #endregion
  }
}
