package com.dbs.mplus.knuh.consent;

import android.content.Context;
import android.os.Build;
import android.util.Log;

import com.dbs.mplus.knuh.BuildConfig;
import com.dbs.mplus.knuh.R;
import com.dbs.mplus.knuh.activity.ConsentActivity;
import com.dbs.mplus.knuh.httpTask.HttpSoapConnection;
import com.dbs.mplus.knuh.model.ConsentFormListVO;
import com.dbs.mplus.knuh.model.PatientInfoVO;
import com.dbs.mplus.knuh.model.UserVO;
import com.dbs.mplus.knuh.util.ConsentConfig;
import com.dbs.mplus.knuh.util.Util;

import org.ksoap2.serialization.SoapObject;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.concurrent.ExecutionException;

public class ConsentCreateParam {
  private static final String TAG = "ConsentCreateParam";
  private Context mContext;
  private String indexPage  = "";
  private String userDrFlag = "";
  private String consentState = "";
  private String consentStateEng = "";

  public ConsentCreateParam(Context mContext, String userDrFlag, String consentState, String consentStateEng) {
    this.mContext        = mContext;
    this.indexPage       = ((ConsentActivity) mContext).indexPage;
    this.userDrFlag      = userDrFlag;
    this.consentState    = consentState;
    this.consentStateEng = consentStateEng;
  }


  public HashMap<String, String> setGlobalParam(PatientInfoVO patientInfoVO, String consentMstRid, ConsentFormListVO consentFormListVO) {
    HashMap<String, String> map = new HashMap<String, String>();
    String loginUserId         = Util.getStringPreference(mContext, "userInfo", "userId");
    String loginUserName       = Util.getStringPreference(mContext, "userInfo", "userName");
    String loginUserDeptCd    = Util.getStringPreference(mContext, "userInfo", "deptCd");
    String loginUserJobKindCd = Util.getStringPreference(mContext, "userInfo", "jobKindCd");

    int rid = Integer.parseInt(consentMstRid);

    String ordDeptCd   = patientInfoVO.getOrdDeptCd();
    String deptEngAbbr = patientInfoVO.getDeptEngAbbr();
    String ordDeptNm   = patientInfoVO.getOrdDeptNm();
    String pid         = patientInfoVO.getPid();
    String cretNo      = patientInfoVO.getCretNo();
    String roomCd      = patientInfoVO.getRoomCd();
    String inDd        = patientInfoVO.getInDd();
    String dschDd      = patientInfoVO.getDschDd();
    String ordType     = patientInfoVO.getOrdType();
    String instCd      = patientInfoVO.getInstCd();
    String mainDrId    = patientInfoVO.getMainDrId();
    String mainDrName  = patientInfoVO.getMainDrName();
    String erDrNm      = patientInfoVO.getErDrNm();
    String firstRgstDt = patientInfoVO.getFirstRgstDt();
    String sa          = patientInfoVO.getSa();
    String patientName = patientInfoVO.getPatientName();
    String juminNo     = patientInfoVO.getJuminNo();
    String zipCdAddr   = patientInfoVO.getZipCdAddr();
    String telNum      = patientInfoVO.getTelNum();
    String insuKind    = patientInfoVO.getInsuKind();
    String ward        = patientInfoVO.getWard();
    String dxCd        = patientInfoVO.getDxCd();
    String dxNm        = patientInfoVO.getDxNm();
    String gbn         = patientInfoVO.getGbn();
    String opDeptCd    = patientInfoVO.getOpDeptCd();
    String opDeptNm    = patientInfoVO.getOpDeptNm();
    String opDrNm      = patientInfoVO.getOpDrNm();
    String opDrId      = patientInfoVO.getOpDrId();
    String opCnfmDd    = patientInfoVO.getOpCnfmDd();
    String perfDrNm    = patientInfoVO.getPerfDrNm();
    String perfDrFlag  = patientInfoVO.getPerfDrFlag();
    String perfDrDept  = patientInfoVO.getPerfDrDept();
    String opDiagNm    = patientInfoVO.getOpDiagNm();
    String opNm        = patientInfoVO.getOpNm();
    String anstDrNm1   = patientInfoVO.getAnstDrNm1();
    String anstDrFlag1 = patientInfoVO.getAnstDrFlag1();
    String anstDeptNm1 = patientInfoVO.getAnstDeptNm1();
    String anstDrNm2   = patientInfoVO.getAnstDrNm2();
    String anstDrFlag2 = patientInfoVO.getAnstDrFlag2();
    String anstDeptNm2 = patientInfoVO.getAnstDeptNm2();
    String anstDrNm3   = patientInfoVO.getAnstDrNm3();
    String anstDrFlag3 = patientInfoVO.getAnstDrFlag3();
    String anstDeptNm3 = patientInfoVO.getAnstDeptNm3();
    String opRsrvNo    = patientInfoVO.getOpRsrvNo();
    String orderNo     = patientInfoVO.getOrderNo();
    String printTime   = patientInfoVO.getPrintTime();
    String ocrCd       = patientInfoVO.getOcrCd();
    String inputId     = patientInfoVO.getInputId();
    String inputNm     = patientInfoVO.getInputNm();
    String signImg     = patientInfoVO.getSignImg();
    String bp          = patientInfoVO.getBp();
    String dm          = patientInfoVO.getDm();
    String heart       = patientInfoVO.getHeart();
    String kidney      = patientInfoVO.getKidney();
    String respiration = patientInfoVO.getRespiration();
    String hx          = patientInfoVO.getHx();
    String allergy     = patientInfoVO.getAllergy();
    String drug        = patientInfoVO.getDrug();
    String smoking     = patientInfoVO.getSmoking();
    String idio        = patientInfoVO.getIdio();
    String nacrotics   = patientInfoVO.getNacrotics();
    String airway      = patientInfoVO.getAirway();
    String hemorrhage  = patientInfoVO.getHemorrhage();
    String statusEtc   = patientInfoVO.getStatusEtc();
    String signImage   = "";

    HashMap<String, String> mData = new HashMap<String, String>();

    if (!userDrFlag.equals("Y")) {
      mData.put("userId", loginUserId);
      mData.put("deptCd", loginUserDeptCd);
      map.put("mainDrId", loginUserId);
    } else {
      mData.put("userId", loginUserId);
      mData.put("deptCd", loginUserDeptCd);
      map.put("mainDrId", mainDrId);
    }

    if (userDrFlag.equals("Y") && ordType.equals("O")) {
      mData.put("userId", mainDrId);
      mData.put("deptCd", ordDeptCd);
      map.put("mainDrId", mainDrId);
    }

    mData.put("instCd", BuildConfig.INST_CD);

    UserVO userVO = getUserInfo(mData);
    if (userVO.getUserId().equals("")) {
      mData.put("userId", loginUserId);
      mData.put("deptCd", loginUserDeptCd);
      userVO = getUserInfo(mData);
    }

    signImage = getSignImage(mData);

    map.put("parCMSGBD_ExplDrNm", "");
    map.put("parCMSGBD_ExplDrSignature", "");
    map.put("parCMSGBD_ExplDrTelNo", "");

    if (userVO.getJobKindCd().indexOf("03") == 0) {
      map.put("parCMSGBD_ExplDrNm", userVO.getUserName());
      map.put("parCMSGBD_ExplDrSignature", signImage);
      map.put("parCMSGBD_ExplDrTelNo", userVO.getUserTelNo());
    }

    // 새 서식을 작성할 경우
    if (rid == 0 || consentStateEng.equals(ConsentConfig.UNFINISHED)) {
      String[] ipAddressAr = Util.getIpAddress(mContext).split("[.]");

      String ipAddress = ipAddressAr[2] + "." + ipAddressAr[3];
      map.put("parCMDCFT_device", "M");
      map.put("parCMDCFT_1PrintIP", ipAddress);
      map.put("parCMDCHD_1PatientNo", pid);
      map.put("parCMDCHD_1SexAge", sa);
      map.put("parCMDCHD_1PatientNm", patientName);
      map.put("parCMDCHD_1SocialSecuNo", juminNo);
      map.put("parNUR_Fast_HospitalroomNo", roomCd);
      map.put("parCMDCHD_1VisitDt", Util.addSlashDate(inDd));
      map.put("parCMDCHD_1DepartmentNm", deptEngAbbr);
      map.put("parCMDCHD_1DepartmentCd", ordDeptCd);

      map.put("parCMDCBD_PopupV1_SurgeryDoctor", perfDrNm);
      map.put("parCMDCBD_PopupV1_DxNm", !opDiagNm.equals("") ? opDiagNm : dxNm);
      map.put("parCMDCBD_DiseaseBox_bp", bp);
      map.put("parCMDCBD_DiseaseBox_dm", dm);
      map.put("parCMDCBD_DiseaseBox_1CardioVascular", heart);
      map.put("parCMDCBD_DiseaseBox_3Metabolic", kidney);
      map.put("parCMDCBD_DiseaseBox_2Respiratory", respiration);
      map.put("parCMDCBD_DiseaseBox_9History1", hx);
      map.put("parCMDCBD_DiseaseBox_4UnusualConstitution2", allergy);
      map.put("parCMDCBD_DiseaseBox_6Medicine", drug);
      map.put("parCMDCBD_DiseaseBox_8HabitSmoking", smoking);
      map.put("parCMDCBD_DiseaseBox_4UnusualConstitution1", idio);
      map.put("parCMDCBD_DiseaseBox_9History2", nacrotics);
      map.put("parCMDCBD_DiseaseBox_7Airway", airway);
      map.put("parCMDCBD_DiseaseBox_5Blood", hemorrhage);
      map.put("parCMDCBD_status_etc", statusEtc);

      map.put("parCMDCBD_signdate", opCnfmDd);

      map.put("parCMDCBD_signtime", "");
      map.put("parCMDCFT_1PrintDt", "");
      map.put("parCMDCBD_Doctor_Doctor1Nm", mainDrName); // 담당의사

      map.put("parCMSGBD_INPUTNm", userVO.getUserName());

      map.put("parCMSGBD_INPUTSignature", signImage);
      map.put("parCMSGBD_PT_address", zipCdAddr);
      map.put("parCMSGBD_PT_tel", telNum);
      map.put("parCMSGBD_Insukind", insuKind);
      map.put("parCMSGBD_PT_birthday", juminNo.split("-")[0]);
      Log.e(TAG, "opopopopop -- > " + opNm);
      map.put("parCMDCBD_PopupV1_OPNm", opNm.equals("") ? consentFormListVO.getOpNm() : opNm);
      map.put("parCMDCBD_PopupV1_SPNm", opNm.equals("") ? consentFormListVO.getOpNm() : opNm);
      map.put("parCMSGBD_INPUTTelNo", userVO.getUserTelNo());
      map.put("parDEFAULT_DUTINSTCD", instCd);
//      map.put("parDEFAULT_POPUP_PATH", "https://ema031.knuh.kr:9091");
      map.put("parDEFAULT_POPUP_PATH", BuildConfig.CONSENT_SERVER_URL);
      map.put("parCMDCBD_PopupV1_SurgeryDepartment", perfDrFlag.equals("전문의") ? perfDrDept : "");
      map.put("parCMDCBD_PopupV1_SurgeryCommonDepartment", perfDrFlag.equals("전공의") ? perfDrDept : "");
      map.put("parCMDCBD_Anst1DrNm", anstDrNm1);
      map.put("parCMDCBD_Anst1DeptNm", anstDrFlag1.equals("전문의") ? anstDeptNm1 : "");
      map.put("parCMDCBD_Anst1CommonDeptNm", !anstDrFlag1.equals("전문의") ? anstDeptNm1 : "");
      map.put("parCMDCBD_Anst2DrNm", anstDrNm2);
      map.put("parCMDCBD_Anst2DeptNm", anstDrFlag2.equals("전문의") ? anstDeptNm2 : "");
      map.put("parCMDCBD_Anst2CommonDeptNm", !anstDrFlag2.equals("전문의") ? anstDeptNm2 : "");
      map.put("parCMDCBD_Anst3DrNm", anstDrNm3);
      map.put("parCMDCBD_Anst3DeptNm", anstDrFlag3.equals("전문의") ? anstDeptNm3 : "");
      map.put("parCMDCBD_Anst3CommonDeptNm", !anstDrFlag3.equals("전문의") ? anstDeptNm3 : "");
      map.put("parCMSGBD_INPUTDeptcd", userVO.getUserDeptCode());
      map.put("parCMSGBD_Cretno", cretNo);
      map.put("parCMDCBD_OpRsrvNo", opRsrvNo);
      map.put("parCMDCHD_1PatientNmFix", patientName);
      map.put("parCMSGBD_PT_birthdayFix", juminNo.split("-")[0]);
      map.put("parCMSGBD_PT_telFix", telNum);

      map.put("parCMDCBD_SpDrYN", "");
      map.put("parCMDCBD_ContStartDate", "");
      map.put("parCMDCBD_ContEndDate", "");
      map.put("parCMDCBD_RoomCapa", "");
      map.put("parCMDCBD_ContStaff1Name", "");
      map.put("parCMDCBD_ContStaff2Name", "");
      map.put("parCMDCBD_ContStaff3Name", "");
      map.put("parCMDCBD_CardNo", "");

      map.put("ordType", ordType);
      map.put("ward", ward);
      map.put("dschDd", dschDd);

      if(ward.length() > 0 && roomCd.length() > 0) {
        map.put("parNUR_Fast_HospitalroomNo", ward + '/' + roomCd);
      }

    } else {
      map.put("parCMDCHD_1PatientNo", pid);
      map.put("parCMDCHD_1DepartmentCd", opDeptCd);
      map.put("ordType", ordType);
      map.put("parCMDCHD_1VisitDt", Util.addSlashDate(inDd));
      map.put("ward", ward);
      map.put("parNUR_Fast_HospitalroomNo", roomCd);
      map.put("parCMSGBD_Cretno", cretNo);
      map.put("parCMDCBD_OpRsrvNo", opRsrvNo);
      map.put("dschDd", dschDd);

    }

    return map;
  }

  public ArrayList<HashMap<String, String>> setFormParam(String consentMstRid, String formRid, String guid, String formPrntNm, String formCd, String linkFormCd, String ocrTag) {
    ArrayList<HashMap<String, String>> mapArrayList = new ArrayList<HashMap<String, String>>();
    HashMap<String, String> map   = new HashMap<String, String>();
    HashMap<String, String> mData = new HashMap<String, String>();
    int rid = Integer.parseInt(consentMstRid);

    if(rid == 0 || consentStateEng.equals(ConsentConfig.UNFINISHED)) {
      map.put("newConsent", "true");
    } else {
      map.put("newConsent", "false");
    }
    map.put("parCMSGBD_ocr_cd", ocrTag.equals("") ? getOcrTag() : ocrTag);
    map.put("parCMDCFT_1PrintNm", formPrntNm);
    map.put("rid", consentMstRid);
    map.put("guid", guid);
    map.put("formCd", formCd);
    map.put("formRid", formRid);

    mapArrayList.add(map);

    if (!linkFormCd.equals("")) {
      mData.put("formCd", linkFormCd);
      mData.put("instCd", BuildConfig.INST_CD);
      Log.e(TAG, "mData -- > + " + mData);
      HttpSoapConnection connection = new HttpSoapConnection(ConsentConfig.HOST_CONSENT, ConsentConfig.GET_CONSENT_BY_FORMCD, mData);
      try {
        SoapObject object = connection.execute().get();

        if (object.getPropertyCount() > 1) {
          String _consentMstRid = object.getProperty("consentMstRid").toString().trim();
          String _formGuid      = object.getProperty("formGuid").toString().trim();
          String _formPrntNm    = object.getProperty("formPrntNm").toString().trim();
          String _formRid       = object.getProperty("formRid").toString().trim();
          String _formCd        = object.getProperty("formCd").toString().trim();

          HashMap<String, String> linkMap = new HashMap<String, String>();

          if(Integer.parseInt(_consentMstRid) == 0 || consentStateEng.equals(ConsentConfig.UNFINISHED)) {
            linkMap.put("newConsent", "true");
          } else {
            linkMap.put("newConsent", "false");
          }

          linkMap.put("parCMSGBD_ocr_cd", ocrTag.equals("") ? getOcrTag() : ocrTag);
          linkMap.put("rid", _consentMstRid);
          linkMap.put("guid", _formGuid);
          linkMap.put("formRid", _formRid);
          linkMap.put("formCd", _formCd);
          linkMap.put("parCMDCFT_1PrintNm", _formPrntNm);

          mapArrayList.add(linkMap);
        }
      } catch (ExecutionException e) {
        e.printStackTrace();
      } catch (InterruptedException e) {
        e.printStackTrace();
      }
    }

    return mapArrayList;
  }

  private String getOcrTag() {
    HashMap<String, String> mData = new HashMap<String, String>();
    mData.put("instCd", BuildConfig.INST_CD);
    HttpSoapConnection connection = new HttpSoapConnection(ConsentConfig.HOST_HOSPITAL, ConsentConfig.GET_OCR_TAG, mData);

    String ocrTag = "";
    try {
      SoapObject object = connection.execute().get();
      if (object != null) {
        ocrTag = object.getProperty("responseData").toString().trim();
      }
    } catch (ExecutionException e) {
      e.printStackTrace();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    return ocrTag;
  }

  private String getSignImage(HashMap<String, String> mData) {

    HttpSoapConnection connection = new HttpSoapConnection(ConsentConfig.HOST_HOSPITAL, ConsentConfig.GET_SIGN_DATA, mData);
    String signImage = "";
    try {
      SoapObject object = connection.execute().get();
      if (object != null) {
        signImage = object.getProperty("SignImage").toString().trim();
        signImage = signImage.equals(ConsentConfig.RETURN_NULL) ? "" : signImage;
      }

    } catch (ExecutionException e) {
      e.printStackTrace();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }

    return signImage;
  }

  private UserVO getUserInfo(HashMap<String, String> mData) {
    UserVO userVO = new UserVO();
    HttpSoapConnection connection = new HttpSoapConnection(ConsentConfig.HOST_HOSPITAL, ConsentConfig.GET_USER_INFO, mData);
    try {
      SoapObject object = connection.execute().get();
      Log.e(TAG, "object -- > " + object);
      String userId       = object.getProperty("userId").toString().trim();
      String userName     = object.getProperty("userName").toString().trim();
      String userDeptCode = object.getProperty("userDeptCode").toString().trim();
      String userDeptName = object.getProperty("userDeptName").toString().trim();
      String userDeptEngAbbr = object.getProperty("deptEngAbbr").toString().trim();
      String jobKindCd    = object.getProperty("jobKindCd").toString().trim();
      String jobKindNm    = object.getProperty("jobKindNm").toString().trim();
      String userInstCd   = object.getProperty("instCd").toString().trim();
      String userTelNo    = object.getProperty("userTelNo").toString().trim();
      String ioFlag       = object.getProperty("ioFlag").toString().trim();

      userId       = userId.equals(ConsentConfig.RETURN_NULL) ? "" : userId;
      userName     = userName.equals(ConsentConfig.RETURN_NULL) ? "" : userName;
      userDeptCode = userDeptCode.equals(ConsentConfig.RETURN_NULL) ? "" : userDeptCode;
      userDeptName = userDeptName.equals(ConsentConfig.RETURN_NULL) ? "" : userDeptName;
      userDeptEngAbbr  = userDeptEngAbbr.equals(ConsentConfig.RETURN_NULL) ? "" : userDeptEngAbbr;
      jobKindCd    = jobKindCd.equals(ConsentConfig.RETURN_NULL) ? "" : jobKindCd;
      jobKindNm    = jobKindNm.equals(ConsentConfig.RETURN_NULL) ? "" : jobKindNm;
      userInstCd   = userInstCd.equals(ConsentConfig.RETURN_NULL) ? "" : userInstCd;
      userTelNo    = userTelNo.equals(ConsentConfig.RETURN_NULL) ? "" : userTelNo;
      ioFlag       = ioFlag.equals(ConsentConfig.RETURN_NULL) ? "" : ioFlag;

      userVO.setUserId(userId);
      userVO.setUserName(userName);
      userVO.setUserDeptCode(userDeptCode);
      userVO.setUserDeptName(userDeptName);
      userVO.setDeptEngAbbr(userDeptEngAbbr);
      userVO.setJobKindCd(jobKindCd);
      userVO.setJobKindNm(jobKindNm);
      userVO.setUserInstCd(userInstCd);
      userVO.setUserTelNo(userTelNo);
      userVO.setIoFlag(ioFlag);

    } catch (ExecutionException e) {
      e.printStackTrace();
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    return userVO;
  }
}
