package com.dbs.consent.demo.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.AppCompatRadioButton;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.RecyclerView;
import androidx.viewpager.widget.ViewPager;

import android.content.Context;
import android.content.Intent;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.dbs.consent.demo.BuildConfig;
import com.dbs.consent.demo.R;
import com.dbs.consent.demo.activity.activityEvent.CenterMenu;
import com.dbs.consent.demo.activity.activityEvent.LeftMenu;
import com.dbs.consent.demo.activity.activityEvent.RightMenu;
import com.dbs.consent.demo.activity.activityEvent.TapMenu;
import com.dbs.consent.demo.activity.activityEvent.TopMenu;
import com.dbs.consent.demo.adapter.ConsentHistoryAdapter;
import com.dbs.consent.demo.adapter.ViewPagerAdapter;
import com.dbs.consent.demo.consent.sign.SignWrapper;
import com.dbs.consent.demo.customView.CustomAlertDialog;
import com.dbs.consent.demo.customView.CustomRadioGroup;
import com.dbs.consent.demo.customView.LoadingProgress;
import com.dbs.consent.demo.fragment.HistoryFragment;
import com.dbs.consent.demo.fragment.MarkerFragment;
import com.dbs.consent.demo.fragment.SearchFragment;
import com.dbs.consent.demo.util.ConsentConfig;
import com.dbs.consent.demo.util.Util;

public class ConsentActivity extends AppCompatActivity {

  private static final String TAG = "ConsentActivity";
  public AppCompatActivity mActivity;
  public Context mContext;
  private LoadingProgress loadingProgress;
  public CustomAlertDialog csAlert;
  private TopMenu topMenu;
  private TapMenu tapMenu;
  public LeftMenu leftMenu;
  public CenterMenu centerMenu;
  private RightMenu rightMenu;

  public HistoryFragment history;
  public MarkerFragment marker;
  public SearchFragment search;

  public ConsentHistoryAdapter consentCenterAdaper;
  public ConsentHistoryAdapter consentHistoryAdapter;

  /** 상단 메뉴 **/
  private ImageView ivLogo;
  private TextView tvEdu;
  private TextView tvConsent;
  private TextView tvDoctor;
  private TextView tvDept;
  private LinearLayout settingLayout;
  private LinearLayout logoutLayout;
  /** 상단 메뉴 **/
  /** 탭 메뉴 **/
  public LinearLayout tabAdmission;
  public ImageView ivInPatient;
  public TextView tvInPatient;
  public LinearLayout tabOutPatient;
  public ImageView ivOutPatient;
  public TextView tvOutPatient;
  public LinearLayout tabEmergency;
  public ImageView ivErPatient;
  public TextView tvErPatient;
  public LinearLayout tabSurgery;
  public ImageView ivOpPatient;
  public TextView tvOpPatient;
  public LinearLayout tabSearch;
  public ImageView ivSearchPatient;
  public TextView tvSearchPatient;
  /** 탭 메뉴 **/
  /** left Menu **/
  public LinearLayout dateLayout;
  public TextView tvMainDate;
  public LinearLayout wardLayout;
  public Spinner wardSpinner;
  public LinearLayout deptLayout;
  public Spinner deptSpinner;
  public LinearLayout doctorLayout;
  public Spinner doctorSpinner;
//  public CustomRadioGroup radioGroup;
//  public RadioButton radioBtn1;
//  public RadioButton radioBtn2;
//  public RadioButton radioBtn3;
//  public RadioButton radioBtn4;
//  public RadioButton radioBtn5;
  public RelativeLayout radioLayout;
  public CustomRadioGroup radioGroup;
  public CustomRadioGroup.LayoutParams radioGroupParams;
  public RelativeLayout.LayoutParams radioParams;
  public AppCompatRadioButton radioButton1;
  public AppCompatRadioButton radioButton2;
  public AppCompatRadioButton radioButton3;
  public AppCompatRadioButton radioButton4;
  public AppCompatRadioButton radioButton5;

  public EditText etPatientId;
  public LinearLayout patientSearchLayout;

  public RecyclerView patientRecyclerView;
  public TextView patientEmpty;
  public CheckBox chkMyPatient;
  public LinearLayout llPatientSort;
  public LinearLayout llPatientNmSort;
  public LinearLayout llRoomSort;
  public TextView column1;
  public TextView column4;
  public TextView column6;

  /** left Menu **/

  /** Center Menu **/
  public TextView tvPatientInfo;
  public TextView tvAdmissionDay;
  public TextView tvChargeDoctor;
  public TextView tvDiagnosisName;
  public TextView tvPatientAlert;
  public TextView tvTempCenterTxt;
  public RecyclerView tempRecyclerView;
  /** Center Meny **/

  /** Right Menu **/
  public LinearLayout historyLayout;
  public LinearLayout markerLayout;
  public LinearLayout searchLayout;

  public TextView     tvRightHistory;
  public TextView     tvRightMarker;
  public TextView     tvRightSearch;
  public ViewPager viewPager;
  /** Right Menu **/

  public boolean tapClick = false;
  private long backKeyPressedTime = 0;

  public String deptCd    = "";
  public String deptNm    = "";
  public String jobKindCd = "";
  public String jobKindNm = "";
  public String userId    = "";
  public String userName   = "";
  public String indexPage = "";
  public String drKind    = "";

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_consent);

    init();
  }

  @Override
  public boolean onTouchEvent(MotionEvent event) {
    InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
    if (getCurrentFocus() == null) {
      return false;
    }
    imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);

    return true;
  }

  private void init() {
    mActivity = this;
    mContext  = this;

    getIntentData();

    setTopMenuLayout();
    setTapMenuLayout();
    setCenterLayout();
    setLeftLayout();
    setRightLayout();
    setTopMenuEvent();
  }

  private void getIntentData() {
    Intent intent = getIntent();
    deptCd     = intent.getStringExtra("deptCd");
    deptNm     = intent.getStringExtra("deptNm");
    jobKindCd  = intent.getStringExtra("jobKindCd");
    jobKindNm  = intent.getStringExtra("jobKindNm");
    userId     = intent.getStringExtra("userId");
    userName   = intent.getStringExtra("userName");
    indexPage  = intent.getStringExtra("indexPage");
    drKind     = intent.getStringExtra("drKind");

    Log.e(TAG, "deptCd    -- > " + deptCd   );
    Log.e(TAG, "deptNm    -- > " + deptNm   );
    Log.e(TAG, "jobKindCd -- > " + jobKindCd);
    Log.e(TAG, "jobKindNm -- > " + jobKindNm);
    Log.e(TAG, "userId    -- > " + userId   );
    Log.e(TAG, "userName  -- > " + userName );
    Log.e(TAG, "indexPage -- > " + indexPage);
    Log.e(TAG, "drKind    -- > " + drKind   );

    setLoadClass();
  }

  private void setLoadClass() {
    loadingProgress = new LoadingProgress(mContext);
    csAlert    = new CustomAlertDialog(mContext);
    topMenu    = new TopMenu(mContext, mActivity);
    tapMenu    = new TapMenu(mContext, mActivity);
    leftMenu   = new LeftMenu(mContext, mActivity);
    centerMenu = new CenterMenu(mContext, mActivity);
    rightMenu  = new RightMenu(mContext, mActivity);
  }

  private void setTopMenuLayout() {
    ivLogo        = (ImageView) findViewById(R.id.ivLogo);
    tvEdu         = (TextView) findViewById(R.id.tvEdu);
    tvConsent     = (TextView) findViewById(R.id.tvConsent);
    tvDoctor      = (TextView) findViewById(R.id.tvDoctor);
    tvDept        = (TextView) findViewById(R.id.tvDept);
    settingLayout = (LinearLayout) findViewById(R.id.settingLayout);
    logoutLayout  = (LinearLayout) findViewById(R.id.logoutLayout);

    int logo = 0;
    if (BuildConfig.INST_CD.equals("031")) {
      logo = R.drawable.knuh_logo;
    } else {
      logo = R.drawable.chilgok_logo;
    }

    if (Util.getAppName(mContext).indexOf(getString(R.string.edu)) > 0) {
      tvEdu.setVisibility(View.VISIBLE);
      tvEdu.setText(Util.getAppName(mContext));
    } else {
      tvEdu.setVisibility(View.GONE);
    }

    ivLogo.setImageResource(logo);
    tvDoctor.setText(userName);
    tvDept.setText(deptNm);
    Drawable tvEduBg = (Drawable) tvEdu.getBackground();
    tvEduBg.setColorFilter(ContextCompat.getColor(mContext, R.color.eduColor), PorterDuff.Mode.SRC_ATOP);
    Drawable tvConsentBg = (Drawable) tvConsent.getBackground();
    tvConsentBg.setColorFilter(ContextCompat.getColor(mContext, R.color.consentColor), PorterDuff.Mode.SRC_ATOP);
  }

  private void setTopMenuEvent() {
    settingLayout.setOnClickListener(topMenu.settingClickListener);
    logoutLayout.setOnClickListener(topMenu.logoutClickListener);
  }

  private void setTapMenuLayout() {
    tabAdmission    = (LinearLayout) findViewById(R.id.tabAdmission);
    ivInPatient     = (ImageView) findViewById(R.id.ivInPatient);
    tvInPatient     = (TextView) findViewById(R.id.tvInPatient);
    tabOutPatient   = (LinearLayout) findViewById(R.id.tabOutPatient);
    ivOutPatient    = (ImageView) findViewById(R.id.ivOutPatient);
    tvOutPatient    = (TextView) findViewById(R.id.tvOutPatient);
    tabEmergency    = (LinearLayout) findViewById(R.id.tabEmergency);
    ivErPatient     = (ImageView) findViewById(R.id.ivErPatient);
    tvErPatient     = (TextView) findViewById(R.id.tvErPatient);
    tabSurgery      = (LinearLayout) findViewById(R.id.tabSurgery);
    ivOpPatient     = (ImageView) findViewById(R.id.ivOpPatient);
    tvOpPatient     = (TextView) findViewById(R.id.tvOpPatient);
    tabSearch       = (LinearLayout) findViewById(R.id.tabSearch);
    ivSearchPatient = (ImageView) findViewById(R.id.ivSearchPatient);
    tvSearchPatient = (TextView) findViewById(R.id.tvSearchPatient);

    tapMenu.tapMenuColorChange(indexPage);
    tabAdmission.setOnClickListener(tapMenu.onClickListener);
    tabOutPatient.setOnClickListener(tapMenu.onClickListener);
    tabEmergency.setOnClickListener(tapMenu.onClickListener);
    tabSurgery.setOnClickListener(tapMenu.onClickListener);
    tabSearch.setOnClickListener(tapMenu.onClickListener);
  }

  private void setLeftLayout() {
    dateLayout    = (LinearLayout) findViewById(R.id.dateLayout);
    tvMainDate    = (TextView) findViewById(R.id.tvMainDate);
    wardLayout    = (LinearLayout) findViewById(R.id.wardLayout);
    wardSpinner   = (Spinner) findViewById(R.id.wardSpinner);
    deptLayout    = (LinearLayout) findViewById(R.id.deptLayout);
    deptSpinner   = (Spinner) findViewById(R.id.deptSpinner);
    doctorLayout  = (LinearLayout) findViewById(R.id.doctorLayout);
    doctorSpinner = (Spinner) findViewById(R.id.doctorSpinner);
    radioLayout = (RelativeLayout) findViewById(R.id.radioLayout);

    etPatientId = (EditText) findViewById(R.id.etPatientId);
    patientSearchLayout = (LinearLayout) findViewById(R.id.patientSearchLayout);

    patientRecyclerView = (RecyclerView) findViewById(R.id.patientRecyclerView);
    patientEmpty = (TextView) findViewById(R.id.patientEmpty);
    chkMyPatient = (CheckBox) findViewById(R.id.chkMyPatient);

    llPatientSort = (LinearLayout) findViewById(R.id.llPatientSort);
    llPatientNmSort = (LinearLayout) findViewById(R.id.llPatientNmSort);
    llRoomSort = (LinearLayout) findViewById(R.id.llRoomSort);

    column1 = (TextView) findViewById(R.id.column1);
    column4 = (TextView) findViewById(R.id.column4);
    column6 = (TextView) findViewById(R.id.column6);

    leftMenu.setRadioGroupDraw(indexPage);

    if (!indexPage.equals("I")) {
      wardLayout.setVisibility(View.INVISIBLE);
      chkMyPatient.setVisibility(View.GONE);

      column6.setText("");
      if (indexPage.equals("OP")) {
        column6.setText(getString(R.string.opRoom));
      } else if (indexPage.equals("SR")) {
        column6.setText(getString(R.string.medicalTreatmentDate));
      }

    } else if (indexPage.equals("I")) {
      column6.setText(getString(R.string.wardRoom));
      chkMyPatient.setVisibility(View.VISIBLE);
//      if (ConsentConfig.SETTING_DATA.get("MY_PATIENT").equals("Y")) {
//        chkMyPatient.setVisibility(View.VISIBLE);
//      } else {
//        chkMyPatient.setVisibility(View.GONE);
//      }
    }

    if(jobKindCd.indexOf("03") == 0){
      chkMyPatient.setVisibility(View.GONE);
    }

    tvMainDate.setText(Util.nowDate());

    dateLayout.setOnClickListener(leftMenu.onClickListener);
    radioGroup.setOnCheckedChangeListener(leftMenu.onCheckedChangeListener);
    patientSearchLayout.setOnClickListener(leftMenu.onClickListener);
    etPatientId.setOnEditorActionListener(leftMenu.onEditorActionListener);

    llPatientSort.setOnClickListener(leftMenu.sortOnClickListener);
    llPatientNmSort.setOnClickListener(leftMenu.sortOnClickListener);
    llRoomSort.setOnClickListener(leftMenu.sortOnClickListener);

    leftMenu.getWardList();
    leftMenu.getDeptList();
    leftMenu.getInitPatientList();
  }

  private void setCenterLayout() {
    tvPatientInfo    = (TextView) findViewById(R.id.tvPatientInfo);
    tvAdmissionDay   = (TextView) findViewById(R.id.tvAdmissionDay);
    tvChargeDoctor   = (TextView) findViewById(R.id.tvChargeDoctor);
    tvDiagnosisName  = (TextView) findViewById(R.id.tvDiagnosisName);
    tvPatientAlert   = (TextView) findViewById(R.id.tvPatientAlert);
    tvTempCenterTxt  = (TextView) findViewById(R.id.tvTempCenterTxt);
    tempRecyclerView = (RecyclerView) findViewById(R.id.tempRecyclerView);
  }

  private void setRightLayout() {
    /** RightTab **/
    historyLayout  = (LinearLayout) findViewById(R.id.historyLayout);
    markerLayout   = (LinearLayout) findViewById(R.id.markerLayout);
    searchLayout   = (LinearLayout) findViewById(R.id.searchLayout);
    tvRightHistory = (TextView) findViewById(R.id.tvHistory);
    tvRightMarker  = (TextView) findViewById(R.id.tvMarker);
    tvRightSearch  = (TextView) findViewById(R.id.tvSearch);
    viewPager      = (ViewPager) findViewById(R.id.viewPager);
    /** RightTab **/

    historyLayout.setOnClickListener(rightMenu.onClickListener);
    markerLayout.setOnClickListener(rightMenu.onClickListener);
    searchLayout.setOnClickListener(rightMenu.onClickListener);

    setViewPager();
    rightMenu.rightMenuStartColor();
  }

  public void setViewPager() {
    ViewPagerAdapter agreeAdapter = new ViewPagerAdapter(getSupportFragmentManager());

    history = new HistoryFragment(mActivity, mContext, centerMenu);
    agreeAdapter.addItem(history);

    marker = new MarkerFragment(mActivity, mContext);
    agreeAdapter.addItem(marker);

    search = new SearchFragment(mActivity, mContext);
    agreeAdapter.addItem(search);

    viewPager.setAdapter(agreeAdapter);
    viewPager.setOffscreenPageLimit(2);
    viewPager.setCurrentItem(1);
//    startTabColor();
    viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
      @Override
      public void onPageScrolled(int i, float v, int i1) {
      }

      @Override
      public void onPageSelected(int position) {
//        Log.e(TAG, "i -- >" + position);
//        changedColorTab(position);
        rightMenu.rightMenuColorChange(position);
        if (position == 1) {
//          marker.getConsentSetList();
        }
      }

      @Override
      public void onPageScrollStateChanged(int i) {
      }
    });

  }

  public void showSingButtonDialog(String message) {
    csAlert.show();
    csAlert.setContent(message, ConsentConfig.ALERT_BTN_TYPE);
    csAlert.btnConfirm2.setOnClickListener(new View.OnClickListener() {
      @Override
      public void onClick(View v) {
        csAlert.dismiss();
      }
    });
  }

  public void showProgress() {
    runOnUiThread(new Runnable() {
      @Override
      public void run() {
        if (!loadingProgress.isShowing()) {
          loadingProgress.show();
        }
      }
    });

  }

  public void dismissProgress() {
    runOnUiThread(new Runnable() {
      @Override
      public void run() {
        if (loadingProgress.isShowing()) {
          loadingProgress.dismiss();
        }
      }
    });

  }

  @Override
  public void onBackPressed() {
    if(System.currentTimeMillis() > backKeyPressedTime + 2000) {
      backKeyPressedTime = System.currentTimeMillis();
      Toast.makeText(mContext, getString(R.string.doublePressed), Toast.LENGTH_SHORT).show();
      return;
    }

    if(System.currentTimeMillis() <= backKeyPressedTime + 2000) {
      tapClick = false;
//      super.onBackPressed();
      finishAffinity();
    }
  }

  @Override
  protected void onDestroy() {
    if (tapClick == false) {
      try {
//        SignWrapper.getInstance().deleteAll();
//        Util.clearPreference(mContext, "userInfo");
//        Util.clearPreference(mContext, "sessionTime");
      } catch (Exception e) {
      }
    }

    super.onDestroy();
//    if (softKeyboard != null) {
//      softKeyboard.unRegisterSoftKeyboardCallback();
//    }
  }
}
