/*
 * Copyright (c) 2015. Ncomz. All Rights Reserved
 */

package com.ntels.onecable.view.homemember;

import com.ntels.onecable.R;
import com.ntels.onecable.common.AppConfig;
import com.ntels.onecable.common.Constants;
import com.ntels.onecable.common.c_interface.ListInterface;
import com.ntels.onecable.common.c_interface.MainInterface;
import com.ntels.onecable.common.c_interface.OnDataSendToReslut;
import com.ntels.onecable.common.http.HttpSend;
import com.ntels.onecable.common.http.Response;
import com.ntels.onecable.common.util.Dlog;
import com.ntels.onecable.common.util.Util;
import com.ntels.onecable.view.dialog.CustomDialog;
import com.ntels.onecable.view.dialog.DialogCustomList;

import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

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

import jp.wasabeef.recyclerview.adapters.AlphaInAnimationAdapter;
import jp.wasabeef.recyclerview.adapters.ScaleInAnimationAdapter;

/**
 * <pre>
 * 1. ClassName :   FragmentHomeMember
 * 2. FileName  :   FragmentHomeMember.java
 * 3. Package   :   com.ntels.onecable.view.homemember
 * 4. Date      :   2016-12-01
 * 5. Author    :   aaron
 * 6. Comment   :   Initialize
 * </pre>
 */
public class FragmentHomeMember extends Fragment implements View.OnClickListener,
        CustomDialog.OnMsgAlterToResult,
        ListInterface {

    /**
     * 멤버 타입 코드
     */
    public static final String HOMEGRP_MEMBER = "01";
    public static final String INVITATION_MEMBER = "02";
    private static final int MSG_COM_G_HOMEGRP_MEMBERS = 1;
    private static final int MSG_COM_D_HOMEGRP_MEMBERS = 2;
    private static final int MSG_COM_P_HOMEGRP_MASTER_GRADE = 3;
    /**
     * 마스터 권한 양도/취소 타입
     */
    private static final String REQUEST_TRANSFER = "R";
    private static final String REQUEST_TRANSFER_CANCEL = "C";
    /**
     * 마스터 권한 양도 상태
     */
    private static final String PERMISSION_STATUS_TRANSFER = "T";
    private static final String PERMISSION_STATUS_RECEIVER = "R";
    Handler mComHandler = new Handler(new IncomingHandlerCallBack());
    /*툴바 관련*/
    private Toolbar mToolbar;
    /*통신 관련*/
    private ArrayList<HashMap<String, Object>> alTotalList = new ArrayList<HashMap<String, Object>>();
    private int type = 0;
    /*리스트 관련*/
    private FragmentHomeMemberAdapter dataAdapter;
    private SwipeRefreshLayout swipeRefreshLayout;
    private GridLayoutManager gridLayoutManager;
    private DialogCustomList.Builder dialogListBuilder;
    private boolean loading = false;
    private boolean isListHeader = false;
    private boolean isListFooter = false;
    private int listColumnsCnt = 1;
    /*공통*/
    private Activity mActivity;
    private AppConfig mAppConfig;
    private MainInterface mCallback;
    private Util mUtil = new Util();
    private CustomDialog customDialog = new CustomDialog();
    private int mLimitCount = 10;
    private String mTransferMemberId = "";
    private String mTransferType = "";
    private HashMap<String, Object> mReceiveMemberInfo;

    @Override
    public void onAttach(Activity activity) {

        super.onAttach(activity);

        try {
            mCallback = (MainInterface) activity;
        } catch (ClassCastException ex) {
            throw new ClassCastException(activity.toString() + " must implement MainInterface");
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        Dlog.v("onCreate()");
    }

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

        Dlog.v("onCreateView()");
        View rootView = inflater.inflate(R.layout.fragment_homemember, container, false);

        return rootView;
    }

    @Override
    public void onStop() {

        super.onStop();
        Dlog.v("onStop()");
//        GoogleAnalytics.getInstance(mActivity).reportActivityStop(mActivity);
    }

    @Override
    public void onStart() {

        super.onStart();
        Dlog.v("onStart()");
//        GoogleAnalytics.getInstance(mActivity).reportActivityStart(mActivity);
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {

        super.onActivityCreated(savedInstanceState);
        Dlog.v("onActivityCreated().");
        Dlog.v(savedInstanceState == null ? "true" : "false");

        mActivity = getActivity();
        String actName = "HomeMember_List";
        mAppConfig = (AppConfig) mActivity.getApplicationContext();
        customDialog.setOnMsgAlterToResultEvent(this);

        mUtil.callActGoogleAnalytics(actName);
        setToolbar();

        displayListView();
    }

    /**
     * 툴바 셋팅.
     */
    private void setToolbar() {

        mToolbar = (Toolbar) mActivity.findViewById(R.id.toolbar);
        mUtil.setKeyboardHide(mActivity, mToolbar);
        mUtil.getView(mToolbar, R.id.tvToolbarTitle1).setVisibility(View.VISIBLE);
        mUtil.getView(mToolbar, R.id.tvToolbarTitle2).setVisibility(View.VISIBLE);
        mUtil.getView(mToolbar, R.id.tvToolbarTitleDivider).setVisibility(View.VISIBLE);
        mUtil.getView(mToolbar, R.id.tvToolbarTitle3).setVisibility(View.VISIBLE);
        mUtil.getView(mToolbar, R.id.tvToolbarTitle4).setVisibility(View.VISIBLE);
        mUtil.getView(mToolbar, R.id.btnToolbarClose).setVisibility(View.GONE);
        mUtil.getView(mToolbar, R.id.btnToolbarMore).setVisibility(View.VISIBLE);

        mUtil.getTextView(mToolbar, R.id.tvToolbarTitle1).setText(mUtil.getString(mActivity, R.string.layout_join));
        mUtil.getTextView(mToolbar, R.id.tvToolbarTitle2).setText("");
        mUtil.getTextView(mToolbar, R.id.tvToolbarTitle3).setText(mUtil.getString(mActivity, R.string.layout_wait));
        mUtil.getTextView(mToolbar, R.id.tvToolbarTitle4).setText("");

        mUtil.getView(mToolbar, R.id.btnToolbarClose).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                mUtil.getTextView(mToolbar, R.id.btnToolbarClose).setVisibility(View.GONE);
                mUtil.getTextView(mToolbar, R.id.btnToolbarMore).setVisibility(View.VISIBLE);
//                for (int row = 0; row < alTotalList.size(); row++) {
//                    alTotalList.get(row).put(Constants.KEY_CHECK_YN, "N");
//                }

                dataAdapter.setListCheck(false);
                dataAdapter.setPermissionCheck(false);
                dataAdapter.setDelCheck(false);
                dataAdapter.notifyDataSetChanged();
                setRefresh(true);
            }
        });
        mUtil.getView(mToolbar, R.id.btnToolbarMore).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                ArrayList<HashMap<String, Object>> alMenuList = new ArrayList<HashMap<String, Object>>();
                if (mAppConfig.getCtrtGroupGradeCode().equals("MAS")) {
                    if (alTotalList.size() > 2) {
                        alMenuList.add(mUtil.getPopMenu(21));
                    }
                    alMenuList.add(mUtil.getPopMenu(15));
                    if (alTotalList.size() > 2) {
                        alMenuList.add(mUtil.getPopMenu(16));
                    }
                } else {
                    alMenuList.add(mUtil.getPopMenu(17));
                }
                alMenuList.add(mUtil.getPopMenu(6));
                msgAlertList(alMenuList);
            }
        });
    }

    /**
     * UI display.
     */
    private void displayListView() {

        mUtil.getView(mActivity, R.id.llNodata_Master).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.llNoHub_Master).setOnClickListener(this);
        mUtil.getViewUnderline(mActivity, R.id.tvWidthdraw);
        mUtil.getView(mActivity, R.id.tvWidthdraw).setOnClickListener(this);
        mUtil.getViewUnderline(mActivity, R.id.tvConnect);

        swipeRefreshLayout = (SwipeRefreshLayout) getView().findViewById(R.id.swiperefreshlayou);
        swipeRefreshLayout.setColorSchemeResources(android.R.color.holo_red_light,
                android.R.color.holo_green_light, android.R.color.holo_blue_bright,
                android.R.color.holo_orange_light);
        swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

                if (!dataAdapter.getListCheck()) {
                    if (!loading) {
                        onListReload();
                    }
                } else {
                    swipeRefreshLayout.setRefreshing(false);
                }
            }
        });
        setRefresh(true);

        isListFooter = true;
        dataAdapter = new FragmentHomeMemberAdapter(mActivity, R.layout.row_homemember_list,
                R.layout.row_homemember_list, R.layout.row_footer_homemember_list,
                alTotalList, this);
        dataAdapter.setFooterCheck(isListFooter);

        RecyclerView recyclerView = (RecyclerView) getView().findViewById(R.id.rcvList);
        recyclerView.setHasFixedSize(true);
        listColumnsCnt = 2;
        if (listColumnsCnt == 1) {
            LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mActivity);
            recyclerView.setLayoutManager(linearLayoutManager);
        } else {
            gridLayoutManager = new GridLayoutManager(mActivity, listColumnsCnt, GridLayoutManager.VERTICAL, false);
            gridLayoutManager.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
                @Override
                public int getSpanSize(int position) {

                    int positionType = dataAdapter.getItemViewType(position);
                    int totalCount = dataAdapter.getItemCount();
                    int valueCount = dataAdapter.getItemCount();
                    if (isListHeader) {
                        valueCount = totalCount - 1;
                    }

                    if (positionType == FragmentHomeMemberAdapter.TYPE_HEADER) {
                        return gridLayoutManager.getSpanCount();
                    } else {
                        return 1;
//                        return dataAdapter.getItemViewType(position) == 1
//                                ? 1 : (valueCount % listColumnsCnt == 1 ? gridLayoutManager.getSpanCount() : 1);
                    }
                }
            });
            recyclerView.setLayoutManager(gridLayoutManager);
        }
//    recyclerView.addItemDecoration(new DividerItemDecoration( getActivity(), R.drawable.list_color_line_01));
        AlphaInAnimationAdapter alphaAdapter = new AlphaInAnimationAdapter(dataAdapter);
        alphaAdapter.setDuration(150);
        ScaleInAnimationAdapter scaleAdapter = new ScaleInAnimationAdapter(alphaAdapter);
        scaleAdapter.setDuration(150);
        recyclerView.setAdapter(scaleAdapter);

        setHomeHubStateTitle();
        onListReload();
    }

    /**
     * 현재 홈허브 상태(온라인, 오프라인 등)에 따라 타이틀과 리스트를 보여준다.
     */
    public void setHomeHubStateAll() {

        setHomeHubStateTitle();
        setHomeHubStateList();
    }

    /**
     * 현재 홈허브 상태(온라인, 오프라인 등)에 따라 다른 타이틀을 보여준다.
     */
    public void setHomeHubStateTitle() {

        if (mAppConfig.getCtrtGroupId().equals("")) {
            //홈그룹 없을경우
            mUtil.getView(mToolbar, R.id.llToolbar).setVisibility(View.VISIBLE);
            mUtil.getView(mToolbar, R.id.llToolbarHomeHub).setVisibility(View.GONE);
            mUtil.getView(mToolbar, R.id.btnToolbarMore).setVisibility(View.GONE);
            mUtil.getView(mToolbar, R.id.btnToolbarClose).setVisibility(View.GONE);
            if (dialogListBuilder != null) {
                dialogListBuilder.create().dismiss();
            }
        } else {
            //홈그룹 있을경우
            if (!mAppConfig.getIsCtrtGroupHomehub()) {
                //홈그룹은 있고 홈허브가 없는경우
                mUtil.getView(mToolbar, R.id.llToolbar).setVisibility(View.GONE);
                mUtil.getView(mToolbar, R.id.llToolbarHomeHub).setVisibility(View.VISIBLE);
                mUtil.getTextView(mToolbar, R.id.tvToolbarHomeHub).setText(mUtil.getString(mActivity, R.string.layout_homehub_delete));
                mUtil.getView(mToolbar, R.id.btnToolbarMore).setVisibility(View.GONE);
                mUtil.getView(mToolbar, R.id.btnToolbarClose).setVisibility(View.GONE);
                if (dialogListBuilder != null) {
                    dialogListBuilder.create().dismiss();
                }
            } else {
                //                mUtil.getView(mToolbar, R.id.btnToolbarMore).setVisibility(View.VISIBLE);
//                if (mAppConfig.getSelect_Homegrp_Homehub_Online_State().equals("OFF")) {
                if (mAppConfig.getSelectCtrtGroupHomehubOnlineState().equals("OFF")) {
                    //홈그룹은 있고 홈허브가 오프라인인경우
                    mUtil.getView(mToolbar, R.id.llToolbar).setVisibility(View.GONE);
                    mUtil.getView(mToolbar, R.id.llToolbarHomeHub).setVisibility(View.VISIBLE);
                    mUtil.getTextView(mToolbar, R.id.tvToolbarHomeHub).setText(mUtil.getString(mActivity, R.string.layout_homehub_offline));
                } else {
                    //홈그룹은 있고 홈허브가 온라인인 경우
                    mUtil.getView(mToolbar, R.id.llToolbar).setVisibility(View.VISIBLE);
                    mUtil.getView(mToolbar, R.id.llToolbarHomeHub).setVisibility(View.GONE);
                }
                // 리스트가 2개 이하일경우에는 본인이 마스터인경우와 푸터랑 해서 2Row이기 때문에 삭제 상태를 다시 일반상태로 변환함
                if (alTotalList.size() <= 2) {
//                    mUtil.getTextView(mToolbar, R.id.btnToolbarDel).setVisibility(View.GONE);
                    mUtil.getTextView(mToolbar, R.id.btnToolbarClose).setVisibility(View.GONE);
                    mUtil.getTextView(mToolbar, R.id.btnToolbarMore).setVisibility(View.VISIBLE);
                }
            }
        }
    }

    /**
     * 현재 홈허브 상태(온라인, 오프라인 등)에 따라 다른 리스트를 보여준다.
     *
     * @return 리스트 갱신했는지 여부
     */
    public boolean setHomeHubStateList() {

        Boolean isListLoad = false;
        swipeRefreshLayout.setVisibility(View.GONE);
        mUtil.getView(mActivity, R.id.llNoHub_Master).setVisibility(View.GONE);
        mUtil.getView(mActivity, R.id.llNoHub_Guest).setVisibility(View.GONE);
        mUtil.getView(mActivity, R.id.llNodata_Master).setVisibility(View.GONE);
        mUtil.getView(mActivity, R.id.llNodata_Guest).setVisibility(View.GONE);

        mUtil.getView(mActivity, R.id.llNoHub_NoHome_Smartcity).setVisibility(View.GONE);
        mUtil.getView(mActivity, R.id.llNoHub_Master_Smartcity).setVisibility(View.GONE);
        mUtil.getView(mActivity, R.id.llNoHub_Guest_Smartcity).setVisibility(View.GONE);
        mUtil.getView(mActivity, R.id.llNodata_Master_Smartcity).setVisibility(View.GONE);
        mUtil.getView(mActivity, R.id.llNodata_Guest_Smartcity).setVisibility(View.GONE);
        if (false/*mAppConfig.getCtrtGroupId().equals("")*/) {
            //홈그룹 없을경우
//            mUtil.getView(mActivity, R.id.llNoHub_Master).setVisibility(View.VISIBLE);
            dataAdapter.setListCheck(false);
            dataAdapter.setPermissionCheck(false);
            dataAdapter.setDelCheck(false);
            dataAdapter.notifyDataSetChanged();
            setRefresh(false);
        } else {
            //홈그룹 있을경우
            if (false/*mAppConfig.getSelectHomehubDeviceId().equals("")*/) {
                //홈그룹은 있고 홈허브가 없는경우
                if (mAppConfig.getCtrtGroupGradeCode().equals("MAS")) {
//                    mUtil.getView(mActivity, R.id.llNoHub_Master).setVisibility(View.VISIBLE);
                    dataAdapter.setListCheck(false);
                    dataAdapter.setPermissionCheck(false);
                    dataAdapter.setDelCheck(false);
                    dataAdapter.notifyDataSetChanged();
                    setRefresh(false);
                } else {
                    mUtil.getView(mActivity, R.id.llNoHub_Guest).setVisibility(View.VISIBLE);
                    dataAdapter.setListCheck(false);
                    dataAdapter.setPermissionCheck(false);
                    dataAdapter.setDelCheck(false);
                    dataAdapter.notifyDataSetChanged();
                    setRefresh(false);
                }
            } else {
                //                if ( alTotalList.size() > 0 ) {
                swipeRefreshLayout.setVisibility(View.VISIBLE);
                // 리스트가 2개 이하일경우에는 본인이 마스터인경우와 푸터랑 해서 2Row이기 때문에 삭제 상태를 다시 일반상태로 변환함
                if (alTotalList.size() <= 2) {
                    dataAdapter.setListCheck(false);
                    dataAdapter.setPermissionCheck(false);
                    dataAdapter.setDelCheck(false);
                    setRefresh(true);
                }
                if (mAppConfig.getCtrtGroupGradeCode().equals("MAS")) {
                    dataAdapter.setFooterVisible(true);
                } else {
                    dataAdapter.setFooterVisible(false);
                }
                dataAdapter.notifyDataSetChanged();
                isListLoad = true;
            }
        }
        return isListLoad;
    }

    /**
     * {@link #swipeRefreshLayout} enable/disable.
     *
     * @param isEnable true or false
     */
    private void setRefresh(boolean isEnable) {

        if (isEnable) {
            swipeRefreshLayout.setEnabled(true);
        } else {
            swipeRefreshLayout.setEnabled(false);
        }
    }

    /**
     * {@link HomeMemberAdd} 로 이동.
     */
    public void homeMemberAdd() {

        Intent intent = new Intent(mActivity, HomeMemberAdd.class);
        mUtil.callActivityForResult(mActivity, intent, Constants.ACT_HOMEMEMBER_ADD);
    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.llNoHub_Master:
                mCallback.onHomehubStart();
                break;
            case R.id.tvWidthdraw:
                mCallback.onHomeMemberWidthdraw();
                break;
            case R.id.llNodata_Master:
                homeMemberAdd();
                break;
            default:
                break;
        }
    }

    /**
     * 홈그룹 멤버 강퇴/초대 취소(홈그룹으로 초대받은 멤버의 정보를 변경한다) 요청.
     */
    private void sendDeleteHomegrpMembers() {

        try {
            HttpSend httpSend;
            httpSend = new HttpSend(mActivity);
            httpSend.setOnDataSendToReslutEvent(new OnDataSendToReslut() {
                @Override
                public void resultResponse(Response result) {

                    resultDeleteHomegrpMembers(result);
                }
            });

            String temp = "";
            String temp1 = "";
            for (int row = 0; row < alTotalList.size(); row++) {
                Dlog.v("alTotalList.get(row).get(Constants.KEY_CHECK_YN) = "
                        + alTotalList.get(row).get(Constants.KEY_CHECK_YN));
                if (alTotalList.get(row).get(Constants.KEY_CHECK_YN).equals("Y")) {
                    if (alTotalList.get(row).get(Constants.KEY_MEMBER_TYPE_CODE).equals("01")) {
                        temp += (temp.equals("") ? "" : ",")
                                + alTotalList.get(row).get(Constants.KEY_MEMBER_ID);
                    } else {
                        temp1 += (temp1.equals("") ? "" : ",")
                                + alTotalList.get(row).get(Constants.KEY_NICKNAME);
                    }
                }
            }

            httpSend.deleteHomegrpMembers(temp, temp1);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * {@link #sendDeleteHomegrpMembers()} 요청 결과.
     *
     * @param response 결과 data
     */
    private void resultDeleteHomegrpMembers(Response response) {

        loading = false;
        try {
            if (response.getStatusCode() == 200) {
//                mUtil.setShowToast(mActivity, mUtil.getString(mActivity, R.string.MSG880), Toast.LENGTH_SHORT);
                mUtil.getView(mToolbar, R.id.btnToolbarClose).performClick();
                onListReload();
            } else {
                JSONObject joResult = new JSONObject(response.getContent());
                Dlog.v(joResult.toString());
                String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
                String resultMsg = mUtil.null2string(joResult.get(Constants.KEY_RESULT_MSG));

                switch (resultCode) {
                    case "401":
                        customDialog.msgAlert(mActivity, Constants.MSG998, resultMsg);
                        break;
                    case "401-106":
                        customDialog.msgAlert(mActivity, Constants.MSG997, resultMsg);
                        break;
                    default:
                        mUtil.setShowToast(mActivity, resultMsg, Toast.LENGTH_SHORT);
                        break;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            customDialog.msgAlert(mActivity, Constants.MSG807);
        }
//        try {
//            mUtil.getView(mToolbar, R.id.btnToolbarDel).setEnabled(true);
//        } catch (Exception ex) {
//            ex.printStackTrace();
//        }
    }

    /**
     * 홈그룹 멤버 목록 조회(홈그룹의 멤버 목록을 조회한다) 요청.
     */
    private void sendGetHomegrpMembers() {

        try {
            HttpSend httpSend;

            httpSend = new HttpSend(mActivity, !swipeRefreshLayout.isRefreshing());

            httpSend.setOnDataSendToReslutEvent(new OnDataSendToReslut() {
                @Override
                public void resultResponse(Response result) {

                    resultGetHomegrpMembers(result);
                }
            });
            alTotalList.clear();
            swipeRefreshLayout.setVisibility(View.GONE);
            httpSend.getHomeGroupMembers();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    /**
     * {@link #sendGetHomegrpMembers()} 요청 결과.
     *
     * @param response 결과 data
     */
    private void resultGetHomegrpMembers(Response response) {

        loading = false;
        try {
            if (response.getStatusCode() == 200) {
                mReceiveMemberInfo = null;
                JSONObject joResult = new JSONObject(response.getContent());
                mLimitCount = mUtil.null2int(joResult.get(Constants.KEY_LIMIT_CNT));
                String homegrpMemberList = mUtil.null2string(
                        joResult.get(Constants.KEY_CTRT_GRP_MEMBER_LIST));
                ArrayList<HashMap<String, Object>> alList = mUtil.jsonToArrayListMap(homegrpMemberList);
                int memberCnt = 0;
                int invitationCnt = 0;
                if (alList.size() > 0) {
                    for (int row = 0; row < alList.size(); row++) {
                        HashMap<String, Object> tempMap;
                        tempMap = alList.get(row);

                        String memberTypeCode = mUtil.null2string(tempMap.get(Constants.KEY_MEMBER_TYPE_CODE));
                        tempMap.put(Constants.KEY_CHECK_YN, "N");
                        alTotalList.add(tempMap);

                        if (HOMEGRP_MEMBER.equals(memberTypeCode)) {
                            memberCnt++;
                        } else if (INVITATION_MEMBER.equals(memberTypeCode)) {
                            invitationCnt++;
                        }

                        String transferStatus = mUtil.null2string(tempMap.get(Constants.KEY_PERMISSION_TRANSFER_FLAG));
                        if (PERMISSION_STATUS_RECEIVER.equals(transferStatus)) {
                            mReceiveMemberInfo = tempMap;
                        }
                    }

                    HashMap<String, Object> hmTemp = new HashMap<String, Object>();
                    hmTemp.put(Constants.KEY_CHECK_YN, "N");
                    alTotalList.add(hmTemp);
                }
                mUtil.getTextView(mToolbar, R.id.tvToolbarTitle2).setText(String.valueOf(memberCnt));
                mUtil.getTextView(mToolbar, R.id.tvToolbarTitle4).setText(String.valueOf(invitationCnt));

                setHomeHubStateAll();
                swipeRefreshLayout.setRefreshing(false);
            } else {
                JSONObject joResult = new JSONObject(response.getContent());
                Dlog.v(joResult.toString());
//                String errorCode = mUtil.null2string(joResult.get(Constants.KEY_ERR_CODE));
                String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
//                String errorMsg = mUtil.null2string(joResult.get(Constants.KEY_ERR_MSG));
                String resultMsg = mUtil.null2string(joResult.get(Constants.KEY_RESULT_MSG));

                switch (resultCode) {
                    case "401":
                        customDialog.msgAlert(mActivity, Constants.MSG998, resultMsg);
                        break;
                    case "401-106":
                        customDialog.msgAlert(mActivity, Constants.MSG997, resultMsg);
                        break;
                    default:
                        customDialog.msgAlert(mActivity, Constants.MSG000, resultMsg);
                        break;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            customDialog.msgAlert(mActivity, Constants.MSG807);
        }
    }

    /**
     * 마스터 권한 양도/취소 요청.
     */
    private void sendPutHomegrpMasterGrade() {

        try {
            HttpSend httpSend;

            httpSend = new HttpSend(mActivity, !swipeRefreshLayout.isRefreshing());

            httpSend.setOnDataSendToReslutEvent(new OnDataSendToReslut() {
                @Override
                public void resultResponse(Response result) {

                    resultPutHomegrpMasterGrade(result);
                }
            });
            alTotalList.clear();
            swipeRefreshLayout.setVisibility(View.GONE);
            httpSend.putHomegrpMasterGrade(mTransferMemberId, mTransferType);
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void resultPutHomegrpMasterGrade(Response response) {
        loading = false;
        try {
            if (response.getStatusCode() == 200) {
                mUtil.getView(mToolbar, R.id.btnToolbarClose).performClick();
                onListReload();
            } else {
                JSONObject joResult = new JSONObject(response.getContent());
                Dlog.v(joResult.toString());
                String resultCode = mUtil.null2string(joResult.get(Constants.KEY_RESULT_CODE));
                String resultMsg = mUtil.null2string(joResult.get(Constants.KEY_RESULT_MSG));

                switch (resultCode) {
                    case "401":
                        customDialog.msgAlert(mActivity, Constants.MSG998, resultMsg);
                        break;
                    case "401-106":
                        customDialog.msgAlert(mActivity, Constants.MSG997, resultMsg);
                        break;
                    default:
                        customDialog.msgAlert(mActivity, Constants.MSG000, resultMsg);
                        break;
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            customDialog.msgAlert(mActivity, Constants.MSG807);
        }
    }

    @Override
    public void resultCustomDialogResponse(int msgId, int btnResult) {

        switch (msgId) {

            case Constants.MSG998:
                mUtil.callApp_Start(mActivity, "LOGOUT");
                break;
            case Constants.MSG996:
                if (btnResult == 1) {
                    loading = true;
                    mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_D_HOMEGRP_MEMBERS), Constants.HANDLER_DELAY_MILLIS);
                }
                break;
            case Constants.MSG807:
                if (btnResult == 1) {
                    mComHandler.sendMessageDelayed(mComHandler.obtainMessage(type), 10);
                }
                break;
            case Constants.MSG995:
                if (btnResult == 1) {
                    loading = true;
                    mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_P_HOMEGRP_MASTER_GRADE), Constants.HANDLER_DELAY_MILLIS);
                }
                break;
            default:
                break;
        }
    }

    /**
     * 메뉴 선택 시 처리.
     *
     * @param list 메뉴 리스트
     */
    private void msgAlertList(ArrayList<HashMap<String, Object>> list) {

        try {
            dialogListBuilder = new DialogCustomList.Builder(mActivity);
            dialogListBuilder.setList(list);
            dialogListBuilder.setPositiveButton(new AlertDialog.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                    Dlog.v("which = " + which);
                    dialog.dismiss();
                    switch (which) {
                        case 1:
                            break;
                        case 2:
                            break;
                        case 3:
                            break;
                        case 4:
                            break;
                        case 5:
                            break;
                        case 6:
                            onListReload();
                            break;
                        case 7:
                            break;
                        case 8:
                            break;
                        case 9:
                            break;
                        case 10:
                            break;
                        case 11:
                            break;
                        case 12:
                            break;
                        case 15:
                            Intent intent = new Intent(mActivity, HomeMemberAdd.class);
                            mUtil.callActivityForResult(mActivity, intent, Constants.ACT_HOMEMEMBER_ADD);
                            break;
                        case 16:
                            //삭제
//                            mUtil.getTextView(mToolbar, R.id.btnToolbarDel).setVisibility(View.VISIBLE);
                            mUtil.getTextView(mToolbar, R.id.btnToolbarClose).setVisibility(View.VISIBLE);
                            mUtil.getTextView(mToolbar, R.id.btnToolbarMore).setVisibility(View.GONE);
                            for (int row = 0; row < alTotalList.size(); row++) {
                                alTotalList.get(row).put(Constants.KEY_CHECK_YN, "N");
                            }

                            dataAdapter.setDelCheck(true);
                            dataAdapter.notifyDataSetChanged();
                            setRefresh(false);

                            break;
                        case 17:
                            mCallback.onHomeMemberWidthdraw();
                            break;
                        case 21:
                            if (null != mReceiveMemberInfo) {
                                // 권한 양도 취소
                                String member = "";
                                if ("".equals(mReceiveMemberInfo.get(Constants.KEY_NICKNAME))) {
                                    member = mReceiveMemberInfo.get(Constants.KEY_MEMBER_ID).toString();
                                } else {
                                    member = mReceiveMemberInfo.get(Constants.KEY_NICKNAME).toString();
                                }
                                mTransferMemberId = "";
                                mTransferType = REQUEST_TRANSFER_CANCEL;
                                String msg = getString(R.string.MSG926, member);
                                customDialog.msgAlert(mActivity, Constants.MSG995, msg, R.string.MSG_TITLE_007);
                            } else {
                                //권한양도
//                            mUtil.getTextView(mToolbar, R.id.btnToolbarDel).setVisibility(View.VISIBLE);
                                mUtil.getTextView(mToolbar, R.id.btnToolbarClose).setVisibility(View.VISIBLE);
                                mUtil.getTextView(mToolbar, R.id.btnToolbarMore).setVisibility(View.GONE);
                                for (int row = 0; row < alTotalList.size(); row++) {
                                    alTotalList.get(row).put(Constants.KEY_CHECK_YN, "N");
                                }

                                dataAdapter.setPermissionCheck(true);
                                dataAdapter.notifyDataSetChanged();
                                setRefresh(false);
                            }
                            break;
                        default:
                            break;
                    }
                }
            });
            dialogListBuilder.setNegativeButton(new AlertDialog.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {

                    Dlog.v("which = " + which);
                    dialog.dismiss();
                }
            });
            dialogListBuilder.create().show();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {

        super.onActivityResult(requestCode, resultCode, data);
        Boolean isReload = false;
        Dlog.v("jino1111");
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case Constants.ACT_HOMEMEMBER_DETAIL:
                case Constants.ACT_HOMEMEMBER_ADD:
                    isReload = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
                    if (isReload) {
                        onListReload();
                    }
                    break;
                default:
                    break;
            }
        } else {
            switch (requestCode) {
                case Constants.ACT_HOMEMEMBER_DETAIL:
                case Constants.ACT_HOMEMEMBER_ADD:
                    isReload = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
                    if (isReload) {
                        onListReload();
                    }
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onListReload() {

        loading = true;

        if (setHomeHubStateList()) {
            mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_G_HOMEGRP_MEMBERS), Constants.HANDLER_DELAY_MILLIS);
        }
        // do something
    }

    @Override
    public void onLogout() {
    }

    @Override
    public void onCallAction(int callType, int position) {

        if (callType == 0) {
            //추가하기
            homeMemberAdd();
        } else if (callType == 1) {
            // 상세보기
        } else if (callType == 2) {
            // 삭제하기
            alTotalList.get(position).put(Constants.KEY_CHECK_YN, "Y");
            String member = "";
            if ("".equals(alTotalList.get(position).get(Constants.KEY_NICKNAME))) {
                member = alTotalList.get(position).get(Constants.KEY_MEMBER_ID).toString();
            } else {
                member = alTotalList.get(position).get(Constants.KEY_NICKNAME).toString();
            }
            String msg = getString(R.string.MSG877, member);
            customDialog.msgAlert(mActivity, Constants.MSG996, msg, R.string.MSG_TITLE_004);
//            dataAdapter.notifyDataSetChanged();
//            loading = true;
//            mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_D_HOMEGRP_MEMBERS), 10);
        } else if (callType == 3) {
            // 권한 양도
            // 여기서 권한 양도 API 호출후 화면 갱신 그리고 전체 권한 변경 로직 들어가야함
            alTotalList.get(position).put(Constants.KEY_CHECK_YN, "Y");
            String member = "";
            if ("".equals(alTotalList.get(position).get(Constants.KEY_NICKNAME))) {
                member = alTotalList.get(position).get(Constants.KEY_MEMBER_ID).toString();
            } else {
                member = alTotalList.get(position).get(Constants.KEY_NICKNAME).toString();
            }
            mTransferMemberId = alTotalList.get(position).get(Constants.KEY_MEMBER_ID).toString();
            mTransferType = REQUEST_TRANSFER;
            String msg = getString(R.string.MSG878, member);
            customDialog.msgAlert(mActivity, Constants.MSG995, msg, R.string.MSG_TITLE_005);
//            notifyDataSetChanged();

        }
    }

    class IncomingHandlerCallBack implements Handler.Callback {

        @Override
        public boolean handleMessage(Message msg) {

            type = msg.what;
            switch (msg.what) {
                case MSG_COM_G_HOMEGRP_MEMBERS:
                    sendGetHomegrpMembers();
                    break;
                case MSG_COM_D_HOMEGRP_MEMBERS:
                    sendDeleteHomegrpMembers();
                    break;
                case MSG_COM_P_HOMEGRP_MASTER_GRADE:
                    sendPutHomegrpMasterGrade();
                    break;
                default:
                    break;
            }
            return true;
        }
    }
}
