package com.dbs.consent.demo.fragment;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.DatePickerDialog;
import android.content.Context;

import android.graphics.PorterDuff;
import android.graphics.drawable.GradientDrawable;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.DatePicker;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;


import com.dbs.consent.demo.BuildConfig;
import com.dbs.consent.demo.R;
import com.dbs.consent.demo.activity.ConsentActivity;
import com.dbs.consent.demo.activity.activityEvent.CenterMenu;
import com.dbs.consent.demo.adapter.ConsentHistoryAdapter;
import com.dbs.consent.demo.customView.CustomAlertDialog;
import com.dbs.consent.demo.httpTask.CallBack;
import com.dbs.consent.demo.httpTask.SoapParser;
import com.dbs.consent.demo.model.ConsentFormListVO;
import com.dbs.consent.demo.util.ConsentConfig;
import com.dbs.consent.demo.util.Util;

import org.ksoap2.serialization.SoapObject;

import java.util.ArrayList;
import java.util.HashMap;


public class HistoryFragment extends Fragment {

  private static final String TAG = "HistoryFragment";
  private AppCompatActivity mActivity;
  private Context mContext;
  private ConsentActivity instance;
  private CenterMenu centerMenu;
  private LinearLayoutManager linearLayoutManager;

  private DatePickerDialog leftDateDialog;
  private DatePickerDialog rightDateDialog;
  private CustomAlertDialog csAlert;

  private LinearLayout typePatient;
  private LinearLayout patientLeftRound;
  private ImageView ivPatient;
  private LinearLayout patientRightRound;
  private TextView tvPatient;

  private LinearLayout typeWriter;
  private LinearLayout writerLeftRound;
  private ImageView ivWriter;
  private LinearLayout writerRightRound;
  private TextView tvWriter;

  private Button btnHistorySearch;

  private LinearLayout leftDateLayout;
  private LinearLayout rightDateLayout;
  private TextView tvLeftDate;
  private TextView tvRightDate;

  private CheckBox checkAll;
  private CheckBox checkTemp;
  private CheckBox checkCert;
  private CheckBox checkConfirm;
  private CheckBox checkPrint;
  private TextView tvEmptyMsg;
  public RecyclerView historyPatientRecyclerView;
  public RecyclerView historyWriteRecyclerView;

  private HashMap<View, String> consentStateData;
  public String searchType = "patient";

  public HistoryFragment(AppCompatActivity mActivity, Context mContext, CenterMenu centerMenu) {
    this.mContext   = mContext;
    this.mActivity  = mActivity;
    this.instance   = (ConsentActivity) mContext;
    this.centerMenu = centerMenu;
    this.consentStateData = new HashMap<View, String>();
  }

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

  }

  @Nullable
  @Override
  public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    View view = (View) inflater.inflate(R.layout.activity_history_fragment, container, false);

    csAlert = new CustomAlertDialog(mContext);

    typePatient         = (LinearLayout) view.findViewById(R.id.typePatient);
    patientLeftRound    = (LinearLayout) view.findViewById(R.id.patientLeftRound);
    ivPatient           = (ImageView) view.findViewById(R.id.ivPatient);
    patientRightRound   = (LinearLayout) view.findViewById(R.id.patientRightRound);
    tvPatient           = (TextView) view.findViewById(R.id.tvPatient);
    typeWriter          = (LinearLayout) view.findViewById(R.id.typeWriter);
    writerLeftRound     = (LinearLayout) view.findViewById(R.id.writerLeftRound);
    ivWriter            = (ImageView) view.findViewById(R.id.ivWriter);
    writerRightRound    = (LinearLayout) view.findViewById(R.id.writerRightRound);
    tvWriter            = (TextView) view.findViewById(R.id.tvWriter);
    btnHistorySearch    = (Button) view.findViewById(R.id.btnHistorySearch);

    leftDateLayout      = (LinearLayout) view.findViewById(R.id.leftDateLayout);
    rightDateLayout     = (LinearLayout) view.findViewById(R.id.rightDateLayout);
    tvLeftDate          = (TextView) view.findViewById(R.id.tvLeftDate);
    tvRightDate         = (TextView) view.findViewById(R.id.tvRightDate);

    checkAll            = (CheckBox) view.findViewById(R.id.checkAll);
    checkTemp           = (CheckBox) view.findViewById(R.id.checkTemp);
    checkCert           = (CheckBox) view.findViewById(R.id.checkCert);
    checkConfirm        = (CheckBox) view.findViewById(R.id.checkConfirm);
    checkPrint          = (CheckBox) view.findViewById(R.id.checkPrint);
    tvEmptyMsg          = (TextView) view.findViewById(R.id.tvEmptyMsg);
    historyPatientRecyclerView = (RecyclerView) view.findViewById(R.id.historyPatientRecyclerView);
    historyWriteRecyclerView = (RecyclerView) view.findViewById(R.id.historyWriteRecyclerView);

    GradientDrawable btnSearchBg = (GradientDrawable) btnHistorySearch.getBackground();
    btnSearchBg.setColorFilter(ContextCompat.getColor(mContext, R.color.typeLeftColor), PorterDuff.Mode.SRC_ATOP);

    setDate();
    setEvent();
    setDrawableHistoryType("patient");

    return view;
  }

  private void setDrawableHistoryType(String type) {
    GradientDrawable patientLeftBg = (GradientDrawable) patientLeftRound.getBackground();
    GradientDrawable patientRightBg = (GradientDrawable) patientRightRound.getBackground();
    GradientDrawable writerLeftBg = (GradientDrawable) writerLeftRound.getBackground();
    GradientDrawable writerRightBg = (GradientDrawable) writerRightRound.getBackground();

    if (type.equals("patient")) {
      patientLeftBg.setColorFilter(ContextCompat.getColor(mContext, R.color.typeLeftColor), PorterDuff.Mode.SRC_ATOP);
      patientRightBg.setColorFilter(ContextCompat.getColor(mContext, R.color.typeRightColor), PorterDuff.Mode.SRC_ATOP);
      ivPatient.setColorFilter(ContextCompat.getColor(mContext, R.color.white), PorterDuff.Mode.SRC_ATOP);
      tvPatient.setTextColor(ContextCompat.getColor(mContext, R.color.white));

      writerLeftBg.setColorFilter(ContextCompat.getColor(mContext, R.color.historyTypeColor), PorterDuff.Mode.SRC_ATOP);
      writerRightBg.setColorFilter(ContextCompat.getColor(mContext, R.color.departmentBtnColor), PorterDuff.Mode.SRC_ATOP);
      ivWriter.setColorFilter(ContextCompat.getColor(mContext, R.color.black), PorterDuff.Mode.SRC_ATOP);
      tvWriter.setTextColor(ContextCompat.getColor(mContext, R.color.black));

      checkAll.setChecked(true);
      checkTemp.setChecked(false);
      checkCert.setChecked(false);
      checkConfirm.setChecked(false);
      checkPrint.setChecked(false);
      consentStateData.put(checkAll, ConsentConfig.ALL);
      consentStateData.remove(checkTemp);
    } else {
      patientLeftBg.setColorFilter(ContextCompat.getColor(mContext, R.color.historyTypeColor), PorterDuff.Mode.SRC_ATOP);
      patientRightBg.setColorFilter(ContextCompat.getColor(mContext, R.color.departmentBtnColor), PorterDuff.Mode.SRC_ATOP);
      ivPatient.setColorFilter(ContextCompat.getColor(mContext, R.color.black), PorterDuff.Mode.SRC_ATOP);
      tvPatient.setTextColor(ContextCompat.getColor(mContext, R.color.black));

      writerLeftBg.setColorFilter(ContextCompat.getColor(mContext, R.color.typeLeftColor), PorterDuff.Mode.SRC_ATOP);
      writerRightBg.setColorFilter(ContextCompat.getColor(mContext, R.color.typeRightColor), PorterDuff.Mode.SRC_ATOP);
      ivWriter.setColorFilter(ContextCompat.getColor(mContext, R.color.white), PorterDuff.Mode.SRC_ATOP);
      tvWriter.setTextColor(ContextCompat.getColor(mContext, R.color.white));

      checkAll.setChecked(false);
      checkTemp.setChecked(true);
      checkCert.setChecked(false);
      checkConfirm.setChecked(false);
      checkPrint.setChecked(false);
      consentStateData.put(checkTemp, "'" + ConsentConfig.TEMP + "', " + "'" + ConsentConfig.UNFINISHED + "', " + "'" + ConsentConfig.ELECTR_CMP + "'");
      consentStateData.remove(checkAll);
    }

    if (instance.consentHistoryAdapter != null) {
      if (type.equals("patient")) {
        historyPatientRecyclerView.setVisibility(View.VISIBLE);
        historyWriteRecyclerView.setVisibility(View.GONE);
      } else {
        historyPatientRecyclerView.setVisibility(View.GONE);
        historyWriteRecyclerView.setVisibility(View.VISIBLE);
      }
    }

//    if (instance.consentHistoryAdapter != null) {
//      instance.consentHistoryAdapter.arrayList.clear();
//      instance.consentHistoryAdapter.apiType = type;
//      instance.consentHistoryAdapter.notifyDataSetChanged();
//    }

  }

  private void setEvent() {

    // 환자별/작성자별 색상 변경 리스너
    typePatient.setOnClickListener(onClickListener);
    typeWriter.setOnClickListener(onClickListener);

    leftDateLayout.setOnClickListener(onClickListener);
    rightDateLayout.setOnClickListener(onClickListener);

    // 조회 버튼 이벤트
    btnHistorySearch.setOnClickListener(onClickListener);

    // 체크박스 체크 리스너
    checkAll.setOnCheckedChangeListener(onCheckedChangeListener);
    checkTemp.setOnCheckedChangeListener(onCheckedChangeListener);
    checkCert.setOnCheckedChangeListener(onCheckedChangeListener);
    checkConfirm.setOnCheckedChangeListener(onCheckedChangeListener);
    checkPrint.setOnCheckedChangeListener(onCheckedChangeListener);
  }


  private void setDate() {
    int year  = Util.toDayDate()[0];
    int month = Integer.parseInt(Util.plusZero(Util.toDayDate()[1] - 1));
    int day   = Integer.parseInt(Util.plusZero(Util.toDayDate()[2]));


    String rightDate = Util.toDayDate()[0] + "/" + Util.plusZero(Util.toDayDate()[1]) + "/" + Util.plusZero(Util.toDayDate()[2]);
    String leftDate  = Util.addDate(rightDate, "yyyy/MM/dd", 0, 0, -14, 0, 0);
    tvRightDate.setText(rightDate);
    tvLeftDate.setText(leftDate);

    leftDateDialog  = new DatePickerDialog(mContext, R.style.DatePickerDialogTheme , leftDateListener, year, month, day - 7);
    rightDateDialog = new DatePickerDialog(mContext, R.style.DatePickerDialogTheme , rightDateListener, year, month, day);
  }

  private DatePickerDialog.OnDateSetListener rightDateListener = new DatePickerDialog.OnDateSetListener() {
    @Override
    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
      String m            = Util.plusZero(month + 1);
      String d            = Util.plusZero(dayOfMonth);
      String selectedDate = year + "/" + m + "/" + d;
      String ymd          = year + m + d; // 선택한 날짜
      String leftDate     = getLeftDate(); // 왼쪽 날짜
      leftDate            = Util.removeSlashStr(leftDate);

      int ymdInt      = Integer.parseInt(ymd);
      int leftDateInt = Integer.parseInt(leftDate);

      if (leftDateInt <= ymdInt) {
        setRightDate(selectedDate);
      } else {
        csAlert.show();
        csAlert.setContent("조회 마지막일 보다 지난 날짜로 지정될 수 없습니다.", ConsentConfig.ALERT_BTN_TYPE);
        csAlert.btnConfirm2.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            csAlert.dismiss();
          }
        });
      }
    }
  };

  private DatePickerDialog.OnDateSetListener leftDateListener = new DatePickerDialog.OnDateSetListener() {
    @Override
    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
      String m            = Util.plusZero(month + 1);
      String d            = Util.plusZero(dayOfMonth);
      String selectedDate = year + "/" + m + "/" + d;
      String ymd          = year + m + d;
      String rightDate    = getRightDate();
      rightDate           = Util.removeSlashStr(rightDate);

      int ymdInt        = Integer.parseInt(ymd);
      int rightDateInt  = Integer.parseInt(rightDate);

      if (rightDateInt >= ymdInt) {
        setLeftDate(selectedDate);
      } else {
        csAlert.show();
        csAlert.setContent("조회 시작일 보다 이전 날짜로 지정될 수 없습니다.", ConsentConfig.ALERT_BTN_TYPE);
        csAlert.btnConfirm2.setOnClickListener(new View.OnClickListener() {
          @Override
          public void onClick(View v) {
            csAlert.dismiss();
          }
        });
      }
    }
  };



  private View.OnClickListener onClickListener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
      if (v == typePatient) {
        searchType = "patient";
        setDrawableHistoryType("patient");
      } else if (v == typeWriter) {
        searchType = "write";
        setDrawableHistoryType("write");
      } else if (v == leftDateLayout) {
        leftDateDialog.show();
      } else if (v == rightDateLayout) {
        rightDateDialog.show();
      } else if (btnHistorySearch == v) {
        getHistoryConsentList(searchType);
      }

    }
  };

  private CheckBox.OnCheckedChangeListener onCheckedChangeListener = new CheckBox.OnCheckedChangeListener() {
    @Override
    public void onCheckedChanged(CompoundButton v, boolean isChecked) {

      if (v == checkAll) {
        if (isChecked == true) {
          checkTemp.setChecked(false);
          checkCert.setChecked(false);
          checkConfirm.setChecked(false);
          checkPrint.setChecked(false);
          consentStateData.put(checkAll, ConsentConfig.ALL);
        } else {
          consentStateData.remove(checkAll);
        }

      } else if (v == checkTemp) {
        if (isChecked == true) {
          checkAll.setChecked(false);
          consentStateData.put(checkTemp, "'" + ConsentConfig.TEMP + "', " + "'" + ConsentConfig.UNFINISHED + "', " + "'" + ConsentConfig.ELECTR_CMP + "'");
        } else {
          consentStateData.remove(checkTemp);
        }

      } else if (v == checkCert) {
        if (isChecked == true) {
          checkAll.setChecked(false);
          consentStateData.put(checkCert, "'" + ConsentConfig.CERTIFY_CMP + "'");
        } else {
          consentStateData.remove(checkCert);
        }

      } else if (v == checkConfirm) {
        if (isChecked == true) {
          checkAll.setChecked(false);
          consentStateData.put(checkConfirm, "'" + ConsentConfig.ELECTR_CMP + "'");
        } else {
          consentStateData.remove(checkConfirm);
        }

      } else if (v == checkPrint) {
        if (isChecked == true) {
          checkAll.setChecked(false);
          consentStateData.put(checkPrint, "'" + ConsentConfig.PAPER_OUT + "'");
        } else {
          consentStateData.remove(checkPrint);
        }

      }
      if (checkCert.isChecked() && checkTemp.isChecked() && checkConfirm.isChecked() && checkPrint.isChecked()) {
        checkAll.setChecked(true);
        checkCert.setChecked(false);
        checkTemp.setChecked(false);
        checkConfirm.setChecked(false);
        checkPrint.setChecked(false);
        consentStateData.put(checkAll, ConsentConfig.ALL);
        consentStateData.remove(checkTemp);
        consentStateData.remove(checkCert);
        consentStateData.remove(checkConfirm);
        consentStateData.remove(checkPrint);
      }

      if (!checkAll.isChecked() && !checkCert.isChecked() && !checkTemp.isChecked() && !checkConfirm.isChecked() && !checkPrint.isChecked()) {
        checkAll.setChecked(true);
        consentStateData.put(checkAll, ConsentConfig.ALL);
        consentStateData.remove(checkTemp);
        consentStateData.remove(checkCert);
        consentStateData.remove(checkConfirm);
        consentStateData.remove(checkPrint);
      }
    }
  };

  public void getHistoryConsentList(final String type) {
    Log.e(TAG, "type -- > " + type);

    CallBack callBack = new CallBack() {
      @Override
      public void result(SoapObject result) {
        Log.e(TAG, "patientHistoryConsentList result -- > " + result);
        ArrayList<ConsentFormListVO> arrayList = SoapParser.getConsentList(result);
        setHistoryConsentList(arrayList, type);
      }

      @Override
      public void stop() {

      }

      @Override
      public void error() {

      }
    };

    if (centerMenu.patientInfoVO == null && type.equals("patient")) {
      instance.showSingButtonDialog(mContext.getString(R.string.emptyPatientInfo));
    } else {

      instance.showProgress();

      String instCd = BuildConfig.INST_CD;
      String consentState = "";

      int count = 0;
      for (View key : consentStateData.keySet()) {

        String state = consentStateData.get(key);

        if (state.equals("ALL")) {
          consentState = state;
        } else {
          consentState += state;
          if (consentStateData.size() - 1 > count) {
            consentState = consentState + ", ";
          }
        }

        count = count + 1;
      }

      HashMap<String, String> mData = new HashMap<>();
      if (type.equals("write")) {
        mData.put("userId", Util.getStringPreference(mContext, "userInfo", "userId"));
      } else {
        mData.put("patientCode", centerMenu.patientInfoVO.getPid());
      }
      mData.put("startDt", getLeftDate());
      mData.put("endDt", getRightDate());
      mData.put("instCd", instCd);
      mData.put("consentState", consentState);

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

      if (Util.checkNetwork(mContext) == true) {
        Util.callHttp(mContext, ConsentConfig.HOST_CONSENT, ConsentConfig.GET_CONSENT_LIST, mData, callBack);
      } else {
        instance.dismissProgress();
        Util.networkErrorAlert(mActivity);
      }
    }
//    ArrayList<ConsentFormListVO> arrayList = new ArrayList<ConsentFormListVO>();
//    arrayList.add(new ConsentFormListVO("276786", "96070", "2020033179380", "1614154", "20200326", "I", "2010300000", "1", "", "이준식", "임시", "TEMP", "0000001769", "dba52fd6-8933-4fc2-b19e-b63cebb56576", "K7-입원교육확인서(병동)", "16046", "N", "1", "N", "입원교육확인서(병동)", "N", "", "", "N", "", "", "", "", ""));
//    arrayList.add(new ConsentFormListVO("276786", "96070", "2020033179380", "1614154", "20200326", "I", "2010300000", "1", "", "이준식", "연동", "UNFINISH", "0000001769", "dba52fd6-8933-4fc2-b19e-b63cebb56576", "K1-간암수술 동의서", "16046", "N", "1", "N", "간암수술 동의서", "N", "", "", "N", "", "", "", "", ""));
//    arrayList.add(new ConsentFormListVO("276786", "96070", "2020033179380", "1614154", "20200326", "I", "2010300000", "1", "", "이준식", "인증", "CERTIFY_CMP", "0000001769", "dba52fd6-8933-4fc2-b19e-b63cebb56576", "K7-퇴원교육 확인서(병동)", "16046", "N", "1", "N", "퇴원교육 확인서(병동)", "N", "", "", "N", "", "","", "", ""));
//    arrayList.add(new ConsentFormListVO("276786", "96070", "2020033179380", "1614154", "20200326", "I", "2010300000", "1", "", "이준식", "확인", "ELECTR_CMP", "0000001769", "dba52fd6-8933-4fc2-b19e-b63cebb56576", "K7-퇴원교육 확인서(병동)", "16046", "N", "1", "N", "퇴원교육 확인서(병동)", "N", "", "", "N", "", "", "", "", ""));
//    setHistoryConsentList(arrayList, type);
  }

  private void setHistoryConsentList(final ArrayList<ConsentFormListVO> arrayList, final String apiType) {

    mActivity.runOnUiThread(new Runnable() {
      @Override
      public void run() {

        instance.dismissProgress();
        if (arrayList.size() > 0) {
          tvEmptyMsg.setVisibility(View.GONE);
        } else {
          tvEmptyMsg.setVisibility(View.VISIBLE);
        }

        instance.consentHistoryAdapter = new ConsentHistoryAdapter(mActivity, mContext, arrayList, apiType);
        linearLayoutManager = new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false);

        if (apiType.equals("patient")) {
          historyPatientRecyclerView.setLayoutManager(linearLayoutManager);
          historyPatientRecyclerView.setAdapter(instance.consentHistoryAdapter);
        } else {
          historyWriteRecyclerView.setLayoutManager(linearLayoutManager);
          historyWriteRecyclerView.setAdapter(instance.consentHistoryAdapter);
        }

//        if (instance.consentHistoryAdapter == null) {
//          instance.consentHistoryAdapter = new ConsentHistoryAdapter(mActivity, mContext, arrayList, apiType);
//          linearLayoutManager = new LinearLayoutManager(mActivity, LinearLayoutManager.VERTICAL, false);
//          historyPatientRecyclerView.setLayoutManager(linearLayoutManager);
//          historyPatientRecyclerView.setAdapter(instance.consentHistoryAdapter);
//        } else {
//          instance.consentHistoryAdapter.arrayList.clear();
//          instance.consentHistoryAdapter.arrayList = arrayList;
//          instance.consentHistoryAdapter.apiType = apiType;
//          instance.consentHistoryAdapter.notifyDataSetChanged();
//        }


      }
    });


  }

  private String getLeftDate() {
    return Util.removeSlashStr(tvLeftDate.getText().toString());
  }

  public void setLeftDate(String date) {
    tvLeftDate.setText(date);
  }

  private String getRightDate() {
    return Util.removeSlashStr(tvRightDate.getText().toString());
  }

  private void setRightDate(String date) {
    tvRightDate.setText(date);
  }


}