#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: ConsentSvc.asmx.cs
//
#endregion
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Collections.Generic;
using System.Web.Services;
using System.Collections;
using IBatisNet.DataMapper;
using CLIP.eForm.Server.Data;
using CLIP.eForm.Server.VO;
using CLIP.eForm.Consent.Entity;
using CLIP.eForm.Consent.Dac;
using CLIP.eForm.Consent.Web;
using System.Security.AccessControl;
using System.IO.Compression;

namespace CLIP.eForm.Consent.WebService {
  /// <summary>
  /// 전자 동의서 관련 웹서비스
  /// </summary>
  /// <remarks>
  /// <p>[설계자]</p>
  /// <p>  클립소프트 연구소 홍지철 (jchong@clipsoft.co.kr)</p>
  /// <p>[원본 작성자]</p>
  /// <p>  클립소프트 기술부 이창훈 (chlee@clipsoft.co.kr)</p>
  /// <p>[수정 작성자]</p>
  /// <p>  클립소프트 기술부 이인희</p>
  /// <p>----------------------------------------------------------------------------------------</p>
  /// <p>[HISTORY]</p>
  /// <p> 2016-06-15	: 최초작성</p>
  /// <p>----------------------------------------------------------------------------------------</p>
  /// </remarks>

  /// <summary>
  /// ConsentSvc의 요약 설명입니다.
  /// </summary>
  [WebService(Namespace = "http://tempuri.org/")]
  [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
  [System.ComponentModel.ToolboxItem(false)]
  // ASP.NET AJAX를 사용하여 스크립트에서 이 웹 서비스를 호출하려면 다음 줄의 주석 처리를 제거합니다. 
  // [System.Web.Script.Services.ScriptService]
  public class ConsentSvc : System.Web.Services.WebService {
    private IBatisHelper _ibatisHelper;
    private static string tempImageDelStatus = string.Empty;

    public ConsentSvc() {
      _ibatisHelper = new IBatisHelper("ConsentSvcOracleMap.config");
      imageServerProps = new ImageServerProps(_ibatisHelper.GetSqlMapper());
    }

    protected override void Dispose(bool disposing) {
      if (IbatisSession != null && IbatisSession.Transaction != null) {
        IbatisSession.CommitTransaction();
        IbatisSession.CloseConnection();
      }
      if (IbatisMapper != null)
        IbatisMapper.CloseConnection();

      base.Dispose(disposing);
    }

    /// <summary>
    /// 현재 연결된 IBatis Connection을 반환
    /// </summary>
    public ISqlMapper IbatisMapper {
      get {
        if (_ibatisHelper == null) {
          return null;
        } else {
          return _ibatisHelper.GetSqlMapper();
        }
      }
    }

    /// <summary>
    /// 현재 연결된 ISqlMapSession 을 반환
    /// </summary>
    public ISqlMapSession IbatisSession {
      get {
        if (_ibatisHelper == null) {
          return null;
        } else {
          return _ibatisHelper.GetMapSession();
        }
      }
    }

    [WebMethod]
    public bool CheckWebService() {
      return true;
    }

    /// <summary>
    /// 경북대학교병원 출력 로그에 기록되지 않아야 할 목록 조회
    /// </summary>
    /// <param name="dutinstcd"></param>
    /// <returns></returns>
    [WebMethod(Description = "Type 6 인 동의서 조회")]
    public List<String> getOcrType6Forms(string dutinstcd) {
      using (SaveConsentDac dac = new SaveConsentDac()) {
        Hashtable param = new Hashtable();
        param.Add("instcd", dutinstcd);
        return (List<String>) dac.getOcrType6Forms(this.IbatisMapper, param);
      }
    }


    [WebMethod]
    public bool CheckDatabaseConnection() {
      // TODO: 데이터 베이스 커넥션 테스트 호출 필요
      return false;
    }

    /// <summary>
    /// 동의서 하위 카테고리 조회
    /// </summary>
    /// <param name="instCd"></param>
    /// <returns></returns>
    [WebMethod(Description = "동의서 하위 카테고리 조회")]
    public List<CategoryForDropdownVO> GetCategoryForDropdown(string instCd) {
      List<CategoryForDropdownVO> result;
      try {
        using (FormCategoryDac dac = new FormCategoryDac()) {
          string categoryId = "";
          if (instCd.Equals("031")) {
            categoryId = "EMA_031";
          } else {
            categoryId = "EMA_032";
          }

          Hashtable param = new Hashtable();
          param.Add("category_id", categoryId);

          result = (List<CategoryForDropdownVO>) dac.GetCategoryForDropdown(this.IbatisMapper, param);

          CategoryForDropdownVO allSubCategory = new CategoryForDropdownVO();
          allSubCategory.CategoryId = categoryId;
          allSubCategory.CategoryName = "전체";
          allSubCategory.CategoryType = "F";

          result.Insert(0, allSubCategory);
        }

        return result;
      } catch (Exception ex) {
        CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm GetCategoryForDropdown error: {0}", ex.Message));
        throw ex;
      }

    }

    ///// <summary>
    ///// 동의서 하위 카테고리 조회
    ///// </summary>
    ///// <param name="categoryId">카테고리 ID</param>
    ///// <returns></returns>
    //[WebMethod(Description = "동의서 하위 카테고리 조회")]
    //public List<CategoryForDropdownVO> GetCategoryForDropdown(string categoryId) {
    //  List<CategoryForDropdownVO> result;
    //  try {
    //    using (FormCategoryDac dac = new FormCategoryDac()) {
    //      Hashtable param = new Hashtable();
    //      param.Add("category_id", categoryId);

    //      result = (List<CategoryForDropdownVO>) dac.GetCategoryForDropdown(this.IbatisMapper, param);

    //      if (categoryId.Equals("1")) {
    //        CategoryForDropdownVO categoryForDropdownVO = new CategoryForDropdownVO();

    //        categoryForDropdownVO.CategoryType = "F";
    //        categoryForDropdownVO.CategoryId = "1CB1B494-1EF0-48BD-84D6-4965A54E6AEA";
    //        categoryForDropdownVO.CategoryName = "전체";

    //        result.Insert(0, categoryForDropdownVO);
    //      } else {
    //        CategoryForDropdownVO allSubCategory = new CategoryForDropdownVO();
    //        allSubCategory.CategoryId = categoryId;
    //        allSubCategory.CategoryName = "전체";
    //        allSubCategory.CategoryType = "F";

    //        result.Insert(0, allSubCategory);
    //      }
    //    }

    //    return result;
    //  } catch (Exception ex) {
    //    CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm GetCategoryForDropdown error: {0}", ex.Message));
    //    throw ex;
    //  }

    //}

    [WebMethod(Description = "사용자 이름에 따른 환자별 동의서 목록 조회")]
    public List<ConsentVO> GetConsentListByUserName(string username, string startDt, string endDt, string consetState, string dutinstcd) {
      List<ConsentVO> result = null;
      try {
        using (ConsentDac dac = new ConsentDac()) {
          Hashtable param = new Hashtable {
                        { "instcd", dutinstcd },
                        { "startDt", startDt },
                        { "endDt", endDt },
                        { "usename", username },
                        { "status", consetState}
                    };

          return (List<ConsentVO>) dac.GetUnfinishedListPerUserName(this.IbatisMapper, param);
        }
      } catch (Exception ex) {
        CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm GetUnfinishedListPerDoctor error: {0}", ex.Message));
        throw ex;
      }
      return result;
    }

    /// <summary>
    /// 환자, 상태에 따른 동의서 목록 검색
    /// </summary>
    /// <param name="patientCode">환자등록번호</param>
    /// <param name="startDt">데이터생성일자 조회 시작일</param>
    /// <param name="endDt">The end dt.</param>
    /// <param name="consentState">State of the conset.</param>
    /// <param name="instCd">근무지기관코드</param>
    /// <param name="userId">The user identifier.</param>
    /// <returns></returns>
    [WebMethod(Description = "환자/상태에 따른 동의서 목록 검색")]
    public List<ConsentFormListVO> GetConsentList(string patientCode, string startDt, string endDt, string consentState, string instCd
                                        , string userId) {

      List<ConsentFormListVO> result;

      try {

        // 임시저장 조회 시 미작성이 없으면 미작성 상태도 추가
        if (!string.IsNullOrEmpty(consentState)) {
          bool _hasTemp = false;
          bool _hasUnfinished = false;
          string[] _stateArr = consentState.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
          foreach (string s in _stateArr) {
            if (s.Equals("TEMP")) {
              _hasTemp = true;
            } else if (s.Equals("UNFINISHED")) {
              _hasUnfinished = true;
            }
          }

          if (_hasTemp && !_hasUnfinished) {
            consentState += ",'UNFINISHED'";
          }
        }

        using (ConsentDac dac = new ConsentDac()) {

          Hashtable param = new Hashtable {
                        { "patientCode", patientCode },
                        { "startDt", startDt },
                        { "endDt", endDt },
                        { "consentState", consentState },
                        { "instCd", instCd },
                        { "userId", userId ?? string.Empty}
                    };

          //result = (List<ConsentFormListVO>) dac.GetConsentList(this.IbatisMapper, param);
          result = (List<ConsentFormListVO>) dac.GetConsentList(this.IbatisMapper, param);
        }

        return result;

      } catch (Exception ex) {
        CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm GetConsentList error: {0}", ex.Message));
        throw ex;
      }
    }

    /// <summary>
    /// 동의서 찾기
    /// </summary>
    /// <param name="categoryId">카테고리 ID</param>
    /// <param name="keyWord">검색할 키워드</param>
    /// <param name="instCd">근무지기관코드</param>
    /// <returns></returns>
    [WebMethod(Description = "동의서 찾기(조회)")]
    public List<ConsentFormListVO> GetConsentBySearch(string categoryId, string keyWord, string instCd) {
      List<ConsentFormListVO> result;

      if (categoryId.Equals("EMA_031") || categoryId.Equals("EMA_032")) {
        categoryId = "";
      }

      try {
        using (ConsentDac dac = new ConsentDac()) {
          Hashtable param = new Hashtable();
          param.Add("categoryId", categoryId);
          param.Add("instCd", instCd);
          param.Add("keyWord", string.Format("%{0}%", keyWord));

          result = (List<ConsentFormListVO>) dac.GetConsentBySearch(this.IbatisMapper, param);
        }
        return result;
      } catch (Exception ex) {
        System.Diagnostics.Trace.WriteLine(string.Format("CLIP.eForm GetConsentBySearch error: {0}", ex.Message));
        throw ex;
      }
    }

    /// <summary>
    /// 동의서 찾기
    /// </summary>
    /// <param name="formCd">서식코드</param>
    /// <param name="instCd">근무지기관코드</param>
    /// <returns>ConsentBySearchVO 객체 List</returns>
    [WebMethod(Description = "동의서 찾기(서식코드)")]
    public ConsentFormListVO GetConsentByFormcd(string formCd, string instCd) {
      ConsentFormListVO result = new ConsentFormListVO();

      try {
        using (ConsentDac dac = new ConsentDac()) {
          Hashtable param = new Hashtable();

          //string formCdArr = "";
          //string[] cdArr = formCd.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);
          //for (int i = 0; i < cdArr.Length; i++) {
          //  formCdArr += string.Format("'{0}',", cdArr[i].Trim());
          //}
          //formCdArr = formCdArr.Remove(formCdArr.Length - 1);

          param.Add("formCd", formCd);
          param.Add("instCd", instCd);

          result = dac.GetConsentByFormcd(this.IbatisMapper, param);
        }
        return result;
      } catch (Exception ex) {
        System.Diagnostics.Trace.WriteLine(string.Format("CLIP.eForm GetConsentByFormcd error: {0}", ex.Message));
        throw ex;
      }
    }

    private class ImageServerProps {
      public string ipAddr;
      public string remotePath;
      public string user;
      public string pwd;

      public ImageServerProps(ISqlMapper IbatisMapper) {
        using (CommonCodeDac ccdac = new CommonCodeDac()) {
          IList<ImageServerPropsVO> props;
          Hashtable opts = new Hashtable();
          props = ccdac.GetImageServerProps(IbatisMapper, opts);

          foreach (var prop in props) {
            if (prop.active == "A") {
              ipAddr = prop.ipaddr;
              remotePath = prop.localpath;
              user = prop.username;
              pwd = prop.userpasswd;

              break;
            }
          }
        }
      }
    }

    ImageServerProps imageServerProps = null;

    /// <summary>
    /// CONSENT_MST_RID를 갖고 저장된 동의서 이미지를 조회
    /// </summary>
    /// <param name="consentMstRid">동의서 마스터 데이터 Rid</param>
    [WebMethod(Description = "동의서 저장된 이미지 내역 조회")]
    public List<ConsentImageVO> GetConsentImage(string consentMstRid) {
      List<ConsentImageVO> result;

      try {
        using (ConsentDac dac = new ConsentDac()) {
          Hashtable param = new Hashtable();

          int consentMstRidInt = 0;
          int.TryParse(consentMstRid, out consentMstRidInt);

          param.Add("consent-mst-rid", consentMstRidInt);
          result = (List<ConsentImageVO>) dac.GetConsentImage(this.IbatisMapper, param);

          // 사용자 ID 와 패스워드가 없다면 강제로 하드코딩 해서 기입한다
          if (imageServerProps.user == null || imageServerProps.user == "") {
            imageServerProps.user = "choiadmin";
          }
          if (imageServerProps.pwd == null || imageServerProps.pwd == "") {
            imageServerProps.pwd = "choiadmin";
          }

          var targetDrive = "";
          var destDirectory = imageServerProps.remotePath.Substring(2);
          var virtualDir = "";
          var remotePath = "";
          // 경로를 확인하여 가상 디렉토리 경로를 설정한다
          if (imageServerProps != null) {
            targetDrive = imageServerProps.remotePath.Substring(0, 1);
            switch (targetDrive) {
              case "W":
              virtualDir = "his032";
              break;
              case "Z":
              virtualDir = "his031";
              break;
            }
            remotePath = imageServerProps.remotePath;
          }

          // 계정을 choiadmin 으로 가장한다
          ClipSoft.Utility.ImpersonationUtility util = new ClipSoft.Utility.ImpersonationUtility();
          var imResult = util.ImpersonationStart(string.Empty, "choiadmin", "choiadmin");
          CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("Impersonation Start, " + imResult);

          // for debug
          DirectoryInfo destDi = new DirectoryInfo(Server.MapPath("DataTempImage"));

          var destDirStr = destDi.ToString();

          DirectoryInfo origDi = new DirectoryInfo(Server.MapPath(virtualDir));

          // 해당 경로에 디렉토리가 없다면 생성하여 준다
          if (!destDi.Exists) {
            destDi.Create();
          }

          foreach (ConsentImageVO img in result) {
            string newFileName = String.Format(@"{0}{1}", img.ImagePath.Replace("\\", ""), img.ImageFilename);
            var origDiStr = String.Format(@"{0}\{1}\{2}", origDi.ToString(),
                remotePath.Substring(remotePath.IndexOf("ACTIVE_ENC") + @"ACTIVE_ENC\".Length),
                img.ImagePath);

            // for debug
            //var origDiStr = String.Format(@"{0}\{1}\{2}\{3}",
            //    origDi.ToString(),
            //    remotePath.Substring(remotePath.IndexOf("ACTIVE_ENC") + @"ACTIVE_ENC\".Length),
            //    "consentTest",
            //    img.ImagePath);

            var origFullPath = String.Format(@"{0}\{1}", origDiStr, img.ImageFilename);
            var destFullPath = String.Format(@"{0}\{1}", destDirStr, newFileName);

            try {
              File.Copy(origFullPath, destFullPath, true);
            } catch (Exception e) {
              CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error("file copy error", e);
            }
            img.ImagePath = destDirStr;
            img.ImageFilename = newFileName;

          }

          util.ImpersonationEnd();
          CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("Impersonation end");
        }
        // ?? 왜 로컬에 있는 tempfile 들을 삭제할까?
        //int iResult = DeleteTempFile();

        return result;
      } catch (Exception ex) {
        CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm GetConsentImage error: {0}", ex.Message));
        throw ex;
      }
    }

    public byte[] xmlData(string xml) {
      UTF8Encoding encoder = new UTF8Encoding();
      Decoder utf8Decode = encoder.GetDecoder();
      byte[] toEcodeByte = Convert.FromBase64String(xml);
      //byte[] toEcodeByte = Encoding.UTF8.GetBytes(xml);
      int charCount = utf8Decode.GetCharCount(toEcodeByte, 0, toEcodeByte.Length);

      char[] decodedChar = new char[charCount];
      utf8Decode.GetChars(toEcodeByte, 0, toEcodeByte.Length, decodedChar, 0);

      return toEcodeByte;
    }

    /// <summary>
    /// 전자동의서를 임시저장 한다. 안드로이드 저장부분 http connection 변경으로 인한 임시저장 함수 신설
    /// </summary>
    /// <param name="userId">로그인 사용자ID</param>
    /// <param name="patientCode">환자 등록번호</param>
    /// <param name="clnDeptCode">진료과 코드</param>
    /// <param name="formRid">(작성대상)서식 Rid</param>
    /// <param name="formCd">서식코드</param>
    /// <param name="consentMstRid">동의서 마스터 데이터 Rid</param>
    /// <param name="rewriteConsentMstRid">재 작성 대상 동의서 마스터 데이터 Rid</param>
    /// <param name="formXml">동의서 EPT Xml</param>
    /// <param name="dataXml">동의서 Data(필드들) Xml</param>
    /// <param name="deviceType">장비 유형 (WIN, AND, IOS, PRT 중1)</param>
    /// <param name="deviceIdentNo">장비 고유 식별자</param>
    /// <param name="vistType">내원구분</param>
    /// <param name="hosType">병원 구분</param>
    /// <param name="clnDate">병원 구분이 "I" 일 경우 입원일자/병원 구분이 "O"일 경우 진료일자</param>
    /// <param name="ward">병동 코드</param>
    /// <param name="roomcd">병실 코드</param>
    /// <param name="orderNo">처방번호</param>
    /// <param name="orderName">처방명</param>
    /// <param name="orderCd">처방코드</param>
    /// <param name="ocrCode">OCR 코드</param>
    /// <param name="cretno">생성번호</param>
    /// <param name="createUserName">작성자명</param>
    /// <param name="modifyUserName">수정자명</param>
    /// <param name="mainDrId">주치의 아이디</param>
    /// <param name="userDeptCd">사용자 부서 코드</param>
    /// <param name="pageCnt">동의서 매수</param>
    /// <param name="actKind">동작코드(T: 임시 저장, C: 인증 저장, P: 출력, CP: 삭제)</param>
    /// <param name="clientType">Client구분 (P: PC, M: 모바일)</param>
    /// <param name="opRsrvNo">수술예약번호</param>
    /// <returns>
    /// CONSENT_MST_RID
    /// </returns>
    [WebMethod(Description = "동의서 임시저장 NEW")]
    public SingleReturnData SaveTempDataNew(string userId, string patientCode, string clnDeptCode, int formRid, string formCd,
                                int consentMstRid, int rewriteConsentMstRid, string formXml, string dataXml,
                                string deviceType, string deviceIdentNo, string vistType, string hosType, string clnDate,
                                string ward, string roomCd, int orderNo, string orderName, string orderCd, string ocrCode, int cretNo,
                                string createUserName, string modifyUserName, string mainDrId,
                                string userDeptCd, string pageCnt, string actKind, string clientType, string opRsrvNo,
                                string consentState) {
      SingleReturnData result = new SingleReturnData();

      byte[] formXmlbyte64 = Convert.FromBase64String(formXml);
      byte[] dataXmlbyte64 = Convert.FromBase64String(dataXml);

      formXml = Encoding.UTF8.GetString(formXmlbyte64);
      dataXml = Encoding.UTF8.GetString(dataXmlbyte64);

      int reissueConsentMstRid = 0;

      consentState = string.IsNullOrEmpty(consentState) ? "TEMP" : consentState;

      consentMstRid = SaveData(userId, patientCode, clnDeptCode, formRid, formCd,
                               consentMstRid, 0, reissueConsentMstRid, consentState, "N", formXml, dataXml,
                               deviceType, deviceIdentNo, vistType, hosType, clnDate,
                               ward, roomCd, string.Empty, orderNo, orderName, orderCd, ocrCode, cretNo,
                               createUserName, modifyUserName, null, null, null, mainDrId,
                               userDeptCd, pageCnt, actKind, clientType, opRsrvNo);

      result.responseData = Convert.ToString(consentMstRid);
      return result;
    }

    /// <summary>
    /// 전자동의서를 임시저장 한다.
    /// </summary>
    /// <param name="userId">로그인 사용자ID</param>
    /// <param name="patientCode">환자 등록번호</param>
    /// <param name="clnDeptCode">진료과 코드</param>
    /// <param name="formRid">(작성대상)서식 Rid</param>
    /// <param name="formCd">서식코드</param>
    /// <param name="consentMstRid">동의서 마스터 데이터 Rid</param>
    /// <param name="rewriteConsentMstRid">재 작성 대상 동의서 마스터 데이터 Rid</param>
    /// <param name="formXml">동의서 EPT Xml</param>
    /// <param name="dataXml">동의서 Data(필드들) Xml</param>
    /// <param name="deviceType">장비 유형 (WIN, AND, IOS, PRT 중1)</param>
    /// <param name="deviceIdentNo">장비 고유 식별자</param>
    /// <param name="vistType">내원구분</param>
    /// <param name="hosType">병원 구분</param>
    /// <param name="clnDate">병원 구분이 "I" 일 경우 입원일자/병원 구분이 "O"일 경우 진료일자</param>
    /// <param name="ward">병동 코드</param>
    /// <param name="roomcd">병실 코드</param>
    /// <param name="orderNo">처방번호</param>
    /// <param name="orderName">처방명</param>
    /// <param name="orderCd">처방코드</param>
    /// <param name="ocrCode">OCR 코드</param>
    /// <param name="cretno">생성번호</param>
    /// <param name="createUserName">작성자명</param>
    /// <param name="modifyUserName">수정자명</param>
    /// <param name="mainDrId">주치의 아이디</param>
    /// <param name="userDeptCd">사용자 부서 코드</param>
    /// <param name="pageCnt">동의서 매수</param>
    /// <param name="actKind">동작코드(T: 임시 저장, C: 인증 저장, P: 출력, CP: 삭제)</param>
    /// <param name="clientType">Client구분 (P: PC, M: 모바일)</param>
    /// <param name="opRsrvNo">수술예약번호</param>
    /// <returns>
    /// CONSENT_MST_RID
    /// </returns>
    [WebMethod(Description = "동의서 임시저장")]
    public SingleReturnData SaveTempData(string userId, string patientCode, string clnDeptCode, int formRid, string formCd,
                                int consentMstRid, int rewriteConsentMstRid, string formXml, string dataXml,
                                string deviceType, string deviceIdentNo, string vistType, string hosType, string clnDate,
                                string ward, string roomCd, int orderNo, string orderName, string orderCd, string ocrCode, int cretNo,
                                string createUserName, string modifyUserName, string mainDrId,
                                string userDeptCd, string pageCnt, string actKind, string clientType, string opRsrvNo,
                                string consentState) {
      SingleReturnData result = new SingleReturnData();



      //string orgFormXml = Unzip(formXml);
      //string orgDataXml = Unzip(dataXml);


      //dataXml = Unzip(xmlData(dataXml));
      //formXml = Unzip(xmlData(formXml));


      //string paramLog = "";
      //paramLog += "clnDept[" + userId + "]patientCode[" + patientCode + "]clnDeptCode[" + clnDeptCode + "]formRid[" + formRid + "]";
      //paramLog += "formCd[" + formCd + "]consentMstRid[" + consentMstRid + "]rewriteConsentMstRid[" + rewriteConsentMstRid + "]";
      //paramLog += "deviceType[" + deviceType + "]vistType[" + vistType + "]hosType[" + hosType + "]";
      //paramLog += "clnDate[" + clnDate + "]ward[" + ward + "]roomcd[" + roomcd + "]orderNo[" + orderNo + "]";
      //paramLog += "orderName[" + orderName + "]orderCd[" + orderCd + "]ocrCode[" + ocrCode + "]cretno[" + cretno + "]";
      //paramLog += "createUserName[" + createUserName + "]modifyUserName[" + modifyUserName + "]";
      //paramLog += "deviceIdentNo[" + deviceIdentNo + "]mainDrId[" + mainDrId + "]";
      //paramLog += "dataXml[" + dataXml + "]formXml[" + formXml + "]";

      //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("dataXml -- > " + dataXml);
      //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("formXml -- > " + formXml);

      int reissueConsentMstRid = 0;

      consentState = string.IsNullOrEmpty(consentState) ? "TEMP" : consentState;

      consentMstRid = SaveData(userId, patientCode, clnDeptCode, formRid, formCd,
                               consentMstRid, 0, reissueConsentMstRid, consentState, "N", formXml, dataXml,
                               deviceType, deviceIdentNo, vistType, hosType, clnDate,
                               ward, roomCd, string.Empty, orderNo, orderName, orderCd, ocrCode, cretNo,
                               createUserName, modifyUserName, null, null, null, mainDrId,
                               userDeptCd, pageCnt, actKind, clientType, opRsrvNo);

      result.responseData = Convert.ToString(consentMstRid);
      return result;
    }

    /// <summary>
    /// 전자 동의서를 완료저장 한다.
    /// </summary>
    /// <param name="userId">로그인 사용자ID</param>
    /// <param name="patientCode">환자 등록번호</param>
    /// <param name="clnDeptCode">진료과 코드</param>
    /// <param name="formRid">(작성대상)서식 Rid</param>
    /// <param name="formCd">서식코드</param>
    /// <param name="consentMstRid">동의서 마스터 데이터 Rid</param>
    /// <param name="rewriteConsentMstRid">재 작성 대상 동의서 마스터 데이터 Rid</param>
    /// <param name="formXml">동의서 EPT Xml</param>
    /// <param name="dataXml">동의서 Data(필드들) Xml</param>
    /// <param name="deviceType">장비 유형 (WIN, AND, IOS, PRT 중1)</param>
    /// <param name="deviceIdentNo">장비 고유 식별자</param>
    /// <param name="vistType">내원구분</param>
    /// <param name="hosType">병원 구분</param>
    /// <param name="clnDate">병원 구분이 "I" 일 경우 입원일자/병원 구분이 "O"일 경우 진료일자</param>
    /// <param name="ward">병동 코드</param>
    /// <param name="roomcd">병실 코드</param>
    /// <param name="orderNo">처방번호</param>
    /// <param name="orderName">처방명</param>
    /// <param name="orderCd">처방코드</param>
    /// <param name="ocrCode">The ocr code.</param>
    /// <param name="cretno">The cretno.</param>
    /// <param name="createUserName">작성자명</param>
    /// <param name="modifyUserName">수정자명</param>
    /// <param name="mainDrId">주치의 아이디</param>
    /// <param name="userDeptCd">사용자 부서 코드</param>
    /// <param name="pageCnt">출력 매수</param>
    /// <param name="actKind">동작 코드</param>
    /// <param name="clientType">Client 구분</param>
    /// <param name="opRsrvNo">수술 예약 번호</param>
    /// <returns></returns>l
    [WebMethod(Description = "동의서 서명 완료")]
    public int SaveComplete(string userId, string patientCode, string clnDeptCode, int formRid, string formCd,
                                int consentMstRid, int rewriteConsentMstRid, string formXml, string dataXml,
                                string deviceType, string deviceIdentNo, string vistType, string hosType, string clnDate,
                                string ward, string roomcd, int orderNo, string orderName, string orderCd, string ocrCode, int cretno,
                                string createUserName, string modifyUserName, string mainDrId,
                                string userDeptCd, string pageCnt, string actKind, string clientType, string opRsrvNo) {
      int reissueConsentMstRid = 0;
      string consentState = "ELECTR_CMP";
      string paperYn = "N";
      string reasonForUseN = string.Empty;

      rewriteConsentMstRid = 0;
      consentMstRid = SaveData(userId, patientCode, clnDeptCode, formRid, formCd,
                               consentMstRid, rewriteConsentMstRid, reissueConsentMstRid, consentState, paperYn, formXml, dataXml,
                               deviceType, deviceIdentNo, vistType, hosType, clnDate,
                               ward, roomcd, reasonForUseN, orderNo, orderName, orderCd, ocrCode, cretno,
                               createUserName, modifyUserName, null, null, null, mainDrId,
                               userDeptCd, pageCnt, actKind, clientType, opRsrvNo);

      return consentMstRid;
    }

    /// <summary>
    /// 전자 동의서를 완료저장 한다. 안드로이드 저장부분 http connection 변경으로 인한 인증, 확인 함수 신설
    /// </summary>
    /// <param name="userId">로그인 사용자ID</param>
    /// <param name="patientCode">환자 등록번호</param>
    /// <param name="clnDeptCode">진료과 코드</param>
    /// <param name="formRid">(작성대상)서식 Rid</param>
    /// <param name="formCd">서식코드</param>
    /// <param name="consentMstRid">동의서 마스터 데이터 Rid</param>
    /// <param name="rewriteConsentMstRid">재 작성 대상 동의서 마스터 데이터 Rid</param>
    /// <param name="formXml">동의서 EPT Xml</param>
    /// <param name="dataXml">동의서 Data(필드들) Xml</param>
    /// <param name="deviceType">장비 유형 (WIN, AND, IOS, PRT 중1)</param>
    /// <param name="deviceIdentNo">장비 고유 식별자</param>
    /// <param name="vistType">내원구분</param>
    /// <param name="hosType">병원 구분</param>
    /// <param name="clnDate">병원 구분이 "I" 일 경우 입원일자/병원 구분이 "O"일 경우 진료일자</param>
    /// <param name="ward">병동 코드</param>
    /// <param name="roomcd">병실 코드</param>
    /// <param name="orderNo">처방번호</param>
    /// <param name="orderCd">처방코드</param>
    /// <param name="orderName">처방명</param>
    /// <param name="createUserName">작성자명</param>
    /// <param name="modifyUserName">수정자명</param>
    /// <param name="imageFileJson">이미지 파일 정보(전자동의서 서버)</param>
    /// <param name="certTarget">이미지 파일 공인인증 대상정보</param>
    /// <param name="certResult">이미지 파일 공인인증 처리정보</param>
    /// <param name="dschdd">퇴원일자</param>
    /// <param name="consentState">상태</param>
    /// <param name="mainDrId">주치의 아이디</param>
    /// <param name="userDeptCd">사용자 부서 코드</param>
    /// <param name="pageCnt">동의서 매수</param>
    /// <param name="actKind">동작코드(T: 임시 저장, C: 인증 저장, P: 출력, CP: 삭제)</param>
    /// <param name="clientType">Client구분 (P: PC, M: 모바일)</param>
    /// <param name="fileSize">이미지 파일 사이즈</param>
    [WebMethod(Description = "동의서 서명 완료 NEW")]
    public SingleReturnData SaveCompleteAllNew(string userId, string patientCode, string clnDeptCode, int formRid, string formCd,
                              int consentMstRid, int rewriteConsentMstRid, string formXml, string dataXml,
                              string deviceType, string deviceIdentNo, string vistType, string hosType, string clnDate,
                              string ward, string roomCd, int orderNo, string orderName, string orderCd, string ocrCode, int cretNo,
                              string createUserName, string modifyUserName, string imageFileJson, string certTarget, string certResult,
                              string dschDd, string consentState, string mainDrId,
                              string userDeptCd, string pageCnt, string actKind, string clientType, string opRsrvNo, string fileSize) {

      SingleReturnData result = new SingleReturnData();

      int reissueConsentMstRid = 0;
      string paperYn = "N";
      string reasonForUseN = string.Empty;

      byte[] formXmlbyte64 = Convert.FromBase64String(formXml);
      byte[] dataXmlbyte64 = Convert.FromBase64String(dataXml);

      formXml = Encoding.UTF8.GetString(formXmlbyte64);
      dataXml = Encoding.UTF8.GetString(dataXmlbyte64);

      rewriteConsentMstRid = 0;
      consentMstRid = SaveDataAll(userId, patientCode, clnDeptCode, formRid, formCd,
                               consentMstRid, rewriteConsentMstRid, reissueConsentMstRid, consentState, paperYn, formXml, dataXml,
                               deviceType, deviceIdentNo, vistType, hosType, clnDate,
                               ward, roomCd, reasonForUseN, orderNo, orderName, orderCd, ocrCode, cretNo,
                               createUserName, modifyUserName, imageFileJson, certTarget, certResult, dschDd, mainDrId,
                               userDeptCd, pageCnt, actKind, clientType, opRsrvNo, fileSize);

      result.responseData = Convert.ToString(consentMstRid);
      return result;
    }

    /// <summary>
    /// 전자 동의서를 완료저장 한다.
    /// </summary>
    /// <param name="userId">로그인 사용자ID</param>
    /// <param name="patientCode">환자 등록번호</param>
    /// <param name="clnDeptCode">진료과 코드</param>
    /// <param name="formRid">(작성대상)서식 Rid</param>
    /// <param name="formCd">서식코드</param>
    /// <param name="consentMstRid">동의서 마스터 데이터 Rid</param>
    /// <param name="rewriteConsentMstRid">재 작성 대상 동의서 마스터 데이터 Rid</param>
    /// <param name="formXml">동의서 EPT Xml</param>
    /// <param name="dataXml">동의서 Data(필드들) Xml</param>
    /// <param name="deviceType">장비 유형 (WIN, AND, IOS, PRT 중1)</param>
    /// <param name="deviceIdentNo">장비 고유 식별자</param>
    /// <param name="vistType">내원구분</param>
    /// <param name="hosType">병원 구분</param>
    /// <param name="clnDate">병원 구분이 "I" 일 경우 입원일자/병원 구분이 "O"일 경우 진료일자</param>
    /// <param name="ward">병동 코드</param>
    /// <param name="roomcd">병실 코드</param>
    /// <param name="orderNo">처방번호</param>
    /// <param name="orderCd">처방코드</param>
    /// <param name="orderName">처방명</param>
    /// <param name="createUserName">작성자명</param>
    /// <param name="modifyUserName">수정자명</param>
    /// <param name="imageFileJson">이미지 파일 정보(전자동의서 서버)</param>
    /// <param name="certTarget">이미지 파일 공인인증 대상정보</param>
    /// <param name="certResult">이미지 파일 공인인증 처리정보</param>
    /// <param name="dschdd">퇴원일자</param>
    /// <param name="consentState">상태</param>
    /// <param name="mainDrId">주치의 아이디</param>
    /// <param name="userDeptCd">사용자 부서 코드</param>
    /// <param name="pageCnt">동의서 매수</param>
    /// <param name="actKind">동작코드(T: 임시 저장, C: 인증 저장, P: 출력, CP: 삭제)</param>
    /// <param name="clientType">Client구분 (P: PC, M: 모바일)</param>
    /// <param name="fileSize">이미지 파일 사이즈</param>
    [WebMethod(Description = "동의서 서명 완료")]
    public SingleReturnData SaveCompleteAll(string userId, string patientCode, string clnDeptCode, int formRid, string formCd,
                              int consentMstRid, int rewriteConsentMstRid, string formXml, string dataXml,
                              string deviceType, string deviceIdentNo, string vistType, string hosType, string clnDate,
                              string ward, string roomCd, int orderNo, string orderName, string orderCd, string ocrCode, int cretNo,
                              string createUserName, string modifyUserName, string imageFileJson, string certTarget, string certResult,
                              string dschDd, string consentState, string mainDrId,
                              string userDeptCd, string pageCnt, string actKind, string clientType, string opRsrvNo, string fileSize) {

      SingleReturnData result = new SingleReturnData();

      //string paramLog = "";
      //paramLog += "clnDept[" + userId + "]patientCode[" + patientCode + "]clnDeptCode[" + clnDeptCode + "]formRid[" + formRid + "]";
      //paramLog += "formCd[" + formCd + "]consentMstRid[" + consentMstRid + "]rewriteConsentMstRid[" + rewriteConsentMstRid + "]";
      //paramLog += "deviceType[" + deviceType + "]vistType[" + vistType + "]hosType[" + hosType + "]";
      //paramLog += "clnDate[" + clnDate + "]ward[" + ward + "]roomcd[" + roomCd + "]orderNo[" + orderNo + "]";
      //paramLog += "orderName[" + orderName + "]orderCd[" + orderCd + "]ocrCode[" + ocrCode + "]cretno[" + cretNo + "]";
      //paramLog += "createUserName[" + createUserName + "]modifyUserName[" + modifyUserName + "]imageFileJson[" + imageFileJson + "]certTarget[" + certTarget + "]";
      //paramLog += "dschdd[" + dschDd + "]consentState[" + consentState + "]mainDrId[" + mainDrId + "]";
      //paramLog += "dataXml[" + dataXml + "]formXml[" + formXml + "]certResult[" + certResult + "]" + "fileSize[" + fileSize + "]";
      //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("CLIP.eForm SaveCompleteAll param : " + paramLog);
      //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("json : " + imageFileJson);

      int reissueConsentMstRid = 0;
      string paperYn = "N";
      string reasonForUseN = string.Empty;

      rewriteConsentMstRid = 0;
      consentMstRid = SaveDataAll(userId, patientCode, clnDeptCode, formRid, formCd,
                               consentMstRid, rewriteConsentMstRid, reissueConsentMstRid, consentState, paperYn, formXml, dataXml,
                               deviceType, deviceIdentNo, vistType, hosType, clnDate,
                               ward, roomCd, reasonForUseN, orderNo, orderName, orderCd, ocrCode, cretNo,
                               createUserName, modifyUserName, imageFileJson, certTarget, certResult, dschDd, mainDrId,
                               userDeptCd, pageCnt, actKind, clientType, opRsrvNo, fileSize);

      result.responseData = Convert.ToString(consentMstRid);
      return result;
    }

    /// <summary>
    /// 동의서 삭제/폐기 데이터를 저장 한다.
    /// </summary>
    /// <param name="userId">로그인 사용자ID</param>
    /// <param name="consentMstRidInt">The consent MST rid int.</param>
    /// <param name="patientCode">환자 등록번호</param>
    /// <param name="clnDeptCode">진료과 코드</param>
    /// <param name="ward">병동 코드</param>
    /// <param name="roomcd">The roomcd.</param>
    /// <param name="formRid">(작성대상)서식 Rid</param>
    /// <param name="formCd">서식 코드</param>
    /// <param name="rewriteConsentMstRid">재 작성 대상 동의서 마스터 데이터 Rid</param>
    /// <param name="reissueConsentMstRid">삭제/폐기 대상 동의서 마스터 데이터 Rid</param>
    /// <param name="consentState">동의서 상태</param>
    /// <param name="deviceIdentNo">장비 고유 식별자</param>
    /// <param name="vistType">진료 형태</param>
    /// <param name="hosType">기관 코드</param>
    /// <param name="clnDate">진료일</param>
    /// <param name="reasonForUseN">삭제/폐기 사유</param>
    /// <param name="ocrCode">OCR Tag</param>
    /// <param name="cretno">생성번호</param>
    /// <param name="userDeptCd">사용자 부서 코드</param>
    /// <param name="pageCnt">동의서 매수</param>
    /// <param name="actKind">동작코드(T: 임시 저장, C: 인증 저장, P: 출력, CP: 삭제)</param>
    /// <param name="clientType">Client구분 (P: PC, M: 모바일)</param>
    /// <returns></returns>
    [WebMethod(Description = "동의서 삭제/폐기 데이터를 저장")]
    public SingleReturnData SaveDelete(string userId, int consentMstRid, string patientCode, string clnDeptCode, string formCd,
                            string vistType, string hosType, string clnDate, string reasonForUseN,
                            string ocrCode, int cretno, string userDeptCd, string pageCnt, string actKind, string clientType) {

      SingleReturnData result = new SingleReturnData();

      if (this.IbatisSession.IsTransactionStart == false) {
        this.IbatisSession.BeginTransaction();
      }

      try {
        using (SaveConsentDac dac = new SaveConsentDac()) {
          Hashtable param = new Hashtable();
          param.Add("userId", userId);
          param.Add("reasonForUseN", reasonForUseN);
          param.Add("consentMstRid", consentMstRid);
          param.Add("ocrTag", ocrCode);

          int resultInt = dac.UpdateConsentMstForDelete(this.IbatisMapper, param);
          CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Warn("Update resultInt -- > " + resultInt);

          if (resultInt > 0) {

            resultInt = dac.DeleteChartpageT(this.IbatisMapper, param);
            CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Warn("Delete resultInt -- > " + resultInt);

            Hashtable ocrParam = new Hashtable {
                        { "instcd", hosType },
                        { "ocrtag", ocrCode },
                        { "pid", patientCode },
                        { "ordtype", vistType },
                        { "orddd", clnDate },
                        { "cretno", cretno },
                        { "orddrid", null },
                        { "orddeptcd", clnDeptCode },
                        { "formcd", formCd },
                        { "fstprntdeptcd", userDeptCd },
                        { "fstprntid", userId },
                        { "updtdeptcd", userDeptCd },
                        { "updtuserid", userId },
                        { "updtdt", DateTime.Now.ToString("yyyyMMddHHmmss")},
                        { "pagecnt", pageCnt },
                        { "updtresncnts", reasonForUseN },
                        { "actkind", actKind },
                        { "clienttype", clientType },
                        { "endYn", "N" }
                    };

            dac.InsertPrintData(this.IbatisMapper, ocrParam);

          } else {
            if (this.IbatisSession != null) this.IbatisSession.RollBackTransaction();
            consentMstRid = -1;
          }
          
        }
      } catch (Exception ex) {
        if (this.IbatisSession != null) this.IbatisSession.RollBackTransaction();
        CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm SaveDelete ERROR : [{0}]", ex.ToString()));
        consentMstRid = -1;
      }

      result.responseData = Convert.ToString(consentMstRid);
      return result;
    }

    public List<ConsentVO> GetConsentData(string patientCode, int consentMstRid, string startDt, string endDt, string dutinstcd
                                    , string userId) {
      List<ConsentVO> result;
      try {

        using (ConsentDac dac = new ConsentDac()) {

          Hashtable param = new Hashtable {
                        { "patientCode", patientCode },
                        { "consentMstRid", consentMstRid },
                        { "startDt", startDt },
                        { "endDt", endDt },
                        { "consentState", "'UNFINISHED', 'TEMP'" },
                        { "instcd", dutinstcd },
                        { "userId", userId ?? string.Empty}
                    };

          result = (List<ConsentVO>) dac.GetConsentList(this.IbatisMapper, param);
        }

        return result;

      } catch (Exception ex) {
        System.Diagnostics.Trace.WriteLine(string.Format("CLIP.eForm GetConsentList error: {0}", ex.Message));
        throw ex;
      }
    }

    /// <summary>
    /// 프린트 출력 후 데이터를 저장 한다.
    /// </summary>
    /// <param name="userId">로그인 사용자ID</param>
    /// <param name="patientCode">환자 등록번호</param>
    /// <param name="clnDeptCode">진료과 코드</param>
    /// <param name="formRid">(작성대상)서식 Rid</param>
    /// <param name="formCd">서식코드</param>
    /// <param name="consentMstRid">동의서 마스터 데이터 Rid</param>
    /// <param name="reissueConsentMstRid">The reissue consent MST rid.</param>
    /// <param name="formXml">동의서 EPT Xml</param>
    /// <param name="dataXml">동의서 Data(필드들) Xml</param>
    /// <param name="deviceType">장비 유형 (WIN, AND, IOS, PRT 중1)</param>
    /// <param name="deviceIdentNo">장비 고유 식별자</param>
    /// <param name="vistType">내원구분</param>
    /// <param name="hosType">병원 구분</param>
    /// <param name="clnDate">병원 구분이 "I" 일 경우 입원일자/병원 구분이 "O"일 경우 진료일자</param>
    /// <param name="ward">병동 코드</param>
    /// <param name="roomcd">병실 코드</param>
    /// <param name="orderNo">처방번호</param>
    /// <param name="orderName">처방명</param>
    /// <param name="orderCd">처방코드</param>
    /// <param name="ocrCode">OCR코드</param>
    /// <param name="cretno">생성번호</param>
    /// <param name="createUserName">작성자명</param>
    /// <param name="modifyUserName">수정자명</param>
    /// <param name="mainDrId">주치의 아이디</param>
    /// <param name="userDeptCd">사용자 부서 코드</param>
    /// <param name="pageCnt">출력 매수</param>
    /// <param name="actKind">동작 방법</param>
    /// <param name="clientType">Client 타입</param>
    /// <param name="opRsrvNo">수술예약번호</param>
    /// <returns></returns>
    [WebMethod(Description = "동의서 프린트 출력 후 데이터를 저장")]
    public int SavePrintOut(string userId, string patientCode, string clnDeptCode, int formRid, string formCd,
                                int consentMstRid, int reissueConsentMstRid, string formXml, string dataXml,
                                string deviceType, string deviceIdentNo, string vistType, string hosType, string clnDate,
                                string ward, string roomcd, int orderNo, string orderName, string orderCd, string ocrCode, int cretno,
                                string createUserName, string modifyUserName, string mainDrId,
                                string userDeptCd, string pageCnt, string actKind, string clientType, string opRsrvNo) {
      string consentState = "PAPER_OUT";
      string paperYn = "Y";

      consentMstRid = SavePrintData(userId, patientCode, clnDeptCode, formRid, formCd,
                                       consentMstRid, 0, reissueConsentMstRid, consentState, paperYn, formXml, dataXml,
                                       deviceType, deviceIdentNo, vistType, hosType, clnDate,
                                       ward, roomcd, null, orderNo, orderName, orderCd, ocrCode, cretno,
                                       createUserName, modifyUserName, null, null, null, mainDrId,
                                       userDeptCd, pageCnt, actKind, clientType, opRsrvNo);

      return consentMstRid;
    }

    /// <summary>
    /// 동의서의 기왕력 데이터 저장
    /// </summary>
    /// <param name="patientCode">환자 등록번호</param>
    /// <param name="clnDate">진료일</param>
    /// <param name="bp">고/저혈압</param>
    /// <param name="dm">당뇨병</param>
    /// <param name="heart">심장질환</param>
    /// <param name="kidney">신장질환</param>
    /// <param name="respiration">호흡기질환</param>
    /// <param name="hx">과거병력</param>
    /// <param name="allergy">알레르기</param>
    /// <param name="drug">복용약물</param>
    /// <param name="smoking">흡연상태</param>
    /// <param name="idio">특이체질</param>
    /// <param name="nacrotics">마약사고</param>
    /// <param name="airway">기도이상 유무</param>
    /// <param name="hemorrhage">출혈소인</param>
    /// <param name="status_etc">기타</param>
    /// <param name="userId">로그인 사용자ID</param>
    /// <returns></returns>
    [WebMethod(Description = "동의서의 기왕력 데이터 저장")]
    public string SaveMedicalHistory(string patientCode, string clnDate,
                                string bp, string dm, string heart, string kidney, string respiration,
                                string hx, string allergy, string drug, string smoking,
                                string idio, string nacrotics, string airway, string hemorrhage, string status_etc,
                                string userId) {
      try {
        using (SaveConsentDac dac = new SaveConsentDac()) {
          Hashtable paramHashTable = new Hashtable();
          paramHashTable.Add("patientCode", patientCode);
          paramHashTable.Add("clnDate", clnDate);
          paramHashTable.Add("bp", bp);
          paramHashTable.Add("dm", dm);
          paramHashTable.Add("heart", heart);
          paramHashTable.Add("kidney", kidney);
          paramHashTable.Add("respiration", respiration);
          paramHashTable.Add("hx", hx);
          paramHashTable.Add("allergy", allergy);
          paramHashTable.Add("drug", drug);
          paramHashTable.Add("smoking", smoking);
          paramHashTable.Add("idio", idio);
          paramHashTable.Add("nacrotics", nacrotics);
          paramHashTable.Add("airway", airway);
          paramHashTable.Add("hemorrhage", hemorrhage);
          paramHashTable.Add("status_etc", status_etc);
          paramHashTable.Add("userId", userId);

          dac.SetMediHistory(this.IbatisMapper, paramHashTable);
        }
      } catch (Exception ex) {
        if (this.IbatisSession != null) this.IbatisSession.RollBackTransaction();
        CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm SaveMedicalHistory ERROR : [{0}]", ex.ToString()));
        throw ex;
      } finally {
      }
      return patientCode;
    }

    /// <summary>
    /// 동의서 서명 완료일 경우 이미지 데이터 저장
    /// </summary>
    /// <param name="consentState">동의서 상태</param>
    /// <param name="imageFileName">이미지파일명(경로포함)</param>
    /// <param name="consentMstRid">동의서 마스터 데이터 Rid</param>
    /// <param name="userId">등록자ID</param>
    /// <param name="formRid">동의서 FORM ID</param>
    /// <returns>저장된 consent image rid</returns>
    [WebMethod(Description = "동의서 서명 완료일 경우 이미지 데이터 저장")]
    public int SaveImageUploadInfo(string consentState, string imageFileName, int consentMstRid, string userId, int formRid) {
      int consentImageRid = 0;

      if (!string.IsNullOrEmpty(consentState) && consentState == "ELECTR_CMP") {
        using (SaveConsentDac dac = new SaveConsentDac()) {
          Hashtable imageHashTable = new Hashtable();

          imageHashTable.Add("consentMstRid", consentMstRid);

          consentImageRid = this.GetSequence("CONSENT_IMAGE");
          imageHashTable.Add("consentImageRid", consentImageRid);

          imageHashTable.Add("userId", userId);
          imageHashTable.Add("formRid", formRid);

          imageHashTable.Add("imagePath", imageFileName.Substring(0, imageFileName.LastIndexOf("\\")));
          imageHashTable.Add("imageFilename", imageFileName.Substring(imageFileName.LastIndexOf("\\") + 1));
          imageHashTable.Add("completeYn", "Y"); //paramHashTable["completeYn"]

          dac.InsertConsentImage(this.IbatisMapper, imageHashTable);
        }
      }

      return consentImageRid;
    }

    /// <summary>
    /// 서명완료된 이미지의 hash 정보 저장
    /// </summary>
    /// <param name="consentState">동의서 상태</param>
    /// <param name="consentMstRid">동의서 마스터 데이터 Rid</param>
    /// <param name="consentImageRid">이미지 데이터 Rid</param>
    /// <param name="userId">등록자ID</param>
    /// <param name="certTarget">hash 정보</param>
    /// <param name="sCertResult">공인인증서명 결과</param>
    [WebMethod(Description = "서명완료된 이미지의 hash 정보 저장")]
    public void SaveImageSignInfo(string consentState, int consentMstRid, int consentImageRid, string userId, string certTarget, string sCertResult) {
      string paramLog = "";
      paramLog += "consentState[" + consentState + "]consentMstRid[" + consentMstRid + "]consentImageRid[" + consentImageRid + "]userId[" + userId + "]";
      paramLog += "certTarget[" + certTarget + "]sCertResult[" + sCertResult + "]";
      //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("CLIP.eForm SaveTempData param : " + paramLog);
      if (!string.IsNullOrEmpty(consentState) && consentState == "ELECTR_CMP") {
        using (SaveConsentDac dac = new SaveConsentDac()) {
          Hashtable imageHashTable = new Hashtable();

          imageHashTable.Add("consentMstRid", consentMstRid);
          imageHashTable.Add("consentImageRid", consentImageRid);
          imageHashTable.Add("certTarget", certTarget);
          imageHashTable.Add("certResult", sCertResult);
          imageHashTable.Add("userId", userId);

          dac.InsertConsentImageSign(this.IbatisMapper, imageHashTable);
          imageHashTable.Add("consentState", "CERTIFY_CMP");
          dac.UpdateConsentMstStatus(this.IbatisMapper, imageHashTable);

        }
      }
    }

    /// <summary>
    /// Saves the data.
    /// </summary>
    /// <param name="userId">The user identifier.</param>
    /// <param name="patientCode">The patient code.</param>
    /// <param name="clnDeptCode">The CLN dept code.</param>
    /// <param name="formRid">The form rid.</param>
    /// <param name="formCd">The form cd.</param>
    /// <param name="consentMstRid">The consent MST rid.</param>
    /// <param name="rewriteConsentMstRid">The rewrite consent MST rid.</param>
    /// <param name="reissueConsentMstRid">The reissue consent MST rid.</param>
    /// <param name="consentState">State of the consent.</param>
    /// <param name="paperYn">The paper yn.</param>
    /// <param name="formXml">The form XML.</param>
    /// <param name="dataXml">The data XML.</param>
    /// <param name="deviceType">Type of the device.</param>
    /// <param name="deviceIdentNo">The device ident no.</param>
    /// <param name="vistType">Type of the vist.</param>
    /// <param name="hosType">Type of the hos.</param>
    /// <param name="clnDate">The CLN date.</param>
    /// <param name="ward">The ward.</param>
    /// <param name="roomcd">The roomcd.</param>
    /// <param name="reasonForUseN">The reason for use n.</param>
    /// <param name="orderNo">The order no.</param>
    /// <param name="orderName">Name of the order.</param>
    /// <param name="orderCd">The order cd.</param>
    /// <param name="ocrCode">The ocr code.</param>
    /// <param name="cretno">The cretno.</param>
    /// <param name="createUserName">Name of the create user.</param>
    /// <param name="modifyUserName">Name of the modify user.</param>
    /// <param name="imageFileName">Name of the image file.</param>
    /// <param name="certTarget">The cert target.</param>
    /// <param name="certResult">The cert result.</param>
    /// <param name="mainDrId">The main dr identifier.</param>
    /// <param name="userDeptCd">The user dept cd.</param>
    /// <param name="pageCnt">The page count.</param>
    /// <param name="actKind">Kind of the act.</param>
    /// <param name="clientType">Type of the client.</param>
    /// <param name="opRsrvNo">The op RSRV no.</param>
    /// <returns></returns>
    private int SaveData(string userId, string patientCode, string clnDeptCode, int formRid, string formCd,
                                       int consentMstRid, int rewriteConsentMstRid, int reissueConsentMstRid, string consentState, string paperYn, string formXml, string dataXml,
                                       string deviceType, string deviceIdentNo, string vistType, string hosType, string clnDate,
                                       string ward, string roomcd, string reasonForUseN, int orderNo, string orderName, string orderCd, string ocrCode, int cretno,
                                       string createUserName, string modifyUserName, string imageFileName, string certTarget, string certResult,
                                       string mainDrId, string userDeptCd, string pageCnt, string actKind, string clientType, string opRsrvNo) {

      bool isNewConsentMasterCase = false;
      if (consentMstRid < 1) {
        isNewConsentMasterCase = true;
      }

      try {
        using (SaveConsentDac dac = new SaveConsentDac()) {

          Hashtable paramHashTable = GetParamHashTable(userId, patientCode, clnDeptCode, formRid, formCd, consentMstRid, rewriteConsentMstRid,
                                                       reissueConsentMstRid, consentState, paperYn, formXml, dataXml, deviceType, deviceIdentNo,
                                                       vistType, hosType, clnDate, ward, roomcd, reasonForUseN,
                                                       orderNo, orderName, orderCd, ocrCode, cretno, createUserName, modifyUserName,
                                                       certTarget, certResult, mainDrId, opRsrvNo);

          consentMstRid = (int) paramHashTable["consentMstRid"];
          String endYn = "N";
          if (consentState.Equals("TEMP")) {
            endYn = "N";
          }

          //새로 작성하는 경우
          if (isNewConsentMasterCase) {
            //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("");
            dac.InsertConsentMst(this.IbatisMapper, paramHashTable);
            dac.InsertConsentData(this.IbatisMapper, paramHashTable);

          } else { //새로 작성 아닌 경우

            if (reissueConsentMstRid > 0) {

              if (string.IsNullOrEmpty(reasonForUseN)) {
                //종이->종이 재발행 
                int newConsentMstRid = this.GetSequence("CONSENT_MST");
                paramHashTable["consentMstRid"] = newConsentMstRid;
                consentMstRid = newConsentMstRid;

                dac.InsertConsentMst(this.IbatisMapper, paramHashTable);
                dac.InsertConsentData(this.IbatisMapper, paramHashTable);

              } else { // 삭제

                dac.UpdateConsentMstForDelete(this.IbatisMapper, paramHashTable);

              }

            } else { //임시저장 또는 저장인 경우

              dac.UpdateConsentMst(this.IbatisMapper, paramHashTable);
              dac.InsertConsentData(this.IbatisMapper, paramHashTable);

            }
          }

          // OCR 테이블 연계
          Hashtable ocrParam = new Hashtable {
                        { "instcd", hosType },
                        { "ocrtag", ocrCode },
                        { "pid", patientCode },
                        { "ordtype", vistType },
                        { "orddd", clnDate },
                        { "cretno", cretno },
                        { "orddrid", mainDrId },
                        { "orddeptcd", clnDeptCode },
                        { "formcd", formCd },
                        { "fstprntdeptcd", userDeptCd },
                        { "fstprntid", userId },
                        { "updtdeptcd", userDeptCd },
                        { "updtuserid", userId },
                        { "updtdt", DateTime.Now.ToString("yyyyMMddHHmmss")},
                        { "pagecnt", pageCnt },
                        { "updtresncnts", reasonForUseN },
                        { "actkind", actKind },
                        { "clienttype", clientType },
                        { "endYn", endYn }
                    };

          dac.InsertPrintData(this.IbatisMapper, ocrParam);

          // 사용 안함
          /*
          if (!string.IsNullOrEmpty(dataXml)) {
              Dictionary<string, string> outputDataDic = DataXmlToDictionary(dataXml);

              Hashtable paramHashTableForMediHistory = new Hashtable();
              paramHashTableForMediHistory.Add("patientCode", patientCode);
              paramHashTableForMediHistory.Add("clnDate", clnDate.Replace("-", ""));
              paramHashTableForMediHistory.Add("bp", outputDataDic.ContainsKey("IO_bp") ? outputDataDic["IO_bp"] : "");
              paramHashTableForMediHistory.Add("dm", outputDataDic.ContainsKey("IO_dm") ? outputDataDic["IO_dm"] : "");
              paramHashTableForMediHistory.Add("heart", outputDataDic.ContainsKey("IO_heart") ? outputDataDic["IO_heart"] : "");
              paramHashTableForMediHistory.Add("kidney", outputDataDic.ContainsKey("IO_kidney") ? outputDataDic["IO_kidney"] : "");
              paramHashTableForMediHistory.Add("respiration", outputDataDic.ContainsKey("IO_respiration") ? outputDataDic["IO_respiration"] : "");
              paramHashTableForMediHistory.Add("hx", outputDataDic.ContainsKey("IO_hx") ? outputDataDic["IO_hx"] : "");
              paramHashTableForMediHistory.Add("allergy", outputDataDic.ContainsKey("IO_allergy") ? outputDataDic["IO_allergy"] : "");
              paramHashTableForMediHistory.Add("drug", outputDataDic.ContainsKey("IO_drug") ? outputDataDic["IO_drug"] : "");
              paramHashTableForMediHistory.Add("smoking", outputDataDic.ContainsKey("IO_smoking") ? outputDataDic["IO_smoking"] : "");
              paramHashTableForMediHistory.Add("idio", outputDataDic.ContainsKey("IO_idio") ? outputDataDic["IO_idio"] : "");
              paramHashTableForMediHistory.Add("nacrotics", outputDataDic.ContainsKey("IO_nacrotics") ? outputDataDic["IO_nacrotics"] : "");
              paramHashTableForMediHistory.Add("airway", outputDataDic.ContainsKey("IO_airway") ? outputDataDic["IO_airway"] : "");
              paramHashTableForMediHistory.Add("hemorrhage", outputDataDic.ContainsKey("IO_hemorrhage") ? outputDataDic["IO_hemorrhage"] : "");
              paramHashTableForMediHistory.Add("status_etc", outputDataDic.ContainsKey("IO_status_etc") ? outputDataDic["IO_status_etc"] : "");
              paramHashTableForMediHistory.Add("userId", userId);

              dac.SetMediHistory(this.IbatisMapper, paramHashTableForMediHistory);
          }
          */
        }
      } catch (Exception ex) {
        if (this.IbatisSession != null) this.IbatisSession.RollBackTransaction();
        CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm SaveData ERROR : [{0}]", ex.ToString()));
        return -1;
        throw ex;
      } finally {
      }
      return consentMstRid;
    }

    private int SaveDataAll(string userId, string patientCode, string clnDeptCode, int formRid, string formCd,
                                       int consentMstRid, int rewriteConsentMstRid, int reissueConsentMstRid, string consentState, string paperYn, string formXml, string dataXml,
                                       string deviceType, string deviceIdentNo, string vistType, string hosType, string clnDate,
                                       string ward, string roomcd, string reasonForUseN, int orderNo, string orderName, string orderCd, string ocrCode, int cretno,
                                       string createUserName, string modifyUserName, string imageFileJson, string certTarget,
                                       string certResult, string dschdd, string mainDrId,
                                       string userDeptCd, string pageCnt, string actKind, string clientType, string opRsrvNo, string fileSize) {

      string endYn = "";
      bool isNewConsentMasterCase = false;
      if (consentMstRid < 1) {
        isNewConsentMasterCase = true;
      }

      // CERTIFY_CMP 인증저장, ELECTR_CMP 확인저장
      if (consentState.Equals("CERTIFY_CMP")) {
        endYn = "Y";
      } else if (consentState.Equals("ELECTR_CMP")) {
        endYn = "C";
      }

      try {
        using (SaveConsentDac dac = new SaveConsentDac()) {
          Hashtable paramHashTable = GetParamHashTable(userId, patientCode, clnDeptCode, formRid, formCd, consentMstRid, rewriteConsentMstRid,
                                                       reissueConsentMstRid, consentState, paperYn, formXml, dataXml, deviceType, deviceIdentNo,
                                                       vistType, hosType, clnDate, ward, roomcd, reasonForUseN,
                                                       orderNo, orderName, orderCd, ocrCode, cretno, createUserName, modifyUserName,
                                                       certTarget, certResult, mainDrId, opRsrvNo);

          consentMstRid = (int) paramHashTable["consentMstRid"];

          //새로 작성하는 경우
          if (isNewConsentMasterCase) {
            dac.InsertConsentMst(this.IbatisMapper, paramHashTable);
            dac.InsertConsentData(this.IbatisMapper, paramHashTable);

            imageUpload(dac, paramHashTable, userId
                        , patientCode, vistType, clnDate, dschdd, cretno, ocrCode
                        , consentMstRid, consentState, formCd, formRid, dataXml
                        , imageFileJson, certTarget, certResult, hosType, createUserName, hosType, fileSize);
          }
            //새로 작성 아닌 경우
            else {
            if (reissueConsentMstRid > 0) {
              if (string.IsNullOrEmpty(reasonForUseN)) {
                //종이->종이 재발행 
                int newConsentMstRid = this.GetSequence("CONSENT_MST");
                paramHashTable["consentMstRid"] = newConsentMstRid;
                consentMstRid = newConsentMstRid;

                dac.InsertConsentMst(this.IbatisMapper, paramHashTable);
                dac.InsertConsentData(this.IbatisMapper, paramHashTable);

                imageUpload(dac, paramHashTable, userId
                            , patientCode, vistType, clnDate, dschdd, cretno, ocrCode
                            , consentMstRid, consentState, formCd, formRid, dataXml,
                            imageFileJson, certTarget, certResult, hosType, createUserName, hosType, fileSize);
              } else {
                dac.UpdateConsentMstForDelete(this.IbatisMapper, paramHashTable);
              }

            }
            //임시저장 또는 저장인 경우
            else {

              Hashtable param = new Hashtable();
              param.Add("consentMstRid", consentMstRid);
              int imageCount = dac.GetConsentImageCount(this.IbatisMapper, param);

              if (imageCount == 0) {
                imageUpload(dac, paramHashTable, userId
                            , patientCode, vistType, clnDate, dschdd, cretno, ocrCode
                            , consentMstRid, consentState, formCd, formRid, dataXml
                            , imageFileJson, certTarget, certResult, hosType, createUserName, hosType, fileSize);
              }

              dac.UpdateConsentMst(this.IbatisMapper, paramHashTable);
              dac.InsertConsentData(this.IbatisMapper, paramHashTable);

              if (imageCount > 0) {
                confirmSaveImageCover(consentMstRid, userId, ocrCode, imageFileJson, consentState);
              }

            }
          }

          // OCR 테이블 연계
          Hashtable ocrParam = new Hashtable {
                        { "instcd", hosType },
                        { "ocrtag", ocrCode },
                        { "pid", patientCode },
                        { "ordtype", vistType },
                        { "orddd", clnDate },
                        { "cretno", cretno },
                        { "orddrid", mainDrId },
                        { "orddeptcd", clnDeptCode },
                        { "formcd", formCd },
                        { "fstprntdeptcd", userDeptCd },
                        { "fstprntid", userId },
                        { "updtdeptcd", userDeptCd },
                        { "updtuserid", userId },
                        { "updtdt", DateTime.Now.ToString("yyyyMMddHHmmss")},
                        { "pagecnt", pageCnt },
                        { "updtresncnts", reasonForUseN },
                        { "actkind", actKind },
                        { "clienttype", clientType },
                        { "endYn", endYn }
                    };

          dac.InsertPrintData(this.IbatisMapper, ocrParam);

          if (consentState.Equals("CERTIFY_CMP")) {
            // 원무 동의서 연동 지금은 사용하지 않음
            SavePatientConsentInfo(formCd, patientCode, ocrCode, hosType, clnDate, cretno.ToString(), vistType, clnDeptCode, mainDrId, userId, dataXml);
          }

          // 사용 안함
          /*
          if (!string.IsNullOrEmpty(dataXml)) {
              Dictionary<string, string> outputDataDic = DataXmlToDictionary(dataXml);

              Hashtable paramHashTableForMediHistory = new Hashtable();
              paramHashTableForMediHistory.Add("patientCode", patientCode);
              paramHashTableForMediHistory.Add("clnDate", clnDate.Replace("-", ""));
              paramHashTableForMediHistory.Add("bp", outputDataDic.ContainsKey("IO_bp") ? outputDataDic["IO_bp"] : "");
              paramHashTableForMediHistory.Add("dm", outputDataDic.ContainsKey("IO_dm") ? outputDataDic["IO_dm"] : "");
              paramHashTableForMediHistory.Add("heart", outputDataDic.ContainsKey("IO_heart") ? outputDataDic["IO_heart"] : "");
              paramHashTableForMediHistory.Add("kidney", outputDataDic.ContainsKey("IO_kidney") ? outputDataDic["IO_kidney"] : "");
              paramHashTableForMediHistory.Add("respiration", outputDataDic.ContainsKey("IO_respiration") ? outputDataDic["IO_respiration"] : "");
              paramHashTableForMediHistory.Add("hx", outputDataDic.ContainsKey("IO_hx") ? outputDataDic["IO_hx"] : "");
              paramHashTableForMediHistory.Add("allergy", outputDataDic.ContainsKey("IO_allergy") ? outputDataDic["IO_allergy"] : "");
              paramHashTableForMediHistory.Add("drug", outputDataDic.ContainsKey("IO_drug") ? outputDataDic["IO_drug"] : "");
              paramHashTableForMediHistory.Add("smoking", outputDataDic.ContainsKey("IO_smoking") ? outputDataDic["IO_smoking"] : "");
              paramHashTableForMediHistory.Add("idio", outputDataDic.ContainsKey("IO_idio") ? outputDataDic["IO_idio"] : "");
              paramHashTableForMediHistory.Add("nacrotics", outputDataDic.ContainsKey("IO_nacrotics") ? outputDataDic["IO_nacrotics"] : "");
              paramHashTableForMediHistory.Add("airway", outputDataDic.ContainsKey("IO_airway") ? outputDataDic["IO_airway"] : "");
              paramHashTableForMediHistory.Add("hemorrhage", outputDataDic.ContainsKey("IO_hemorrhage") ? outputDataDic["IO_hemorrhage"] : "");
              paramHashTableForMediHistory.Add("status_etc", outputDataDic.ContainsKey("IO_status_etc") ? outputDataDic["IO_status_etc"] : "");
              paramHashTableForMediHistory.Add("userId", userId);

              dac.SetMediHistory(this.IbatisMapper, paramHashTableForMediHistory);
          }
          */
        }
      } catch (Exception ex) {
        if (this.IbatisSession != null) this.IbatisSession.RollBackTransaction();
        CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm SaveDataAll ERROR : [{0}]", ex.ToString()));
        return -1;
        throw ex;
      } finally {
      }
      return consentMstRid;
    }

    private void imageUpload(SaveConsentDac dac, Hashtable paramHashTable, string userId, string patientCode, string visitType, string clnDate,
                             string Dschdd, int cretno, string ocrcode, int consentMstRid, string consentState, string formCd, int formRid,
                             string dataXml, string imageFileJson, string certTarget, string certResult, string hosType, string createUserName,
                             string dutinstcd, string fileSize) {

      // 서명 저장일 경우 emrindxm 테이블에 저장
      if (!string.IsNullOrEmpty(consentState) && (consentState.Equals("ELECTR_CMP") || consentState.Equals("CERTIFY_CMP"))) {
        string clnDeptCode = paramHashTable["clnDeptCd"] == null ? string.Empty : paramHashTable["clnDeptCd"].ToString();

        string[] fileSizeAr = fileSize.Split(new char[] { ',' });

        try {
          int consentImageRid    = this.GetSequence("CONSENT_IMAGE");
          int firstImageRid      = consentImageRid;

          string sPath           = string.Empty;
          string sFileName       = string.Empty;
          string newFileFullName = string.Empty;

          if (!string.IsNullOrEmpty(imageFileJson)) {
            Dictionary<string, object> jsonRoot = null;
            jsonRoot = fastJSON.JSON.Parse(imageFileJson) as Dictionary<string, object>;

            if (jsonRoot != null && jsonRoot.Count > 0) {
              Hashtable imageHashTable = new Hashtable();

              int nowCnt = 1;
              int fileSizeCnt = 0;
              foreach (KeyValuePair<string, object> jr in jsonRoot) {
                imageHashTable = new Hashtable();
                imageHashTable.Add("consentMstRid", consentMstRid);

                if (nowCnt > 1) consentImageRid = this.GetSequence("CONSENT_IMAGE");
                imageHashTable.Add("consentImageRid", consentImageRid);

                imageHashTable.Add("userId", userId);
                imageHashTable.Add("formRid", formRid);

                if (jr.Value != null && !string.IsNullOrEmpty(jr.Value.ToString())) {
                  sPath = "";
                  sFileName = "";
                  string[] filepath = jr.Value.ToString().Split('/');
                  for (int i = 0; i < filepath.Length; i++) {
                    if (i == 0) {
                      sPath = filepath[i];
                    } else if ((i + 1) == filepath.Length) {
                      sFileName = filepath[i];
                    } else {
                      sPath += "/" + filepath[i];
                    }
                  }
                  newFileFullName = string.Empty;
                  using (HospitalSvc hospitalWebService = new HospitalSvc()) {
                    //newFileFullName = hospitalWebService.GetFileName(patientCode, visitType,
                    //                                                    clnDate.Replace("-", ""), Dschdd, string.Format("{0}", cretno),
                    //                                                    "500", formCd, nowCnt.ToString(),
                    //                                                    ocrcode, userId, clnDeptCode, dutinstcd);
                    newFileFullName = hospitalWebService.GetFileName(patientCode, visitType,
                                                                     clnDate.Replace("-", ""), Dschdd, string.Format("{0}", cretno),
                                                                     fileSizeAr[fileSizeCnt], formCd, nowCnt.ToString(),
                                                                     ocrcode, userId, clnDeptCode, dutinstcd);

                    fileSizeCnt++;
                  }

                  string uploadFileName = newFileFullName + ".jpg";

                  int idx = uploadFileName.LastIndexOf(".");
                  string sUploadPath = uploadFileName.Substring(idx - 4, 4);
                  string sUploadFileName = uploadFileName.Substring(uploadFileName.LastIndexOf("\\") + 1);
                  var remotePath = imageServerProps.remotePath;
                  //var destDrive = remotePath.Substring(0, 2);
                  var destDirectory = remotePath.Substring(2);
                  //remotePath = "Z:\\ACTIVE_ENC\\M\\TEST";
                  //destDirectory = "\\ACTIVE_ENC\\M\\TEST";

                  //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("uploadFileName -- >  " + uploadFileName);
                  //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("sUploadPath -- >  " + sUploadPath);
                  //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("sUploadFileName -- >  " + sUploadFileName);
                  //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("remotePath -- >  " + remotePath);
                  //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("destDirectory -- >  " + destDirectory);

                  var targetDrive = "";
                  var virtualDir = "";
                  // 경로를 확인하여 가상 디렉토리 경로를 설정한다
                  if (imageServerProps != null) {
                    targetDrive = imageServerProps.remotePath.Substring(0, 1);
                    switch (targetDrive) {
                      case "W":
                      virtualDir = "his032";
                      break;
                      case "Z":
                      virtualDir = "his031";
                      break;
                    }
                  }

                  //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("targetDrive -- >  " + targetDrive);
                  //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("virtualDir -- >  " + virtualDir);

                  // 계정을 choiadmin 으로 가장한다
                  ClipSoft.Utility.ImpersonationUtility util = new ClipSoft.Utility.ImpersonationUtility();
                  var imResult = util.ImpersonationStart(string.Empty, "choiadmin", "choiadmin");
                  CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("Impersonation Start, " + imResult);

                  // IIS 가상 디렉토리 경로를 가져온다
                  DirectoryInfo di = new DirectoryInfo(Server.MapPath(virtualDir));
                  var destDirStr = String.Format(@"{0}\{1}\{2}",
                      di.ToString(),
                      remotePath.Substring(remotePath.IndexOf("ACTIVE_ENC") + @"ACTIVE_ENC\".Length),
                      sUploadPath);

                  //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("destDirStr -- >  " + destDirStr);

                  // for debug
                  //var destDirStr = String.Format(@"{0}\{1}\{2}\{3}\",
                  //    di.ToString(),
                  //    remotePath.Substring(remotePath.IndexOf("ACTIVE_ENC") + @"ACTIVE_ENC\".Length),
                  //    "consentTest",
                  //    sUploadPath);

                  DirectoryInfo destDi = new DirectoryInfo(destDirStr);

                  //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("destDirStr: " + destDirStr + ", exists: " + destDi.Exists);

                  var destFullname = String.Format(@"{0}\{1}", destDirStr, sUploadFileName);
                  var localFile = Server.MapPath(string.Format(@"./UPLOAD/{0}/{1}", sPath, sFileName));

                  CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("localFile -- > " + localFile);
                  CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("destFullname -- > " + destFullname);
                  CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("new DateTime() -- > " + DateTime.Now.ToString("yyyyMMddHHmmss"));

                  if (!destDi.Exists) {
                    destDi.Create();
                  }
                  try {
                    File.Copy(localFile, destFullname);
                  } catch (Exception e) {
                    CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(e);
                    File.Move(destFullname, destFullname.Insert(destFullname.LastIndexOf(".jpg"), "_" + imageHashTable["consentMstRid"] + "_" + DateTime.Now.ToString("yyyyMMddHHmmss")));
                    File.Copy(localFile, destFullname);
                  }


                  util.ImpersonationEnd();
                  CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("Impersonation end");

                  imageHashTable.Add("imagePath", sUploadPath);
                  imageHashTable.Add("imageFilename", sUploadFileName);
                  imageHashTable.Add("completeYn", paramHashTable["completeYn"]);

                  dac.InsertConsentImage(this.IbatisMapper, imageHashTable);
                }
                nowCnt++;
              }       // end of foreach
            }
          }

          paramHashTable.Add("consentImageRid", firstImageRid);

          // TODO 원무 인증 저장 pass
          // 원무 저장시 해당 정보 저장 or skip 확인 해 볼 것
          // 사인정보 저장
          dac.InsertConsentImageSign(this.IbatisMapper, paramHashTable);

        } catch (Exception ex) {
          using (HospitalSvc hospitalWebService = new HospitalSvc()) {
            hospitalWebService.delEformData(patientCode, visitType,
                                            clnDate.Replace("-", ""), Dschdd, string.Format("{0}", cretno),
                                            formCd, ocrcode, userId, createUserName, string.Format("{0}", consentMstRid), hosType,
                                            clnDeptCode, dutinstcd);
          }
          if (this.IbatisSession != null) this.IbatisSession.RollBackTransaction();
          CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm imageUpload ERROR : [{0}]", ex.ToString()));
          throw ex;
        }
      }

    }

    /// <summary>
    /// 확인저장 재 확인시 이미지 이름을 가져온다
    /// 재 업로드하는 이미지를 가져온 이름으로 변경 후 기존의 이미지를 덮어쓴다
    /// </summary>
    /// <param name="pid">환자번호</param>
    /// <param name="ocrTag">ocrTag</param>
    /// <param name="pageNo">페이지 번호</param>
    //[WebMethod(Description = "!@#")]
    private string confirmSaveImageCover(int consentMstRidInt, string userId, string ocrCode, string imageFileJson, string consentState) {
      List<ConsentImageVO> result;
      string fileName = "";
      try {
        using (ConsentDac dac = new ConsentDac()) {

          Dictionary<string, object> jsonRoot = fastJSON.JSON.Parse(imageFileJson) as Dictionary<string, object>;
          Dictionary<string, string> pathDic = new Dictionary<string, string>();

          List<String> sPath = new List<String>();
          List<String> sFileName = new List<String>();
          foreach (KeyValuePair<string, object> jr in jsonRoot) {
            if (jr.Value != null && !string.IsNullOrEmpty(jr.Value.ToString())) {
              //sPath = "";
              //sFileName = "";
              string[] filepath = jr.Value.ToString().Split('/');

              sPath.Add(filepath[0] + "/" + filepath[1]);
              sFileName.Add(filepath[2]);
            }
          }

          Hashtable param = new Hashtable();
          param.Add("consentMstRid", consentMstRidInt);
          param.Add("userId", consentMstRidInt);
          param.Add("ocrCode", ocrCode);
          param.Add("consentState", consentState);
          result = (List<ConsentImageVO>) dac.GetConsentImageFileName(this.IbatisMapper, param);

          int cnt = 0;
          foreach (ConsentImageVO img in result) {
            fileName = img.ImageFilename;
            var sUploadPath = img.ImagePath;


            var remotePath = imageServerProps.remotePath;
            var destDirectory = remotePath.Substring(2);

            var targetDrive = "";
            var virtualDir = "";
            // 경로를 확인하여 가상 디렉토리 경로를 설정한다
            if (imageServerProps != null) {
              targetDrive = imageServerProps.remotePath.Substring(0, 1);
              switch (targetDrive) {
                case "W":
                  virtualDir = "his032";
                  break;
                case "Z":
                  virtualDir = "his031";
                  break;
              }
            }

            // 계정을 choiadmin 으로 가장한다
            ClipSoft.Utility.ImpersonationUtility util = new ClipSoft.Utility.ImpersonationUtility();
            var imResult = util.ImpersonationStart(string.Empty, "choiadmin", "choiadmin");
            CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug("Impersonation Start, " + imResult);

            // IIS 가상 디렉토리 경로를 가져온다
            DirectoryInfo di = new DirectoryInfo(Server.MapPath(virtualDir));
            var destDirStr = String.Format(@"{0}\{1}\{2}",
                di.ToString(),
                remotePath.Substring(remotePath.IndexOf("ACTIVE_ENC") + @"ACTIVE_ENC\".Length),
                sUploadPath);

            DirectoryInfo destDi = new DirectoryInfo(destDirStr);

            var destFullname = String.Format(@"{0}\{1}", destDirStr, fileName);
            var localFile = Server.MapPath(string.Format(@"./UPLOAD/{0}/{1}", sPath[cnt], sFileName[cnt]));

            if (!destDi.Exists) {
              destDi.Create();
            }
            try {
              File.Copy(localFile, destFullname, true);
            } catch (Exception e) {
              CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(e);
              File.Move(destFullname, destFullname.Insert(destFullname.LastIndexOf(".jpg"), "_" + consentMstRidInt + "_" + DateTime.Now.ToString("yyyyMMddHHmmss")));
              File.Copy(localFile, destFullname);
            }


            util.ImpersonationEnd();

            cnt++;
          }

          dac.UpdateConsentImage(this.IbatisMapper, param);

        }
      } catch (Exception ex) {
        CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm imageUpload ERROR : [{0}]", ex.ToString()));
        throw ex;
      }

      return fileName;
    }

    private bool checkOcrType6Form(string dutinstcd, string formCd) {
      List<String> forms = getOcrType6Forms(dutinstcd);
      int pos = forms.FindIndex(x => x.StartsWith(formCd));

      return (pos > 0) ? true : false;
    }

    private int SavePrintData(string userId, string patientCode, string clnDeptCode, int formRid, string formCd,
                                       int consentMstRid, int rewriteConsentMstRid, int reissueConsentMstRid, string consentState, string paperYn, string formXml, string dataXml,
                                       string deviceType, string deviceIdentNo, string vistType, string hosType, string clnDate,
                                       string ward, string roomcd, string reasonForUseN, int orderNo, string orderName, string orderCd, string ocrCode, int cretno,
                                       string createUserName, string modifyUserName, string imageFileName, string certTarget,
                                       string certResult, string mainDrId,
                                       string userDeptCd, string pageCnt, string actKind, string clientType, string opRsrvNo) {
      bool isNewConsentMasterCase = false;
      if (consentMstRid < 1) {
        isNewConsentMasterCase = true;
      }
      // OCR TYPE 6 는 기록하지 않는다
      if (checkOcrType6Form(hosType, formCd)) {
        return -1;
      }

      try {
        using (SaveConsentDac dac = new SaveConsentDac()) {
          Hashtable paramHashTable = GetParamHashTable(userId, patientCode, clnDeptCode, formRid, formCd, consentMstRid, rewriteConsentMstRid,
                                                       reissueConsentMstRid, consentState, paperYn, formXml, dataXml, deviceType, deviceIdentNo,
                                                       vistType, hosType, clnDate, ward, roomcd, reasonForUseN,
                                                       orderNo, orderName, orderCd, ocrCode, cretno, createUserName, modifyUserName,
                                                       certTarget, certResult, mainDrId, opRsrvNo);

          consentMstRid = (int) paramHashTable["consentMstRid"];

          //새로 출력하는 경우
          if (isNewConsentMasterCase) {
            dac.InsertConsentMst(this.IbatisMapper, paramHashTable);
          }
          //새로 작성 아닌 경우
          else {
            if (reissueConsentMstRid > 0)
              dac.UpdateConsentMstForReissue(this.IbatisMapper, paramHashTable);
            else
              dac.UpdateConsentMst(this.IbatisMapper, paramHashTable);
          }

          // OCR 테이블 연계
          Hashtable ocrParam = new Hashtable {
                        { "instcd", hosType },
                        { "ocrtag", ocrCode },
                        { "pid", patientCode },
                        { "ordtype", vistType },
                        { "orddd", clnDate },
                        { "cretno", cretno },
                        { "orddrid", mainDrId },
                        { "orddeptcd", clnDeptCode },
                        { "formcd", formCd },
                        { "fstprntdeptcd", userDeptCd },
                        { "fstprntid", userId },
                        { "updtdeptcd", userDeptCd },
                        { "updtuserid", userId },
                        { "updtdt", DateTime.Now.ToString("yyyyMMddHHmmss")},
                        { "pagecnt", pageCnt },
                        { "updtresncnts", reasonForUseN },
                        { "actkind", actKind },
                        { "clienttype", clientType }
                    };

          dac.InsertPrintData(this.IbatisMapper, ocrParam);
        }
      } catch (Exception ex) {
        if (this.IbatisSession != null) this.IbatisSession.RollBackTransaction();
        CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm SaveData ERROR : [{0}]", ex.ToString()));
        throw ex;
      } finally {
      }
      return consentMstRid;
    }

    public static int ExecuteCommand(string command, int timeout) {
      var processInfo = new System.Diagnostics.ProcessStartInfo("cmd.exe", "/C " + command) {
        RedirectStandardOutput = true,
        CreateNoWindow = true,
        UseShellExecute = false,
        //WorkingDirectory = "C:\\",
        //WorkingDirectory = ".\\",
      };

      var process = System.Diagnostics.Process.Start(processInfo);
      process.WaitForExit(20000);
      //string txt = process.StandardOutput.ReadToEnd();
      //Console.WriteLine(txt);
      var exitCode = process.ExitCode;
      process.Close();
      return exitCode;
    }

    private static Dictionary<string, string> DataXmlToDictionary(string dataXml) {
      Dictionary<string, string> outputDataDic;
      XmlDocument xmlDocument = new XmlDocument();
      xmlDocument.LoadXml(dataXml);

      outputDataDic = new Dictionary<string, string>();
      XmlNode rootNode = xmlDocument.SelectSingleNode("form-data");

      foreach (XmlNode childNode in rootNode.ChildNodes) {
        string fieldName = string.Empty;
        string fieldValue = string.Empty;

        XmlElement outFieldElement = childNode as XmlElement;

        if (outFieldElement != null) {

          fieldName = outFieldElement.Name;

          //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug(string.Format("DataXmlToDictionary 0 : {0}/{1}", outFieldElement.ChildNodes.Count, fieldName));

          if (outFieldElement.ChildNodes.Count == 1 && outFieldElement.ChildNodes[0] is XmlCDataSection) {

            fieldValue = ((XmlCDataSection) outFieldElement.ChildNodes[0]).InnerText;

            //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug(string.Format("DataXmlToDictionary 1 : {0}/{1}", fieldName, fieldValue));

            if (outputDataDic.ContainsKey(fieldName)) {
              outputDataDic[fieldName] = fieldValue;
            } else {
              outputDataDic.Add(fieldName, fieldValue);
            }

          } else if (outFieldElement.ChildNodes.Count > 1) {

            foreach (XmlNode childNode2 in childNode.ChildNodes) {

              string fieldName2 = string.Empty;
              string fieldValue2 = string.Empty;

              XmlElement outFieldElement2 = childNode2 as XmlElement;
              fieldName2 = outFieldElement2.Name;

              //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug(string.Format("DataXmlToDictionary : {0}", fieldName2));
              //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug(string.Format("DataXmlToDictionary : {0}", outFieldElement2.ChildNodes.Count));

              if (outFieldElement2.ChildNodes.Count > 0 && outFieldElement2.ChildNodes[0] is XmlCDataSection) {
                fieldValue2 = ((XmlCDataSection) outFieldElement2.ChildNodes[0]).InnerText;
                //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug(string.Format("DataXmlToDictionary 2 : {0}/{1}", fieldName2, fieldValue2));
              }

              if (outputDataDic.ContainsKey(fieldName2)) {
                outputDataDic[fieldName2] = fieldValue2;
              } else {
                outputDataDic.Add(fieldName2, fieldValue2);
              }
            }
          }
        }
      }

      return outputDataDic;
    }

    /// <summary>
    /// EFORM_CODE에 정의하는 시퀀스(채번)을 구한다.
    /// </summary>
    /// <param name="sSubCd"></param>
    /// <returns></returns>
    private int GetSequence(string sSubCd) {
      int nSeq = -1;

      try {
        using (CommonCodeDac dac = new CommonCodeDac()) {
          Code param = new Code();
          param.sub_cd = sSubCd;

          nSeq = dac.GetSequence(this.IbatisMapper, param);

          if (nSeq == 0) {
            dac.InsertSequence(this.IbatisMapper, param);
            nSeq = 1;
          } else {
            param.ud1_num = ++nSeq;
            dac.UpdateSequence(this.IbatisMapper, param);
          }
        }
      } catch (Exception ex) {
        if (this.IbatisSession != null) this.IbatisSession.RollBackTransaction();
        throw ex;
      }

      return nSeq;
    }

    #region GetParamHashTable
    private Hashtable GetParamHashTable(string userId,              // 사용자 Id
                                            string patientCode,         // 환자 등록번호
                                            string clnDeptCode,         // 진료과 코드
                                            int formRid,                // (작성대상)서식 Rid
                                            string formCd,              // 서식코드 === CONSENT_DATA_CHOICE에서 입력여부 판단할 파라미터 
                                            int consentMstRid,          // 동의서 마스터 데이터 Rid
                                            int rewriteConsentMstRid,   // 재 작성 대상 동의서 마스터 데이터 Rid
                                            int reissueConsentMstRid,   // 재 발행 대상 동의서 마스터 데이터 Rid
                                            string consentState,        // 동의서 상태 (TEMP, PAPER_OUT, ELECTR_CMP, CERTIFY_CMP) 
                                            string paperYn,             // 인쇄 발행 여부            
                                            string formXml,             // 동의서 EPT Xml
                                            string dataXml,             // 동의서 Data(필드들) Xml
                                            string deviceType,          // 장비 유형 (WIN, AND, IOS, PRT 중1)
                                            string deviceIdentNo,       // 장비 고유식별 번호
                                            string vistType,            // 내원 구분
                                            string hosType,             // 병원 구분
                                            string clnDate,             // 내원구분에 따른 입원일자/진료일자
                                            string ward,                // 병동 코드
                                            string roomcd,              // 병실 코드
                                            string reasonForUseN,       // 출력된 동의서 폐기 사유
                                            int orderNo,                // 처방번호
                                            string orderName,           // 처방명
                                            string orderCd,             // 처방코드
                                            string ocrCode,             // OCR 코드
                                            int cretno,                 // 생성번호
                                            string createUserName,      // 작성자명
                                            string modifyUserName,      // 수정자명
                                            string certTarget,          // 서명데이터 원본
                                            string certResult,          // 서명데이터 결과값
                                            string mainDrId,            // 주치의 아이디
                                            string opRsrvNo             // 수술 예약 번호
                                        ) {
      Hashtable paramHashTable = new Hashtable();
      paramHashTable.Add("userId", userId);
      if (consentMstRid < 1) {
        // insert case
        consentMstRid = this.GetSequence("CONSENT_MST");
      }
      paramHashTable.Add("consentMstRid", consentMstRid);
      paramHashTable.Add("patientCode", patientCode);
      paramHashTable.Add("clnDeptCd", clnDeptCode);
      paramHashTable.Add("vistType", vistType);
      paramHashTable.Add("hosType", hosType);
      paramHashTable.Add("clnDate", clnDate);
      paramHashTable.Add("ward", ward);
      paramHashTable.Add("roomcd", roomcd);
      paramHashTable.Add("orderNo", orderNo);
      paramHashTable.Add("orderName", orderName);
      paramHashTable.Add("orderCd", orderCd);
      paramHashTable.Add("ocrCode", ocrCode);
      paramHashTable.Add("cretno", cretno);
      paramHashTable.Add("createUserName", createUserName);
      paramHashTable.Add("modifyUserName", modifyUserName);
      paramHashTable.Add("formRid", formRid);
      paramHashTable.Add("formCd", formCd);
      paramHashTable.Add("consentState", consentState);
      paramHashTable.Add("certTarget", certTarget);   // TODO 원무 pass
      paramHashTable.Add("certResult", certResult);   // TODO 원무 pass
      paramHashTable.Add("mainDrId", mainDrId);
      paramHashTable.Add("opRsrvNo", opRsrvNo ?? string.Empty);

      Encoding encoding = Encoding.GetEncoding("UTF-8");
      //if (certResult != null)
      //{
      //    paramHashTable.Add("certResult", encoding.GetBytes(certResult));
      //}

      string completeYn = "N"; // 완료 여부
      switch (consentState) {
        //case "ELECTR_CMP":
        case "CERTIFY_CMP":
        completeYn = "Y";
        break;
        default:
        break;
      }
      paramHashTable.Add("completeYn", completeYn);

      string completeDateTimeToChars = string.Empty;
      if (completeYn.Equals("Y")) {
        completeDateTimeToChars = "TO_CHAR(SYSDATE,'YYYY-MM-DD hh24:mi:ss')";
        paramHashTable.Add("completeDateTimeToChars", completeDateTimeToChars);
      } else {
        paramHashTable.Add("completeDateTimeToChars", "''");
      }

      paramHashTable.Add("paperYn", paperYn);

      string rewriteYn = "N"; // 재 작성 여부
      if (rewriteConsentMstRid > 1) {
        rewriteYn = "Y";
      }
      paramHashTable.Add("rewriteYn", rewriteYn);
      paramHashTable.Add("rewriteConsentMstRid", rewriteConsentMstRid);

      string reissueYn = "N"; // 재 발행(종이) 여부
      if (reissueConsentMstRid > 1) {
        reissueYn = "Y";
      }
      paramHashTable.Add("reissueYn", reissueYn);
      paramHashTable.Add("reissueConsentMstRid", reissueConsentMstRid);

      int consentDataRid = this.GetSequence("CONSENT_DATA");
      paramHashTable.Add("consentDataRid", consentDataRid);

      paramHashTable.Add("useYn", "Y");

      encoding = Encoding.GetEncoding("UTF-8");
      byte[] formBytesConent = null;
      if (!string.IsNullOrEmpty(formXml)) {
        formBytesConent = encoding.GetBytes(formXml);
      }
      byte[] dataBytesConent = null;
      if (!string.IsNullOrEmpty(dataXml)) {
        dataBytesConent = encoding.GetBytes(dataXml);
      }
      paramHashTable.Add("formXml", formBytesConent);
      paramHashTable.Add("dataXml", dataBytesConent);

      paramHashTable.Add("deviceType", deviceType);
      paramHashTable.Add("deviceIdentNo", deviceIdentNo);
      paramHashTable.Add("reasonForUseN", reasonForUseN);

      return paramHashTable;
    }
    #endregion

    //임시파일 삭제 (1일전 파일은 삭제)
    //public int DeleteTempFile(string targetDate)
    public int DeleteTempFile() {
      //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug(string.Format("DeleteTempFile DateTime.Now.AddDays(-1) : {0}", DateTime.Now.AddDays(-1).ToString())); // 2016-11-06 오후 8:19:56

      if (tempImageDelStatus.Equals(DateTime.Now.AddDays(-1).ToString().Substring(0, 10).Replace("-", ""))) {
        return 1;
      }

      try {
        string sSeverImgPath = Server.MapPath("./DataTempImage/");
        DirectoryInfo di = new System.IO.DirectoryInfo(sSeverImgPath);
        if (Directory.Exists(sSeverImgPath)) {
          string[] filePaths = Directory.GetFiles(sSeverImgPath);
          foreach (string fileName in filePaths) {
            FileInfo fileInfo = new FileInfo(fileName);

            //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug(string.Format("DeleteTempFile fileInfo.CreationTime : {0}", fileInfo.CreationTime.ToString()));
            if (fileInfo.CreationTime < DateTime.Now.AddDays(-1)) {
              fileInfo.Delete();
            }
          }
        }

        tempImageDelStatus = DateTime.Now.AddDays(-1).ToString().Substring(0, 10).Replace("-", "");

        return 1;
      } catch {
        return -1;
      }
    }

    /// <summary>
    /// 동의서 로드 전 consent_mst_rid에 해당하는 동의서가 상위 상태값이 있는지 체크
    /// </summary>
    /// <param name="consentmstrid"></param>
    /// <param name="consent_state"></param>
    /// <returns></returns>
    [WebMethod(Description = "동의서 상위 상태값이 있는지 체크")]
    public SingleReturnData CheckConsentState(int consentmstrid, string consent_state) {
      //CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Debug(string.Format("rid: {0}, state: {1}", consentmstrid, consent_state));
      SingleReturnData singleReturnData = new SingleReturnData();
      try {
        int result = -1;
        int StateNo = 0;
        String CurState;
        using (ConsentDac dac = new ConsentDac()) {
          Hashtable param = new Hashtable();
          param.Add("consentmstrid", consentmstrid);

          CurState = dac.GetConsentStateCheck(this.IbatisMapper, param);
        }

        if (CurState == null) {
          singleReturnData.responseData = "0";
          return singleReturnData;
        } else if (CurState.Equals("UNFINISHED")) {
          StateNo = 1;
        } else if (CurState.Equals("TEMP")) {
          StateNo = 2;
        } else if (CurState.Equals("VERBAL")) {
          StateNo = 3;
        } else if (CurState.Equals("PAPER_OUT")) {
          StateNo = 4;
        } else if (CurState.Equals("ELECTR_CMP")) {
          StateNo = 5;
        } else if (CurState.Equals("CERTIFY_CMP")) {
          StateNo = 6;
        }

        if (consent_state == null/* || string.IsNullOrEmpty(consent_state)*/) {
          singleReturnData.responseData = Convert.ToString(result);
          return singleReturnData;
        } else if (consent_state.Equals("UNFINISHED")) {
          result = 1;
        } else if (consent_state.Equals("TEMP")) {
          result = 2;
        } else if (consent_state.Equals("VERBAL")) {
          result = 3;
        } else if (consent_state.Equals("PAPER_OUT")) {
          result = 4;
        } else if (consent_state.Equals("ELECTR_CMP")) {
          result = 5;
        } else if (consent_state.Equals("CERTIFY_CMP")) {
          singleReturnData.responseData = Convert.ToString(result);
          return singleReturnData;
        }

        if (result < StateNo)//로드하려는 동의서의 상태보다 현재 저장된 상태가 더 높은 상태일 경우
        {
          singleReturnData.responseData = "1";
          return singleReturnData;
        } else//로드하려는 동의서보다 현재 저장된 상태가 낮은상태일 경우 또는 같을경우
          {
          singleReturnData.responseData = "0";
          return singleReturnData;
        }
      } catch {
        singleReturnData.responseData = "-1";
        return singleReturnData;
      }
    }

    [WebMethod(Description = "AGMT 입력을 위한 consent_mst 조회")]
    public string getAgmtConsentData(string instcd, string ocrtag) {
      string retStr = string.Empty;

      using(ConsentDac dac = new ConsentDac()) {
        // 1. 먼저 OCRTAG 로 consent_mst 쪽에서 데이터를 가져온다
        Hashtable param1 = new Hashtable();
        param1.Add("instcd", instcd);
        param1.Add("ocrtag", ocrtag);
        AgmtVo vo = dac.getConsentMst(this.IbatisMapper, param1);

        if(vo == null) {
          return "error, EMA.CONSENT_MST 에 데이터가 없습니다. 입력 파라미터를 다시 확인하세요.";
        }

        // BLOB 데이터를 불러 온다.
        Hashtable parma2 = new Hashtable();
        parma2.Add("consentMstRid", vo.consentMstRid);

        string rawXml = dac.getConsentData(IbatisMapper, parma2);

        if(string.IsNullOrEmpty(rawXml)) {
          return "error, BLOB 데이터 호출 오류";
        }
        try {
          SavePatientConsentInfo(vo.formCd, vo.pid, vo.ocrtag, vo.instcd, vo.clnDate, String.Format("{0}", vo.cretno), vo.ordtype, vo.deptcd, vo.orddrid, vo.createUserId, rawXml);
          retStr = String.Format("PID: {0}, ordtype: {1}, ocrtag: {2} 의 입원약정서가 pam.pmihagmt 테이블에 Insert 되었습니다.", vo.pid, vo.ordtype, vo.ocrtag);
        }
        catch(Exception e) {
          retStr = e.ToString();
        }
        
      }

      return retStr;
    }

    private void SavePatientConsentInfo(string p_formcd
                                      , string p_pid
                                      , string p_ocrtag
                                      , string p_instcd
                                      , string p_orddd
                                      , string p_cretno
                                      , string p_ordtype
                                      , string p_orddeptcd
                                      , string p_orddrid
                                      , string p_userid
                                      , string p_dataxml) {

      try {

        // 원무 동의서 연동 정보 입력
        // 1300013649 : 입원약정서(기간)(E)
        // 1300013647 : 선택진료신청서(E)
        // 1300013648 : 입원약정서(일반)(E)
        // 1100012120 : C3-개인정보 수집·이용 제공 동의서
        // 1400015188 : C3-개인정보 수집 이용 제공 동의서(중국어)
        // 1400015531 : C3-개인정보 수집·이용 및 제공 동의서(영어)
        // 현재 입원 약정서 외에는 사용하지 않음
        if (!p_formcd.Equals("1300013648")
         /*&& !p_formcd.Equals("1300013647")
         && !p_formcd.Equals("1100012120")
         && !p_formcd.Equals("1400015188")
         && !p_formcd.Equals("1400015531")*/
         && !p_formcd.Equals("1300013649")) {

          return;
        }

        // 동의서 내부 데이터 추출
        Dictionary<string, string> pamDic = DataXmlToDictionary(p_dataxml);
        var today = DateTime.Today.ToString("yyyyMMdd");
        string fromdt = null, todt = null;
        if (string.IsNullOrEmpty(pamDic["savCMDCBD_ContStartDate"]))
        {
            fromdt = today;
        }
        else
        {
            fromdt = pamDic["savCMDCBD_ContStartDate"];
        }
        if (string.IsNullOrEmpty(pamDic["savCMDCBD_ContEndDate"]))
        {
            todt = today;
        }
        else
        {
            todt = pamDic["savCMDCBD_ContEndDate"];
        }

        // 선택진료신청서 - 선택 진료 여부 > savCMDCBD_SpDrYN
        // 입원약정서 - 약정시작일 > savCMDCBD_ContStartDate
        // 입원약정서 - 약정종료일 > savCMDCBD_ContEndDate
        // 개인정보이용동의서 - 확인항목 > chkitem00
        // 개인정보이용동의서 - 확인여부 > chkvalue
        Hashtable param = new Hashtable { { "pid", p_pid }
                                                , { "ocrtag", p_ocrtag }
                                                , { "instcd", p_instcd }
                                                , { "orddd", p_orddd }
                                                , { "cretno", p_cretno }
                                                , { "ordtype", p_ordtype }
                                                , { "msflag", "" }
                                                , { "orddeptkind", "" }
                                                , { "orddeptcd", p_orddeptcd }
                                                , { "orddrid", p_orddrid }
                                                , { "specordyn", ( pamDic.ContainsKey("savCMDCBD_SpDrYN") ? pamDic["savCMDCBD_SpDrYN"] : "" ) }
                                                , { "specdrid", "" }
                                                , { "userid", p_userid }
                                                , { "contfromdd", fromdt }
                                                , { "conttodd", todt }
                                                , { "formcd", p_formcd }
                                                , { "chkitem", "" }
                                                , { "chkvalue", ""} };


        using (SaveConsentDac dac = new SaveConsentDac()) {

          // 선택 진료 신청 동의서
          /*
          if (p_formcd.Equals("1300013647")) {
              for (int i = 0; i < 9; i++) {
                  param["msflag"] = i == 0 ? "M" : "S";
                  param["orddeptkind"] = string.Format("0{0}", i);
                  param["specdrid"] = i == 0 ? p_orddrid : "-";

                  dac.InsertPmcmspif(this.IbatisMapper, param);
              }
          }
          */

          // 입원 약정서
          if (p_formcd.Equals("1300013648") || p_formcd.Equals("1300013649")) {
            param["agmttype"] = p_formcd.Equals("1300013648") ? "1" : p_formcd.Equals("1300013649") ? "2" : "";
            dac.InsertPmihagmt(this.IbatisMapper, param);
          }

          // 개인 정보 이용 동의서
          // 개인정보이용동의서 연동 안함
          /*
          List<string> chkItemList = new List<string>();
          List<string> chkValueList = new List<string>();

          foreach(string key in pamDic.Keys) {
              if (key.ToLower().Contains("chkitem")) {
                  chkItemList.Add(key);
                  chkValueList.Add(pamDic[key]);
              }
          }

          for (int i = 0; i < chkItemList.Count; i++) {
              param["chkitem"] = chkItemList[i];
              param["chkvalue"] = chkValueList[i];

              dac.InsertPmcminfo(this.IbatisMapper, param);
          }
          */
        }

      } catch (Exception ex) {
        if (this.IbatisSession != null) this.IbatisSession.RollBackTransaction();
        CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(string.Format("CLIP.eForm SavePatientConsentInfo ERROR : [{0}]", ex.ToString()));
        throw ex;
      }
    }

    /// <summary>
    /// 기준자료로 부터 OCT 태그에 찍힐 String 값
    /// 경북대병원 dependency
    /// </summary>
    /// <param name="formCd">The form cd.</param>
    /// <param name="dutinstcd">The dutinstcd.</param>
    /// <returns></returns>
    [WebMethod(Description = "기준자료로 부터 OCT 태그에 찍힐 String 값")]
    public String getOcrString(string formCd, string dutinstcd) {
      using (ConsentDac dac = new ConsentDac()) {
        Hashtable param = new Hashtable();
        param.Add("formcd", formCd);
        param.Add("instcd", dutinstcd);

        return dac.getOcrString(this.IbatisMapper, param);
      }
    }

    /// <summary>
    /// 원무 서식의 인증저장 사용여부
    /// Y 일 경우 인증서 묻기를 하지 않는다
    /// 경북대병원 dependency
    /// </summary>
    /// <param name="formCd">서식 코드</param>
    /// <param name="dutinstcd">근무지기관코드</param>
    /// <returns></returns>
    [WebMethod(Description = "원무서식 인증저장 사용여부, Y 일 경우 인증저장시 인증서 묻기 pass")]
    public String getCertUseYn(String formCd, String dutinstcd) {
      using (ConsentDac dac = new ConsentDac()) {
        Hashtable param = new Hashtable();
        param.Add("formcd", formCd);
        param.Add("instcd", dutinstcd);

        String value = dac.getCertuseYn(this.IbatisMapper, param);

        return (value == null) ? "N" : value;

        //return dac.getCertuseYn(this.IbatisMapper, param);
      }
    }

    /// <summary>
    /// 원무 서식의 인증저장 사용여부 (모바일에서 사용)
    /// 원무 서식이 여러개 선택되었을때
    /// Y 일 경우 인증서 묻기를 하지 않는다
    /// 경북대병원 dependency
    /// </summary>
    /// <param name="formCd">서식 코드</param> 서식코드는 '11111111', '2222222', '333333' 형태로 들어옴
    /// <param name="dutinstcd">근무지기관코드</param>
    /// <returns></returns>
    [WebMethod(Description = "원무서식 인증저장 사용여부, Y 일 경우 인증저장시 인증서 묻기 pass (모바일에서 다중 선택 기능 포함)")]
    public String getCertUseYnData(String formCd, String dutinstcd) {
      using (ConsentDac dac = new ConsentDac()) {
        Hashtable param = new Hashtable();
        param.Add("formcd", formCd);
        param.Add("instcd", dutinstcd);

        String result = dac.getCertUseYnData(this.IbatisMapper, param);

        if (result == null) {
          result = "";
        }

        return result;
      }
    }

    /// <summary>
    /// 경북대학교병원 PC 클라이언트 dual view 모드 활성화 여부 조회
    /// </summary>
    /// <param name="dutinstcd">근무지기관코드</param>
    /// <param name="ipaddr">해당 PC 의 ip address</param>
    /// <returns></returns>
    [WebMethod(Description = "경북대학교병원 PC 클라이언트 dual view 모드 활성화 여부 조회")]
    public String getDualViewMode(String dutinstcd, String ipaddr) {
      using (ConsentDac dac = new ConsentDac()) {
        Hashtable param = new Hashtable();
        param.Add("instcd", dutinstcd);
        param.Add("ipaddr", ipaddr);

        String value = dac.getDualViewMode(this.IbatisMapper, param);
        return (value == null) ? "N" : value;
      }
      //return "N";
    }

    /// <summary>
    /// 확인저장 된 서식을 일괄저장
    /// </summary>
    /// <param name="consent_rids"></param>
    /// <param name="ocrtags"></param>
    /// <param name="instcd"></param>
    /// <returns></returns>
    [WebMethod(Description = "경북대학교병원 일괄 인증 저장")]
    public String updateCertifyComplete(String consent_rids, String ocrtags, String instcd) {
      String result = "N";

      try {
        Hashtable param1 = new Hashtable();
        Hashtable param2 = new Hashtable();

        param1.Add("consent_rids", consent_rids);
        param1.Add("instcd", instcd);

        param2.Add("ocrtags", ocrtags);
        param2.Add("instcd", instcd);

        using (ConsentDac dac = new ConsentDac()) {
          // 동의서 테이블 master
          dac.updateToCertifyConsentMst(this.IbatisMapper, param1);
          // 경북대학교병원 출력 로그 테이블
          dac.updateToCertifyOcrprnt(this.IbatisMapper, param2);
        }
        result = "Y";
      } catch (Exception ex) {
        if (this.IbatisSession != null) this.IbatisSession.RollBackTransaction();
        result = "N";
        CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(
            String.Format("CLIP.eForm updateCertifyComplete ERROR : [{0}]", ex.ToString()));
      }

      return result;
    }

    /// <summary>
    /// 전자동의서 프린트 출력 오류 시 프린트 로그 삭제 메서드
    /// </summary>
    /// <param name="pid"></param>
    /// <param name="ocrtag"></param>
    /// <param name="instcd"></param>
    [WebMethod(Description = "프린터 출력 오류 시 출력 히스토리 삭제")]
    public void updatePrintHistory(String pid, String ocrtag, String instcd) {
      try {
        Hashtable param1 = new Hashtable();

        param1.Add("pid", pid);
        param1.Add("instcd", instcd);
        param1.Add("ocrtag", ocrtag);

        using (ConsentDac dac = new ConsentDac()) {
          dac.updateOcrPrintHistory(this.IbatisMapper, param1);
          dac.updateConsentMaster(this.IbatisMapper, param1);
        }

      } catch (Exception ex) {
        if (this.IbatisSession != null) this.IbatisSession.RollBackTransaction();
        CLIP.eForm.Server.Diagnostics.LogHelper.LoggingHandler.Error(
            String.Format("CLIP.eForm updatePrintHistory ERROR : [{0}]", ex.ToString()));
      }
    }

    /// <summary>
    /// 동의서 선택시 해당일에 대해 중복으로 작성되었는지 확인 (즐겨찾기와 동의서 찾기에서 확인해야함)
    /// </summary>
    /// <param name="pid"></param>
    /// <param name="instCd"></param>
    /// <param name="formCd"></param> '000000', '000001', '000002' 콤마로 붙여야함
    [WebMethod(Description = "동의서 선택시 해당일에 대해 중복으로 작성되었는지 확인")]
    public SingleReturnData duplicateCertConsent(String pid, String instCd, String formCd) {
      SingleReturnData result = new SingleReturnData();
      using (ConsentDac dac = new ConsentDac()) {
        Hashtable param = new Hashtable();
        param.Add("pid", pid);
        param.Add("instCd", instCd);
        param.Add("formCd", formCd);

        String res = dac.getDupCertConsent(this.IbatisMapper, param);

        result.responseData = res;

        return result;
      }
    }

    /// <summary>
    /// 진정동의서 출력 여부 확인
    /// </summary>
    /// <param name="instcd">사용자 근무지 기관코드</param>
    /// <param name="formcd">조회할 서식 코드</param>
    /// <returns>출력 하여야 할 서식이라면 0 초과의 값을 리턴</returns>
    /// 0보다 크면 진정동의서 작성 0이면 기존 link서식 작성
    [WebMethod(Description = "진정동의서 출력 여부 확인")]
    public int checkJinJeongDocument(String instcd, String formcd) {
      
      using (ConsentDac dac = new ConsentDac()) {
        int result = 0;
        Hashtable param = new Hashtable();
        param.Add("instcd", instcd);
        param.Add("formcd", formcd);
        
        result = dac.checkJinJeongDocument(this.IbatisMapper, param);
        return result;
      }
    }

    /// <summary>
    /// 기관코드별 마취 동의서 서식 코드를 조회한다
    /// </summary>
    /// <param name="instcd"></param>
    /// <returns>마취동의서 서식 코드</returns>
    [WebMethod(Description = "마취동의서 서식 코드 조회")]
    public String getLinkedAnstDocument(String instcd) {
      using (ConsentDac dac = new ConsentDac()) {
        String formCd = null;
        Hashtable param = new Hashtable { { "instcd", instcd } };
        formCd = dac.getLinkedAsntDocument(this.IbatisMapper, param);
        return formCd;
      }
    }

    [WebMethod(Description = "수술 관련 동의서 조회")]
    public string checkOperationDocument(String instcd, String formCd) {
      using (ConsentDac dac = new ConsentDac()) {
        Hashtable param = new Hashtable();
        param.Add("instcd", instcd);
        param.Add("formCd", formCd);

        return dac.checkOperationDocuemnt(this.IbatisMapper, param);
      }
    }

    public byte[] Zip(string str) {
      var bytes = Encoding.UTF8.GetBytes(str);

      using (var msi = new MemoryStream(bytes))
      using (var mso = new MemoryStream()) {
        using (var gs = new GZipStream(mso, CompressionMode.Compress)) {
          CopyTo(msi, gs);
        }

        return mso.ToArray();
      }
    }

    public string Unzip(byte[] bytes) {
      using (var msi = new MemoryStream(bytes))
      using (var mso = new MemoryStream()) {
        using (var gs = new GZipStream(msi, CompressionMode.Decompress)) {
          CopyTo(gs, mso);
        }

        return Encoding.UTF8.GetString(mso.ToArray());
      }
    }

    public void CopyTo(Stream src, Stream dest) {
      byte[] bytes = new byte[4096];

      int cnt;

      while ((cnt = src.Read(bytes, 0, bytes.Length)) != 0) {
        dest.Write(bytes, 0, cnt);
      }
    }

  }
}
