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

package com.ntels.onecable.admin.view.install;


import com.ntels.onecable.admin.R;
import com.ntels.onecable.admin.common.AppConfig;
import com.ntels.onecable.admin.common.Constants;
import com.ntels.onecable.admin.common.c_interface.ListInterface;
import com.ntels.onecable.admin.common.c_interface.MainInterface;
import com.ntels.onecable.admin.common.c_interface.OnDataSendToReslut;
import com.ntels.onecable.admin.common.http.HttpSend;
import com.ntels.onecable.admin.common.http.Response;
import com.ntels.onecable.admin.common.util.Dlog;
import com.ntels.onecable.admin.common.util.Util;
import com.ntels.onecable.admin.common.websocket.WebSocketService;
import com.ntels.onecable.admin.view.dialog.CustomDialog;
import com.ntels.onecable.admin.view.dialog.DialogCustomList;
import com.ntels.onecable.admin.view.things.ThingsDeviceAdd;
import com.ntels.onecable.admin.view.things.ThingsDeviceDelOffStep1;
import com.ntels.onecable.admin.view.things.ThingsDeviceDelStep0;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
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 java.util.ArrayList;
import java.util.HashMap;

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

import static android.content.ContentValues.TAG;

/**
 * <pre>
 * 1. ClassName :   FragmentInstall
 * 2. FileName  :   FragmentInstall.java
 * 3. Package   :   com.ntels.onecable.view.homemember
 * 4. Date      :   2016-12-01
 * 5. Author    :   aaron
 * 6. Comment   :   Initialize
 * </pre>
 */
public class FragmentInstall 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_P_CUSTOMER_PRODUCT = 1;
    private static final int MSG_COM_P_CUSTOMER_WORK_COMPLETE = 2;
    /**
     * 마스터 권한 양도/취소 타입
     */
    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 toolbar;
    /*통신 관련*/
    private ArrayList<HashMap<String, Object>> mTotalList = new ArrayList<HashMap<String, Object>>();
    private int mType = 0;
    /*리스트 관련*/
    private FragmentInstallAdapter mDataAdapter;
    private SwipeRefreshLayout mSwipeRefreshLayout;
    private GridLayoutManager mGridLayoutManager;
    private DialogCustomList.Builder mDialogListBuilder;
    private boolean mLoading = false;
    private boolean mIsListHeader = false;
    private boolean mIsListFooter = false;
    private int listColumnsCnt = 1;
    /*공통*/
    private Activity mActivity;
    private AppConfig mAppConfig;
    private MainInterface callback;
    private Util mUtil = new Util();
    private CustomDialog mCustomDialog = new CustomDialog();
    private int mLimitCount = 10;
    private String mTransferMemberId = "";
    private String mTransferType = "";
    private HashMap<String, Object> mReceiveMemberInfo;
    Intent mIntent;


    public void recevicedWebSocket(Intent intentReceived) {

        int receivedState = intentReceived.getIntExtra(Constants.EXTRA_RESULT_STATE, WebSocketService.WEBSOCKET_RECEIVED_SUCESS);
        if (receivedState == WebSocketService.WEBSOCKET_RECEIVED_SUCESS) {
            try {
                String result = intentReceived.getStringExtra(Constants.EXTRA_RESULT);
                Dlog.v(result);
                JSONObject jsonObject = new JSONObject(result);
                String messageType = mUtil.null2string(jsonObject.get(Constants.KEY_MESSAGE_TYPE));
                Dlog.i(TAG, "websocket message mType : " + messageType);
                String resultCode = "";
                String resultMsg = "";
                if (jsonObject.has(Constants.KEY_RESULT_CODE)) {
                    resultCode = mUtil.null2string(jsonObject.get(Constants.KEY_RESULT_CODE));
                }
                if (jsonObject.has(Constants.KEY_RESULT_MSG)) {
                    resultMsg = mUtil.null2string(jsonObject.get(Constants.KEY_RESULT_MSG));
                }
                if (messageType.equals(Constants.WEBSOCKET_TYPE_NODE_COMMAND)) {
//                    resultWsNodeCommand(jsonObject);
                } else if (messageType.equals(Constants.WEBSOCKET_TYPE_NODE_COMMAND_RESULT)) {
//                    notificationWsNodeCommandResult(jsonObject);
                } else if (messageType.equals(Constants.WEBSOCKET_TYPE_NODE_CONTENT)) {
//                    notificationWsNodeContent(jsonObject);
                } else if (messageType.equals(Constants.WEBSOCKET_TYPE_NODE_REGISTER_RESULT)) {
//                    notificationWsNodeRegisterResult(jsonObject);
                } else if (messageType.equals(Constants.WEBSOCKET_TYPE_NODES_RELOAD)) {
//                    resultWsNodeReload(jsonObject);
                } else if (messageType.equals(Constants.WEBSOCKET_TYPE_NODE_DELETE_RESULT)) {
//                    notificationWsNodeDelete(jsonObject);
                } else {
                    /*final String finalResultMsg = resultMsg;
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            mUtil.setShowToast(mActivity, finalResultMsg, Toast.LENGTH_SHORT);
                        }
                    });*/
                }
            } catch (JSONException ex) {
                ex.printStackTrace();
            }

//        } else if (receivedState == WebSocketService.WEBSOCKET_RECEIVED_ERROR) {
////            if (!mUtil.getTopActivityName(mActivity).equals("view.Main")) {
////                return;
////            }
//            int errorCode = intentReceived.getIntExtra(EXTRA_ERROR_CODE, WebSocketService.WEBSOCKET_CONNECT_TIMEOUT);
//            switch (errorCode) {
//                case Constants.WEBSOCKET_ERROR_TIMEOUT:
//                    Dlog.i(TAG, "WEBSOCKET_ERROR_TIMEOUT!!!");
//                    for (HashMap<String, Object> hm : mAlTotalList) {
//                        hm.put(Constants.KEY_REQUEST_TIME, "");
//                    }
//                    break;
//                case Constants.WEBSOCKET_ERROR_NOT_CONNECTED:
//                    Dlog.i(TAG, "WEBSOCKET_ERROR_NOT_CONNECTED!!!");
//                    mCustomDialog.msgAlert(mActivity, Constants.MSG807);
//                    break;
//                default:
//                    break;
//            }
//            dispListChanged();
        }
    }
    @Override
    public void onAttach(Activity activity) {

        super.onAttach(activity);

        try {
            callback = (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_install, 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 = "Install_List";
        mAppConfig = (AppConfig) mActivity.getApplicationContext();
        mCustomDialog.setOnMsgAlterToResultEvent(this);

        mUtil.callActGoogleAnalytics(actName);

        displayListView();
    }


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

        mAppConfig.getDevicesList().clear();

        mUtil.getView(mActivity, R.id.btnInstallStart).setOnClickListener(this);
        mUtil.getView(mActivity, R.id.btnInstallStop).setOnClickListener(this);
        mSwipeRefreshLayout = (SwipeRefreshLayout) getView().findViewById(R.id.swiperefreshlayou);
        mSwipeRefreshLayout.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);
        mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {

                if (!mDataAdapter.getListCheck()) {
                    if (!mLoading) {
                        onListReload();
                    }
                } else {
                    mSwipeRefreshLayout.setRefreshing(false);
                }
            }
        });
        setRefresh(true);

        mIsListHeader = true;
        mIsListFooter = false;
        mDataAdapter = new FragmentInstallAdapter(mActivity, R.layout.row_install_head,
                R.layout.row_install_list, R.layout.row_install_head,
                mTotalList, this);
        mDataAdapter.setHeaderCheck(mIsListHeader);
        mDataAdapter.setFooterCheck(mIsListFooter);

        RecyclerView recyclerView = (RecyclerView) getView().findViewById(R.id.rcvList);
        recyclerView.setHasFixedSize(true);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(mActivity);
        recyclerView.setLayoutManager(linearLayoutManager);
        AlphaInAnimationAdapter alphaAdapter = new AlphaInAnimationAdapter(mDataAdapter);
        alphaAdapter.setDuration(150);
        ScaleInAnimationAdapter scaleAdapter = new ScaleInAnimationAdapter(alphaAdapter);
        scaleAdapter.setDuration(150);
        recyclerView.setAdapter(scaleAdapter);


        if (mAppConfig.getIsCustomerConn()) {
            mUtil.getView(mActivity, R.id.llDisconnect).setVisibility(View.GONE);
            mUtil.getView(mActivity, R.id.llConnectBody).setVisibility(View.VISIBLE);
            mUtil.getView(mActivity, R.id.btnInstallStart).setVisibility(View.VISIBLE);
            mUtil.getView(mActivity, R.id.btnInstallStop).setVisibility(View.GONE);
            onListReload();
        } else {
            mUtil.getView(mActivity, R.id.llDisconnect).setVisibility(View.VISIBLE);
            mUtil.getView(mActivity, R.id.llConnectBody).setVisibility(View.GONE);
        }
//        setHomeHubStateTitle();
    }


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

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

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

        mDataAdapter.setEditCheck(isEnable);
//        for (int row = 0; row < mTotalList.size(); row++) {
//            HashMap<String, Object> hmTempCategory = new HashMap<String, Object>();
//            hmTempCategory = mTotalList.get(row);
//            hmTempCategory.put(Constants.KEY_EDIT_YN, mDataAdapter.getEditCheck()?"Y":"N");
//        }
        mDataAdapter.notifyDataSetChanged();

    }

    @Override
    public void onClick(View view) {

        switch (view.getId()) {
            case R.id.btnInstallStart:
                setEditMode(true);
                mUtil.getView(mActivity, R.id.btnInstallStart).setVisibility(View.GONE);
                mUtil.getView(mActivity, R.id.btnInstallStop).setVisibility(View.VISIBLE);
                break;
            case R.id.btnInstallStop:
                mUtil.getView(mActivity, R.id.btnInstallStop).setEnabled(false);
                mComHandler.sendMessageDelayed(mComHandler.obtainMessage(MSG_COM_P_CUSTOMER_WORK_COMPLETE), 10);
                break;
            default:
                break;
        }
    }


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

        switch (msgId) {

            case Constants.MSG998:
                mUtil.callApp_Start(mActivity, "LOGOUT");
                break;
            case Constants.MSG807:
                if (btnResult == 1) {
                    mComHandler.sendMessageDelayed(mComHandler.obtainMessage(mType), 10);
                }
                break;
            default:
                break;
        }
    }


    @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_INSTALL_HOMEHUB_DEL:
                case Constants.ACT_INSTALL_HOMEHUB_REGISTER:
                    isReload = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
                    if (isReload) {
                        onListReload();
                    }
                    break;
                default:
                    break;
            }
        } else {
            switch (requestCode) {
                case Constants.ACT_INSTALL_HOMEHUB_DEL:
                case Constants.ACT_INSTALL_HOMEHUB_REGISTER:
                    isReload = data.getBooleanExtra(Constants.EXTRA_RELOAD_FLAG, false);
                    if (isReload) {
                        onListReload();
                    }
                    break;
                default:
                    break;
            }
        }
    }

    @Override
    public void onListReload() {

        mLoading = true;

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

    @Override
    public void onLogout() {
    }

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

        if (callType == 0) {
            //추가하기
            Dlog.v("jino1111");
            if (mDataAdapter.getEditCheck()) {
                String deviceTypeId = mUtil.null2string(mTotalList.get(position).get(Constants.KEY_DEVICE_TYPE_ID));
                String categoryName = mUtil.null2string(mTotalList.get(position).get(Constants.KEY_CATEGORY_NAME));
                Dlog.v("jino1112 deviceTypeId =" + deviceTypeId);
                if (deviceTypeId.equals(Constants.DEVICE_TYPE_ID_GATEWAY)) {
                    Dlog.v("jino1113");
                    Intent intent = new Intent(mActivity, HomehubRegister.class);
                    mUtil.callActivityForResultNoAnim(mActivity, intent, Constants.ACT_INSTALL_HOMEHUB_REGISTER);
                } else {
                    Intent intent = new Intent(mActivity, ThingsDeviceAdd.class);
                    intent.putExtra(Constants.EXTRA_DEVICE_ID, mAppConfig.getFirstHomehubDeviceId());
                    intent.putExtra(Constants.EXTRA_DEVICE_TYPE_ID, deviceTypeId);
                    intent.putExtra(Constants.EXTRA_DVCGRP_NAME, categoryName);
                    mUtil.callActivityForResult(mActivity, intent, Constants.ACT_THINGS_DEVICE_ADD);
                }
            }
        } else if (callType == 1) {
            // 상세보기
        } else if (callType == 2) {
            HashMap<String, Object> delDevice = mDataAdapter.getDeleteInfo();
            String categoryName = mUtil.null2string(delDevice.get(Constants.KEY_CATEGORY_NAME));
            String deviceTypeId = mUtil.null2string(delDevice.get(Constants.KEY_DEVICE_TYPE_ID));
            String deviceId = mUtil.null2string(delDevice.get(Constants.KEY_DEVICE_ID));
            String nodeId = mUtil.null2string(delDevice.get(Constants.KEY_NODE_ID));
            String onlineState = mUtil.null2string(delDevice.get(Constants.KEY_ONLINE_STATE));
            String deviceName = mUtil.null2string(delDevice.get(Constants.KEY_PRD_USER_NAME));
            if ("".equals(deviceName)) {
                deviceName = mUtil.null2string(delDevice.get(Constants.KEY_PRD_NAME));
            }
            if (deviceTypeId.equals(Constants.DEVICE_TYPE_ID_GATEWAY)) {
                Intent intent = new Intent(mActivity, HomehubDel.class);
                intent.putExtra(Constants.EXTRA_DEVICE_ID, deviceId);
                mUtil.callActivityForResultNoAnim(mActivity, intent, Constants.ACT_INSTALL_HOMEHUB_DEL);
            } else {
                if (onlineState.equals("OFF")) {
                    mIntent = new Intent(mActivity, ThingsDeviceDelOffStep1.class);
                } else {
                    mIntent = new Intent(mActivity, ThingsDeviceDelStep0.class);
                }
                mIntent.putExtra(Constants.EXTRA_DEVICE_NAME, deviceName);
                mIntent.putExtra(Constants.EXTRA_DEVICE_ID, deviceId);
                mIntent.putExtra(Constants.EXTRA_NODE_ID, nodeId);



//                if (deviceclassTypeId == Constants.DEVICECLASS_TYPE_ID_40302) {
//                    mIntent.putExtra(Constants.EXTRA_COMPANY_NAME, mUtil.getString(mActivity, R.string.layout_things_device_add_03));
//                    mIntent.putExtra(Constants.EXTRA_DEVICE_DEL_DESC, mUtil.getString(mActivity, R.string.layout_things_device_add_del_04));
//                    mIntent.putExtra(Constants.EXTRA_DEVICE_IMAGE, R.drawable.img_things_product_addimg_01_smartgasvalve);
//                    mIntent.putExtra(Constants.EXTRA_DEVICE_IMAGE1, R.drawable.img_things_product_addimg_01_smartgasvalve_wait);
//                } else
                 if (deviceTypeId.equals(Constants.DEVICE_TYPE_ID_GASVALVE_CLOSEONLY)) {
//                    Gas Valve(Close Only)
                    mIntent.putExtra(Constants.EXTRA_COMPANY_NAME, mUtil.getString(mActivity, R.string.layout_things_device_add_03));
                    mIntent.putExtra(Constants.EXTRA_DEVICE_DEL_DESC, mUtil.getString(mActivity, R.string.layout_things_device_add_del_04));
                    mIntent.putExtra(Constants.EXTRA_DEVICE_IMAGE, R.drawable.img_things_product_addimg_01_smartgasvalve);
                    mIntent.putExtra(Constants.EXTRA_DEVICE_IMAGE1, R.drawable.img_things_product_addimg_01_smartgasvalve_wait);
                } else if (deviceTypeId.equals(Constants.DEVICE_TYPE_ID_SMARTPLUG)) {
                    //Smart Plug
                    mIntent.putExtra(Constants.EXTRA_COMPANY_NAME, mUtil.getString(mActivity, R.string.layout_things_device_add_05));
                    mIntent.putExtra(Constants.EXTRA_DEVICE_DEL_DESC, mUtil.getString(mActivity, R.string.layout_things_device_add_del_05));
                    mIntent.putExtra(Constants.EXTRA_DEVICE_IMAGE, R.drawable.img_things_product_addimg_02_iotplug);
                    mIntent.putExtra(Constants.EXTRA_DEVICE_IMAGE1, R.drawable.img_things_product_addimg_02_iotplug_wait);
                 } else if (deviceTypeId.equals(Constants.DEVICE_TYPE_ID_DOORSENSOR)) {
                    //Door Sensor
                    mIntent.putExtra(Constants.EXTRA_COMPANY_NAME, mUtil.getString(mActivity, R.string.layout_things_device_add_11));
                    mIntent.putExtra(Constants.EXTRA_DEVICE_DEL_DESC, mUtil.getString(mActivity, R.string.layout_things_device_add_del_12));
                    mIntent.putExtra(Constants.EXTRA_DEVICE_IMAGE, R.drawable.img_things_product_addimg_06_mutisensor_door);
                    mIntent.putExtra(Constants.EXTRA_DEVICE_IMAGE1, R.drawable.img_things_product_addimg_06_mutisensor_door_wait);
//                } else if (deviceclassTypeId == Constants.DEVICECLASS_TYPE_ID_40107) {
//                    mIntent.putExtra(Constants.EXTRA_COMPANY_NAME, mUtil.getString(mActivity, R.string.layout_things_device_add_09));
//                    mIntent.putExtra(Constants.EXTRA_DEVICE_DEL_DESC, mUtil.getString(mActivity, R.string.layout_things_device_add_del_08));
//                    mIntent.putExtra(Constants.EXTRA_DEVICE_IMAGE, R.drawable.img_things_product_addimg_04_mutisensor_motion);
//                    mIntent.putExtra(Constants.EXTRA_DEVICE_IMAGE1, R.drawable.img_things_product_addimg_04_mutisensor_motion_wait);
//                } else if (deviceclassTypeId == Constants.DEVICECLASS_TYPE_ID_40801) {
//                    mComHandler.sendEmptyMessageDelayed(MSG_COM_WS_NODE_DELETE, 10);
//                    return;
//                } else if (deviceclassTypeId == Constants.DEVICECLASS_TYPE_ID_40802) {
//                    mComHandler.sendEmptyMessageDelayed(MSG_COM_D_CLOUD_NODE, 10);
//                    return;
//                } else if (deviceProtocolType.equalsIgnoreCase("WIRED")) {
//                    // Weather station을 비롯한 유선 연결기기는 삭제처리하지않는다.
//                    mCustomDialog.msgAlert(mActivity, Constants.MSG921);
//                    return;
                } else {
                    mIntent.putExtra(Constants.EXTRA_COMPANY_NAME, mUtil.getString(mActivity, R.string.layout_things_device_add_15));
                    mIntent.putExtra(Constants.EXTRA_DEVICE_DESC, mUtil.getString(mActivity, R.string.layout_things_device_add_del_13));
                    mIntent.putExtra(Constants.EXTRA_DEVICE_DESC1, mUtil.getString(mActivity, R.string.layout_things_device_add_del_15));
                    mIntent.putExtra(Constants.EXTRA_DEVICE_IMAGE, R.drawable.img_things_product_addimg_00_zwave);
                    mIntent.putExtra(Constants.EXTRA_DEVICE_IMAGE1, R.drawable.img_things_product_addimg_00_zwave_wait);
                }

                if (onlineState.equals("OFF")) {
                    mUtil.callActivityForResultNoAnim(mActivity, mIntent, Constants.ACT_THINGS_DEVICE_DEL_OFF_STEP1);
                } else {
                    mUtil.callActivityForResultNoAnim(mActivity, mIntent, Constants.ACT_THINGS_DEVICE_DEL_STEP0);
                }
            }
        } else if (callType == 3) {

        }
    }

    private void sendCustomerProduct() {

        try {
            HttpSend httpSend;

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


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

                    resultCustomerProduct(result);
                }
            });
            httpSend.postCustomerProduct(mAppConfig.getCustId(), mAppConfig.getCustomerCtrtId(), mAppConfig.getCustomerMemberId());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void resultCustomerProduct(Response result) {

        mLoading = false;
        try {
            if (result.getStatusCode() == Response.OK) {
                Dlog.v("response.getContent() = " + result.getContent());

                JSONObject joResult = new JSONObject(result.getContent());


                String categoryList = mUtil.null2string(joResult.get(Constants.KEY_CATEGORY_LIST));
                mTotalList.clear();
                HashMap<String, Object> hmTemp = new HashMap<String, Object>();
                mTotalList.add(hmTemp);

                ArrayList<HashMap<String, Object>> alCategoryList = mUtil.jsonToArrayListMap(categoryList);

                if (alCategoryList.size() > 0) {
                    for (int row = 0; row < alCategoryList.size(); row++) {
                        HashMap<String, Object> hmTempCategory = new HashMap<String, Object>();
                        hmTempCategory = alCategoryList.get(row);
                        hmTempCategory.put(Constants.KEY_EDIT_YN, mDataAdapter.getEditCheck() ? "Y" : "N");
                        mTotalList.add(hmTempCategory);
                    }
                }
                mSwipeRefreshLayout.setVisibility(View.VISIBLE);
                mDataAdapter.notifyDataSetChanged();
                setRefresh(true);
            } else {
                JSONObject joResult = new JSONObject(result.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));

                if ("401".equals(resultCode)) {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG998, resultMsg);
                } else if ("401-106".equals(resultCode)) {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG997, resultMsg);
                } else {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG000, resultMsg);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            mCustomDialog.msgAlert(mActivity, Constants.MSG807);
        } finally {
            mSwipeRefreshLayout.setRefreshing(false);
        }
    }

    private void sendCustomerWorkComplete() {

        try {
            HttpSend httpSend;

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


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

                    resultCustomerWorkComplete(result);
                }
            });
            httpSend.putCustomerWorkComplete(mAppConfig.getCustId(), mAppConfig.getCustomerCtrtId(), mAppConfig.getCustomerMemberId());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private void resultCustomerWorkComplete(Response result) {

        mLoading = false;
        mUtil.getView(mActivity, R.id.btnInstallStop).setEnabled(true);
        try {
            if (result.getStatusCode() == Response.OK) {
                Dlog.v("response.getContent() = " + result.getContent());

                setEditMode(false);
                mUtil.getView(mActivity, R.id.btnInstallStart).setVisibility(View.VISIBLE);
                mUtil.getView(mActivity, R.id.btnInstallStop).setVisibility(View.GONE);
            } else {
                JSONObject joResult = new JSONObject(result.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));

                if ("401".equals(resultCode)) {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG998, resultMsg);
                } else if ("401-106".equals(resultCode)) {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG997, resultMsg);
                } else {
                    mCustomDialog.msgAlert(mActivity, Constants.MSG000, resultMsg);
                }
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            mCustomDialog.msgAlert(mActivity, Constants.MSG807);
        } finally {
            mSwipeRefreshLayout.setRefreshing(false);
        }
    }

    class IncomingHandlerCallBack implements Handler.Callback {

        @Override
        public boolean handleMessage(Message msg) {

            mType = msg.what;
            switch (msg.what) {
                case MSG_COM_P_CUSTOMER_PRODUCT:
                    sendCustomerProduct();
                    break;
                case MSG_COM_P_CUSTOMER_WORK_COMPLETE:
                    sendCustomerWorkComplete();
                    break;
                default:
                    break;
            }
            return true;
        }
    }
}
