package com.dbs.mplus.fatima.adapter;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.GradientDrawable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;

import com.dbs.mplus.fatima.R;
import com.dbs.mplus.fatima.activity.ConsentActivity;
import com.dbs.mplus.fatima.activity.ImageActivity;
import com.dbs.mplus.fatima.consent.ConsentFacade;
import com.dbs.mplus.fatima.consent.ConsentParameter;
import com.dbs.mplus.fatima.httpTask.DataParser;
import com.dbs.mplus.fatima.httpTask.HttpCallBack;
import com.dbs.mplus.fatima.httpTask.HttpCon;
import com.dbs.mplus.fatima.httpTask.SoapParser;
import com.dbs.mplus.fatima.model.ConsentImageListVO;
import com.dbs.mplus.fatima.model.ConsentWriteListVO;
import com.dbs.mplus.fatima.model.PatientInfoVO;
import com.dbs.mplus.fatima.util.ConsentConfig;
import com.dbs.mplus.fatima.util.Util;

import org.json.JSONObject;
import org.ksoap2.serialization.SoapObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.concurrent.ExecutionException;

public class ConsentWriteAdapter extends RecyclerView.Adapter<ConsentWriteAdapter.ViewHolder> {

  private static final String TAG = "ConsentWriteAdapter";
  private AppCompatActivity mActivity;

  private Context mContext;
  private ConsentActivity instance;
  public ArrayList<ConsentWriteListVO> arrayList;

//  private String userId  = "";
//  private String userName = "";
  private String apiType = "";

  public HashMap<Integer, Object> checkMap;

  public ConsentWriteAdapter(AppCompatActivity mActivity, Context mContext, ArrayList<ConsentWriteListVO> arrayList, String apiType) {
    this.mActivity = mActivity;
    this.mContext = mContext;
    this.arrayList = arrayList;
    this.instance  = (ConsentActivity) mContext;
//    this.userId    = Util.getStringPreference(mContext, "userInfo", "emplNo");
//    this.userName = Util.getStringPreference(mContext, "userInfo", "name");
    this.checkMap = new HashMap<Integer, Object>();
    this.apiType = apiType;
  }

  @Override
  public int getItemCount() {
    return arrayList.size();
  }

  public class ViewHolder extends RecyclerView.ViewHolder {

    public RelativeLayout listLayer;
    public TextView tvConsentName;
    public TextView tvPatientName;
    public TextView tvTemp;
    public TextView tvSubText;
    public CheckBox chkConsent;

    public int position = 0;

    public ViewHolder(@NonNull View itemView) {
      super(itemView);
    }
  }

  @NonNull
  @Override
  public ConsentWriteAdapter.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
    View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.consent_list_item, parent, false);
    ViewHolder holder = new ViewHolder(view);

    holder.listLayer     = (RelativeLayout) view.findViewById(R.id.listLayer);
    holder.tvConsentName = (TextView) view.findViewById(R.id.tvConsentName);
    holder.tvPatientName = (TextView) view.findViewById(R.id.tvPatientName);
    holder.tvTemp        = (TextView) view.findViewById(R.id.tvTemp);
    holder.tvSubText     = (TextView) view.findViewById(R.id.tvSubText);
    holder.chkConsent    = (CheckBox) view.findViewById(R.id.chkConsent);

    holder.listLayer.setTag(holder);
    holder.tvSubText.setTag(holder);
    holder.chkConsent.setTag(holder);
    return holder;
  }

  @Override
  public void onBindViewHolder(@NonNull ConsentWriteAdapter.ViewHolder holder, int position) {
    ConsentWriteListVO consentWriteListVO = arrayList.get(position);
    String consentState = consentWriteListVO.getConsentState();
    String formName = consentWriteListVO.getFormNm();
    String pid = consentWriteListVO.getPid();
    String hngNm = consentWriteListVO.getHngNm();
    String consentStateDisp = "";

    GradientDrawable tvSubBg = (GradientDrawable) holder.tvSubText.getBackground().getCurrent();

    SpannableStringBuilder builder = new SpannableStringBuilder();
    SpannableString colorSpannable = new SpannableString(pid);
    colorSpannable.setSpan(new ForegroundColorSpan(ContextCompat.getColor(mContext, R.color.commonColor)), 0, pid.length(), 0);
    builder.append(colorSpannable);
    builder.append(" " + hngNm);

    GradientDrawable tvSubText = (GradientDrawable) holder.tvSubText.getBackground().getCurrent();
    if (consentState.equals(ConsentConfig.UNFINISHED)) {
      tvSubText.setColor(ContextCompat.getColor(mContext, R.color.alertColor));
      consentStateDisp = mContext.getString(R.string.tempSave);
    } else if (consentState.equals(ConsentConfig.TEMP) || consentState.equals(ConsentConfig.FNU_PRINT)) {
      tvSubText.setColor(ContextCompat.getColor(mContext, R.color.tempColor));
      if (consentState.equals(ConsentConfig.TEMP)) {
        consentStateDisp = mContext.getString(R.string.noWrite);
      } else {
        consentStateDisp = mContext.getString(R.string.fnuPrint);
      }
    } else if (consentState.equals(ConsentConfig.VERBAL)) {
      tvSubText.setColor(ContextCompat.getColor(mContext, R.color.vervbalColor));
      consentStateDisp = mContext.getString(R.string.checkGudu);
    } else if (consentState.equals(ConsentConfig.ELECTR_CMP)) {
      tvSubText.setColor(ContextCompat.getColor(mContext, R.color.userDeptColor));
      consentStateDisp = mContext.getString(R.string.electSign);
    } else if (consentState.equals(ConsentConfig.CERTIFY_CMP)) {
      tvSubText.setColor(ContextCompat.getColor(mContext, R.color.sexNAgeColor));
      consentStateDisp = mContext.getString(R.string.cert);
    } else if (consentState.equals(ConsentConfig.PAPER_OUT)) {
      tvSubText.setColor(ContextCompat.getColor(mContext, R.color.paperOutcolor));
      consentStateDisp = mContext.getString(R.string.print);
    }

    holder.chkConsent.setChecked(false);
    holder.chkConsent.setVisibility(View.VISIBLE);
    holder.tvTemp.setVisibility(View.GONE);

    holder.tvPatientName.setText(builder, TextView.BufferType.SPANNABLE);
    holder.tvConsentName.setText(formName);
    holder.tvSubText.setText(consentStateDisp);

    holder.chkConsent.setOnCheckedChangeListener(onCheckedChangeListener);
    holder.listLayer.setOnClickListener(onClickListener);

    if (checkMap.containsKey(holder.position) == true) {
      holder.chkConsent.setChecked(true);
    } else {
      holder.chkConsent.setChecked(false);
    }
  }

  private View.OnClickListener onClickListener = new View.OnClickListener() {
    @Override
    public void onClick(View view) {
      ViewHolder holder = (ViewHolder) view.getTag();
      int position = holder.getLayoutPosition();
      ConsentWriteListVO consentWriteListVO = arrayList.get(position);
      String consentState = consentWriteListVO.getConsentState();
      String consentMstRid = consentWriteListVO.getConsentMstRid();

      if (holder.listLayer == view) {
        holder.chkConsent.setChecked(true);
        if (consentState.equals(ConsentConfig.CERTIFY_CMP)) {
          notifyDataSetChanged();
          checkMap.clear();
          HashMap<String, String> mData = new HashMap<String, String>();
          mData.put("consentMstRid", consentMstRid);
//          HttpSoapConnection connection = new HttpSoapConnection(ConsentConfig.HOST_CONSENT, ConsentConfig.GET_CONSENT_IMAGE, mData);
//          try {
//            SoapObject object = connection.execute().get();
//            ArrayList<ConsentImageListVO> arrayList = SoapParser.getConsetImageList(object);
//            if (arrayList.size() == 0) {
//              instance.csAlert.show();
//              instance.csAlert.setContent(mContext.getString(R.string.imageLoadFailed), ConsentConfig.ALERT_BTN_TYPE);
//              instance.csAlert.btnConfirm2.setOnClickListener(new View.OnClickListener() {
//                @Override
//                public void onClick(View view) {
//                  instance.csAlert.dismiss();
//                }
//              });
//            } else {
//              Intent intent = new Intent(mContext, ImageActivity.class);
//              intent.putExtra("imageArray", arrayList);
//              instance.startActivity(intent);
//            }
//          } catch (ExecutionException e) {
//            e.printStackTrace();
//          } catch (InterruptedException e) {
//            e.printStackTrace();
//          }

          HttpCon con = new HttpCon(ConsentConfig.HOST_CONSENT, mData, ConsentConfig.GET_CONSENT_IMAGE);
          try {
            String result = con.execute().get();
            if (result.equals("")) {
              instance.csAlert.show();
              instance.csAlert.setContent(mContext.getString(R.string.imageLoadFailed), ConsentConfig.ALERT_BTN_TYPE);
              instance.csAlert.btnConfirm2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                  instance.csAlert.dismiss();
                }
              });
            } else {
              ArrayList<ConsentImageListVO> arrayList = DataParser.getConsetImageList(mContext, result);
              if (arrayList.size() == 0) {
                instance.csAlert.show();
                instance.csAlert.setContent(mContext.getString(R.string.imageLoadFailed), ConsentConfig.ALERT_BTN_TYPE);
                instance.csAlert.btnConfirm2.setOnClickListener(new View.OnClickListener() {
                  @Override
                  public void onClick(View view) {
                    instance.csAlert.dismiss();
                  }
                });
              } else {
                Intent intent = new Intent(mContext, ImageActivity.class);
                intent.putExtra("imageArray", arrayList);
                instance.startActivity(intent);
              }
            }

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

          return;
        }

        final ArrayList<String> printOnly = new ArrayList<>();
        final ArrayList<ConsentWriteListVO> selectConsentList = new ArrayList<>();
        String patientId = "";
        int cnt = 0;
        for (int key : checkMap.keySet()) {
          ConsentWriteListVO _consentWriteListVO = arrayList.get(key);
          String _consentMstRid = _consentWriteListVO.getConsentMstRid();
          String _consentState = _consentWriteListVO.getConsentState();
          String _consentName = _consentWriteListVO.getFormNm();
          String _patientId = _consentWriteListVO.getPid();

          if (cnt == 0) {
            patientId = _patientId;
          }

          Log.e(TAG, "patientId -- > " + patientId);
          Log.e(TAG, "_patientId -- > " + _patientId);

          if (!patientId.equals(_patientId)) {
            instance.csAlert.show();
            instance.csAlert.setContent(mContext.getString(R.string.samePatientId), ConsentConfig.ALERT_BTN_TYPE);
            instance.csAlert.btnConfirm2.setOnClickListener(new View.OnClickListener() {
              @Override
              public void onClick(View view) {
                instance.csAlert.dismiss();
                printOnly.clear();
                selectConsentList.clear();
              }
            });
            return;
          }

          patientId = _patientId;

          if (consentState.equals(ConsentConfig.PAPER_OUT) ||  consentState.equals(ConsentConfig.FNU_PRINT)) {
            printOnly.add("[" + _consentName + "] - "  + (_consentState.equals(ConsentConfig.PAPER_OUT) ? mContext.getString(R.string.print) : mContext.getString(R.string.fnuPrint)));
          } else {
            HashMap<String, String> mData = new HashMap<>();
            mData.put("consentmstrid", _consentMstRid);
            mData.put("consent_state", _consentState);

            HttpCon con = new HttpCon(ConsentConfig.HOST_CONSENT, mData, ConsentConfig.CHECK_CONSENT_STATE);
            try {
              String result = con.execute().get();
              if (!result.equals("")) {
                JSONObject object = Util.xmltoJsonObject(result);
                String res = Util.xmlToJsonString(object);
                ArrayList<HashMap<String, String>> mapArrayList = Util.parseJSON(mContext, res);

                String state = mapArrayList.get(0).get("CheckConsentStateResult");
                Log.e(TAG, "state -- > " + state);
                if (state.equals("-1")) {
                  printOnly.add("[" + _consentName + "] - " + mContext.getString(R.string.stateFail));
                } else if (state.equals("1")) {
                  printOnly.add("[" + _consentName + "] - " + mContext.getString(R.string.writeConsent));
                } else if (state.equals("0")) {
                  selectConsentList.add(_consentWriteListVO);
                }
              }
            } catch (ExecutionException e) {
              e.printStackTrace();
            } catch (InterruptedException e) {
              e.printStackTrace();
            }
          }

          cnt = cnt + 1;
        }

        if (selectConsentList.size() > 0) {
          ConsentWriteListVO selectConsentVO = arrayList.get(0);
          String pid = selectConsentVO.getPid();
          String ordDd = selectConsentVO.getOrdDd();
          String ordType = selectConsentVO.getOrdType();
          String ordDeptCd = selectConsentVO.getOrdDeptCd();
          String cretNo = selectConsentVO.getCretNo();

          HashMap<String, String> mData = new HashMap<>();
          mData.put("pid", pid);
          mData.put("orddd", ordDd);
          mData.put("ordtype", ordType);
          mData.put("orddeptcd", ordDeptCd);
          mData.put("cretno", cretNo);

//          HttpSoapConnection connection = new HttpSoapConnection(ConsentConfig.HOST_HOSPITAL, ConsentConfig.GET_PATIENT_INFO, mData);
          HttpCon connection = new HttpCon(ConsentConfig.HOST_HOSPITAL, mData, ConsentConfig.GET_PATIENT_INFO);
          PatientInfoVO patientInfoVO = null;
          try {
            String result = connection.execute().get();
            patientInfoVO = DataParser.getPatientInfo(mContext, result);
            if (patientInfoVO == null) {
              instance.showSingButtonDialog(mContext.getString(R.string.failedPatientInfo));
              return;
            }

            String certUserId = "";
            String certuserNm = "";
            if (instance.mobile.equals("O")) {
              certUserId = patientInfoVO.getMainDrId();
              certuserNm = patientInfoVO.getMainDrNm();
            } else {
              certUserId = Util.getStringPreference(mContext, "userInfo", "emplNo");
              certuserNm = Util.getStringPreference(mContext, "userInfo", "name");
            }

            // 담당의가 일반의사인 경우 무조건 출력전용 이므르 alert 메시지 띄우고 리턴한다
            // 16.12.12 #6225 siyoung.ahn
            if (certUserId.startsWith("5000") && instance.mobile.equals("O")) {
              instance.csAlert.show();
              instance.csAlert.setContent(mContext.getString(R.string.doctorMsg), ConsentConfig.ALERT_BTN_TYPE);
              instance.csAlert.btnConfirm2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                  instance.csAlert.dismiss();
                }
              });
              return;
            }

            String printOnlyAlertMsg = "";
            if (printOnly.size() > 0) {
              printOnlyAlertMsg = printOnly.get(printOnly.size() - 1) + "\n";
            }

            final PatientInfoVO finalPatientInfoVO = patientInfoVO;

            if (printOnlyAlertMsg.length() > 0) {
              instance.csAlert.show();
              instance.csAlert.setContent(mContext.getString(R.string.printOnlyConsent) + "\n" + printOnlyAlertMsg, "");
              final String finalCertuserNm = certuserNm;
              final String finalCertUserId = certUserId;
              instance.csAlert.btnConfirm.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                  instance.csAlert.dismiss();
                  if (selectConsentList.size() > 0) {
                    HashMap<String, Object> param = new HashMap<String, Object>();
                    HashMap<String, String> globalParam = new HashMap<String, String>();
                    ArrayList<HashMap<String, Object>> consentParam = new ArrayList<HashMap<String, Object>>();
                    globalParam = ConsentParameter.makeGlobalParam(finalPatientInfoVO, finalCertUserId, mContext);
                    consentParam = ConsentParameter.makeConsent(finalPatientInfoVO, selectConsentList, finalCertuserNm, "write", mContext);

                    param.put("globalParam", globalParam);
                    param.put("consentParam", consentParam);

                    ConsentFacade consentFacade = new ConsentFacade(mContext);
                    consentFacade.startConsent(param, apiType, finalCertUserId);

                    instance.centerMenu.clearPatientInfo();
                  }
                }
              });

              instance.csAlert.btnCancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                  instance.csAlert.dismiss();
                }
              });
            } else {
              HashMap<String, Object> param = new HashMap<String, Object>();
              HashMap<String, String> globalParam = new HashMap<String, String>();
              ArrayList<HashMap<String, Object>> consentParam = new ArrayList<HashMap<String, Object>>();
              globalParam = ConsentParameter.makeGlobalParam(finalPatientInfoVO, certUserId, mContext);
              consentParam = ConsentParameter.makeConsent(finalPatientInfoVO, selectConsentList, certuserNm, "write", mContext);

              param.put("globalParam", globalParam);
              param.put("consentParam", consentParam);

              ConsentFacade consentFacade = new ConsentFacade(mContext);
              consentFacade.startConsent(param, apiType, certUserId);
              instance.centerMenu.clearPatientInfo();
            }

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

        }

        notifyDataSetChanged();
        checkMap.clear();
      }

    }
  };

  private CheckBox.OnCheckedChangeListener onCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
      ViewHolder holder = (ViewHolder) buttonView.getTag();
      final int position = holder.getLayoutPosition();
      ConsentWriteListVO consentWriteListVO = arrayList.get(position);
      String consentMstRid = consentWriteListVO.getConsentMstRid();

      if (isChecked == true) {
        checkMap.put(position, consentMstRid);
      } else {
        checkMap.remove(position);
      }

    }
  };
}
