package com.tomas.ckd_system;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.tomas.ckd_system.Adapter.Staging_Adapter_Detail;
import com.tomas.ckd_system.List_Class.Staging_detail_list;
import com.tomas.ckd_system.lib.ProductionSchedule;
import com.tomas.ckd_system.lib.Settings;
import com.tomas.ckd_system.lib.common.AsyncHttpClient;
import com.tomas.ckd_system.lib.common.CallbackListener;
import com.tomas.ckd_system.lib.common.MessageListener;

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

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import cn.pedant.SweetAlert.SweetAlertDialog;
import okhttp3.WebSocket;

public class Staging_Detail_Activity extends AppCompatActivity implements View.OnClickListener, MessageListener, CallbackListener , ClickRowItemStaging{

    Spinner spinner_status;
    RecyclerView view_staging_detail;
    WsClient wsClient;
    Button btn_meiji_card, btn_packing;

    EditText edt_model, edt_dest, edt_pclot, edt_model_type, edt_packing_date, edt_packing_line;
    TextView txt_HT, txt_model, txt_dest, txt_pc_lot, txt_type, txt_packing, txt_packing_line;
    String str_today; //str_pc_no, str_model_no, str_model_type, str_dist,str_line_no, str_control_no, str_case_no,
    ConstraintLayout Layout_choice_pdf, layout_staging_detail;
    String str_user_id, str_status, str_outer_plan_date, str_url_meiji_card, str_url_packing_method, str_pc_no, str_control_no, str_part_no,
            str_part_color,Str_case_no, str_packing_no;
//            str_schedule_id;
    Button btn_search, btn_clear;
//    Bundle bundle;
    int position;
    Intent intent_pdf;
    SimpleDateFormat dt_format;
    private JSONArray j_schedules;
    Calendar calendar;
    boolean isOpenPDF;
    int pdf_content = 1001;
    ArrayList<String> list_status;
    List<Staging_detail_list> staging_list;
    Staging_Adapter_Detail staging_adapter_detail;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_staging_detail);
        // update MessageListener class
        WsClient.getInstance().setOnMessageListener(this);

        dt_format = new SimpleDateFormat("yyyy-MM-dd");
        calendar = Calendar.getInstance();
        calendar = (Calendar) calendar.clone();
        str_today = dt_format.format(calendar.getTime());
        Log.d(getString(R.string.tag), "datetime_to_server: " + str_outer_plan_date);

        layout_staging_detail = (ConstraintLayout)findViewById(R.id.layout_staging_detail);
        Layout_choice_pdf = (ConstraintLayout)findViewById(R.id.view_choice_pdf);
        btn_search = (Button)findViewById(R.id.btn_search);
        btn_clear = (Button)findViewById(R.id.btn_clear);
        btn_meiji_card = (Button)findViewById(R.id.btn_meiji_card);
        btn_packing = (Button)findViewById(R.id.btn_packing);

        list_status = new ArrayList<String>();
        staging_list = new ArrayList<Staging_detail_list>();

        txt_HT = (TextView)findViewById(R.id.txt_device_ht);
        txt_HT.setText("Handy terminal #"+Settings.getDeviceHT().getDevice_id());
        str_user_id = Settings.getLoginUser().getName();

        edt_model = (EditText) findViewById(R.id.edt_model);
        edt_model.setEnabled(true);

        edt_dest = (EditText) findViewById(R.id.edt_dest);
        edt_dest.setEnabled(true);

        edt_model_type = (EditText) findViewById(R.id.edt_type);
        edt_model_type.setEnabled(true);

        edt_packing_date = (EditText) findViewById(R.id.edt_packing_date);
        edt_packing_date.setEnabled(true);
        edt_packing_date.setText(str_today);
        edt_packing_date.setInputType(InputType.TYPE_NULL);
        edt_packing_date.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Calendar currentDate = Calendar.getInstance();
                new DatePickerDialog(Staging_Detail_Activity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        currentDate.set(Calendar.YEAR,year);
                        currentDate.set(Calendar.MONTH,monthOfYear);
                        currentDate.set(Calendar.DATE,dayOfMonth);
                        str_outer_plan_date = dt_format.format(currentDate.getTime());
                        edt_packing_date.setText(str_outer_plan_date);
                        Log.d(getString(R.string.tag), "packing_date "+str_outer_plan_date);
                    }
                }, currentDate.get(Calendar.YEAR), currentDate.get(Calendar.MONTH), currentDate.get(Calendar.DATE)).show();
            }
        });

        edt_packing_line = (EditText) findViewById(R.id.edt_packing_line);
        edt_packing_line.setEnabled(true);

        edt_pclot = (EditText) findViewById(R.id.edt_pclot);
        edt_pclot.setEnabled(true);

        txt_model = (TextView)findViewById(R.id.txt_model);
        txt_dest = (TextView)findViewById(R.id.txt_dest);
        txt_type = (TextView)findViewById(R.id.txt_type);
        txt_packing = (TextView)findViewById(R.id.txt_packing);
        txt_packing_line = (TextView)findViewById(R.id.txt_packing_line);
        txt_pc_lot = (TextView)findViewById(R.id.txt_pc_lot);

        spinner_status = (Spinner) findViewById(R.id.spinner_status);
        spinner_status.setSelection(0);

        view_staging_detail = (RecyclerView) findViewById(R.id.view_staging_detail);
        view_staging_detail.setHasFixedSize(true);
        view_staging_detail.setRecycledViewPool(new RecyclerView.RecycledViewPool());
        view_staging_detail.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        view_staging_detail.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        view_staging_detail.setItemAnimator(new DefaultItemAnimator());

    }

    @Override
    protected void onStart() {
        super.onStart();
//        str_status = spinner_status.getSelectedItem().toString().trim();
//        position = spinner_status.getSelectedItemPosition();
//        Log.d(getString(R.string.tag), "spinner SelectedItemPosition: "+String.valueOf(position));
//
//        if (str_status.equals("All")){
//            str_status = "";
//        }
//
//        str_outer_plan_date = edt_packing_date.getText().toString().trim();
//        Get_Schedule_ID("37333S570718", "80HF");

    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_search:
//                if(edt_model.getText().toString().trim().equals("")||
//                edt_dest.getText().toString().trim().equals("")||
//                edt_pclot.getText().toString().trim().equals("")||
//                edt_model_type.getText().toString().trim().equals("")||
//                edt_packing_line.getText().toString().trim().equals("")){
//                    new SweetAlertDialog(Staging_Detail_Activity.this, SweetAlertDialog.WARNING_TYPE)
//                            .setTitleText("WARNING")
//                            .setContentText("Pleas complete data!")
//                            .show();
//
//                }else {
                    btn_search.setEnabled(false);
                    btn_search.setBackgroundResource(R.drawable.button_backgroup_gray);
                    hideKeyboard(this);

                    str_status = spinner_status.getSelectedItem().toString().trim();
                    position = spinner_status.getSelectedItemPosition();
                    Log.d(getString(R.string.tag), "spinner SelectedItemPosition: " + String.valueOf(position));

                    if (str_status.equals("All")) {
                        str_status = "";
                    }

                    str_outer_plan_date = edt_packing_date.getText().toString().trim();
                    Get_Schedule(str_status, str_outer_plan_date);
//                }

                break;

            case R.id.btn_clear:
                btn_search.setEnabled(true);
                btn_search.setBackgroundResource(R.drawable.button_backgroup_green);

                staging_list.clear();
                edt_model.setText("");
                txt_model.setText("");
                edt_dest.setText("");
                txt_dest.setText("");
                edt_pclot.setText("");
                txt_pc_lot.setText("");
                edt_model_type.setText("");
                txt_type.setText("");
                edt_packing_date.setText("");
                txt_packing.setText("");
                edt_packing_date.setText(str_today);
                txt_packing_line.setText("");

                spinner_status.setSelection(0);
                staging_list.clear();
                staging_adapter_detail = new Staging_Adapter_Detail(staging_list, Staging_Detail_Activity.this, Staging_Detail_Activity.this);
                view_staging_detail.setAdapter(staging_adapter_detail);
                break;

            case R.id.btn_main:
                finish();
                break;

            case R.id.btn_close_view_choice_pdf:
                layout_staging_detail.setVisibility(View.VISIBLE);
                Layout_choice_pdf.setVisibility(View.GONE);
                break;

            case R.id.btn_meiji_card:
                layout_staging_detail.setVisibility(View.VISIBLE);
                Layout_choice_pdf.setVisibility(View.GONE);

                String url_pdf =  Settings.getMgmtList().get("web_api") + "/res/MeijiCard/"+str_url_meiji_card;
                url_pdf = url_pdf.replace("'\'","");
                Log.d(getString(R.string.tag), "path_pdf : " + url_pdf);


                Intent intent = new Intent();
                intent.setDataAndType(Uri.parse(url_pdf), "application/pdf");
                startActivity(intent);

                try {
                    JSONObject j_ext;
                    j_ext = new JSONObject();
                    j_ext.put("user_id", Settings.getLoginUser().getId());
                    j_ext.put("device_id", Settings.getDeviceNo());
                    j_ext.put("device_type", getString(R.string.device_type));
                    j_ext.put("event", WsProtocol.EVENT.TB_STAGING_MONITOR_MEIJI_CARD_SUCCESS);
                    j_ext.put("status", ProductionSchedule.STATUS.WORKING);
                    j_ext.put("stage", ProductionSchedule.STAGE.STAGING);
//                    j_ext.put("schedule_id", str_schedule_id);
                    j_ext.put("pc_no", str_pc_no);
                    j_ext.put("control_no", str_control_no);
                    j_ext.put("part_no", str_part_no);
                    j_ext.put("part_color", str_part_color);
                    WsClient.getInstance().sendMessage(
                            WsProtocol.encapsulation(
                                    WsProtocol.COMMAND.EVENT_LOG_REQUEST.toString(),
                                    j_ext
                            )
                    );

                } catch (JSONException e) {
                    new SweetAlertDialog(Staging_Detail_Activity.this, SweetAlertDialog.ERROR_TYPE)
                            .setTitleText("ERROR")
                            .setContentText(e.getMessage())
                            .show();
                } catch (Exception e) {
                    if (e.getMessage().trim().equals("The server might crash")){
                        WsClient.getInstance().connect();
                    }
                }
                break;

            case R.id.btn_packing:
                Layout_choice_pdf.setVisibility(View.GONE);
                layout_staging_detail.setVisibility(View.VISIBLE);

                String url_packing =  Settings.getMgmtList().get("web_api") + "/res/MeijiCard/"+str_url_packing_method;
                url_packing = url_packing.replace("'\'","");
                Log.d(getString(R.string.tag), "path_pdf : " + url_packing);

                Intent intent_packing = new Intent();
                intent_packing.setDataAndType(Uri.parse(url_packing), "application/pdf");
                startActivity(intent_packing);

                try {
                    JSONObject j_ext;
                    j_ext = new JSONObject();
                    j_ext.put("user_id", Settings.getLoginUser().getId());
                    j_ext.put("device_id", Settings.getDeviceNo());
                    j_ext.put("device_type", getString(R.string.device_type));
                    j_ext.put("event", WsProtocol.EVENT.TB_STAGING_MONITOR_PACKING_METHOD_SUCCESS);
                    j_ext.put("status", ProductionSchedule.STATUS.WORKING);
                    j_ext.put("stage", ProductionSchedule.STAGE.STAGING);
//                    j_ext.put("schedule_id", str_schedule_id);
                    j_ext.put("pc_no", str_pc_no);
                    j_ext.put("control_no", str_control_no);
                    j_ext.put("part_no", str_part_no);
                    j_ext.put("part_color", str_part_color);
                    WsClient.getInstance().sendMessage(
                            WsProtocol.encapsulation(
                                    WsProtocol.COMMAND.EVENT_LOG_REQUEST.toString(),
                                    j_ext
                            )
                    );
                } catch (JSONException e) {
                    new SweetAlertDialog(Staging_Detail_Activity.this, SweetAlertDialog.ERROR_TYPE)
                            .setTitleText("ERROR")
                            .setContentText(e.getMessage())
                            .show();
                } catch (Exception e) {
                    if (e.getMessage().trim().equals("The server might crash")){
                        WsClient.getInstance().connect();
                    }
                }
                break;
        }
    }

    public static void hideKeyboard(@NonNull Activity activity) {
        // Check if no view has focus:
        View view = activity.getCurrentFocus();
        if (view != null) {
            InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
            inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

    private void Get_Schedule(String status, String outer_plan_dt) {
        staging_list.clear();

        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "get_staging_detail_p3");
            json.put("outer_plan_date", outer_plan_dt);
            json.put("pc_no", edt_pclot.getText().toString().trim());
//            json.put("control_no", "");
            json.put("model_no",edt_model.getText().toString().trim());
            json.put("model_type", edt_model_type.getText().toString().trim());
            json.put("line_no", edt_packing_line.getText().toString().trim());
            json.put("dist", edt_dest.getText().toString().trim());
            json.put("status", status);
//            json.put("case_no", str_case_no);

            new AsyncHttpClient(getApplicationContext()
                    , Settings.getMgmtList().get("web_api") + "/api_tablet.php"
                    , json.toString()
            ) {
                @Override
                public void onFinished(String response, int resp_code) {
                    Log.d(getString(R.string.tag), "response: " + response);

                    try {
                        JSONArray jArray = new JSONArray(response);
                        Log.d(getString(R.string.tag), "response json length: " + jArray.length());

                        if (jArray.length()==0){
                            staging_list.clear();

                            Toast.makeText(Staging_Detail_Activity.this,"Not found schedule",Toast.LENGTH_SHORT).show();

                        }else {
                            String control_old = "old", before_color = "white";

                            for (int i = 0; i < jArray.length(); i++){
                                JSONObject obj = jArray.getJSONObject(i);

                                String staging_act_dt = jArray.getJSONObject(i).getString("staging_act_dt");
                                if (staging_act_dt.trim().equals("")||staging_act_dt.trim().equals("null")){
                                    staging_act_dt = "";
                                }else {
                                    JSONObject array_date = obj.getJSONObject("staging_act_dt");
                                    staging_act_dt = array_date.getString("date");
                                    staging_act_dt = staging_act_dt.substring(0,19);
                                }

                                String bg_color;
                                String control_new = jArray.getJSONObject(i).getString("control_no");

                                if(control_new.trim().equals(control_old)){
                                    control_old = control_new;
                                    bg_color = before_color;

                                }else {
                                    if(before_color.trim().equals("white")){
                                        before_color = "blue";

                                    }else{
                                        before_color = "white";
                                    }
                                    control_old = control_new;
                                    bg_color = before_color;
                                }

                                staging_list.add(new Staging_detail_list(
                                        String.valueOf(i+1),
                                        jArray.getJSONObject(i).getString("schedule_id"),
                                        jArray.getJSONObject(i).getString("dist").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("dist"),
                                        jArray.getJSONObject(i).getString("model_no").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("model_no"),
                                        jArray.getJSONObject(i).getString("model_type").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("model_type"),
                                        jArray.getJSONObject(i).getString("part_name").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("part_name"),
                                        jArray.getJSONObject(i).getString("item_no"),
                                        jArray.getJSONObject(i).getString("part_no"),
                                        jArray.getJSONObject(i).getString("control_no"),
                                        jArray.getJSONObject(i).getString("case_no"),
                                        jArray.getJSONObject(i).getString("part_color").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("part_color"),
                                        jArray.getJSONObject(i).getString("pc_no").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("pc_no"),
                                        jArray.getJSONObject(i).getString("line_no").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("line_no"),
                                        jArray.getJSONObject(i).getString("maker_code"),
                                        jArray.getJSONObject(i).getString("maker_name").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("maker_name"),
                                        jArray.getJSONObject(i).getString("receive_plan_qty").trim().equals("null") ? "0" : jArray.getJSONObject(i).getString("receive_plan_qty"),
                                        jArray.getJSONObject(i).getString("receive_act_qty").trim().equals("null") ? "0" : jArray.getJSONObject(i).getString("receive_act_qty"),
                                        jArray.getJSONObject(i).getString("staging_plan_qty").trim().equals("null") ? "0" : jArray.getJSONObject(i).getString("staging_plan_qty"),
                                        jArray.getJSONObject(i).getString("staging_act_qty").trim().equals("null") ? "0" : jArray.getJSONObject(i).getString("staging_act_qty"),
                                        staging_act_dt,
                                        jArray.getJSONObject(i).getString("staging_user_id").trim().equals("null")? "" : jArray.getJSONObject(i).getString("staging_user_id"),
                                        jArray.getJSONObject(i).getString("url_meiji_card").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("url_meiji_card"),
                                        jArray.getJSONObject(i).getString("url_packing_method").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("url_packing_method"),
                                        jArray.getJSONObject(i).getString("status"),
                                        bg_color,
                                        jArray.getJSONObject(i).getString("case_packing_seq")));

                            }
//                            String model_no = jArray.getJSONObject(0).getString("model_no").trim().equals("null") ? "" : jArray.getJSONObject(0).getString("model_no").trim();
//                            String dest = jArray.getJSONObject(0).getString("dist").trim().equals("null") ? "" : jArray.getJSONObject(0).getString("dist").trim();
//                            String pc_no = jArray.getJSONObject(0).getString("pc_no").trim().equals("null") ? "" : jArray.getJSONObject(0).getString("pc_no").trim();
//                            String model_type = jArray.getJSONObject(0).getString("model_type").trim().equals("null") ? "" : jArray.getJSONObject(0).getString("model_type").trim();
//                            String line_no = jArray.getJSONObject(0).getString("line_no").trim().equals("null") ? "" : jArray.getJSONObject(0).getString("line_no").trim();
//                            String outer_plan_date = jArray.getJSONObject(0).getString("outer_plan_date");
//                            if (outer_plan_date.trim().equals("")||outer_plan_date.trim().equals("null")){
//                                outer_plan_date = "";
//                            }else {
//                                JSONObject array_date = jArray.getJSONObject(0).getJSONObject("outer_plan_date");
//                                outer_plan_date = array_date.getString("date");
//                                outer_plan_date = outer_plan_date.substring(0,19);
//                            }
//                            edt_model.setText(model_no);
//                            txt_model.setText(model_no);
//                            edt_dest.setText(dest);
//                            txt_dest.setText(dest);
//                            edt_pclot.setText(pc_no);
//                            txt_pc_lot.setText(pc_no);
//                            edt_model_type.setText(model_type);
//                            txt_type.setText(model_type);
//                            edt_packing_date.setText(outer_plan_date);
//                            txt_packing.setText(outer_plan_date);
//                            edt_packing_date.setText(line_no);
//                            txt_packing_line.setText(line_no);
                        }
                        staging_adapter_detail = new Staging_Adapter_Detail(staging_list, Staging_Detail_Activity.this, Staging_Detail_Activity.this);
                        view_staging_detail.setAdapter(staging_adapter_detail);

                        btn_search.setEnabled(true);
                        btn_search.setBackgroundResource(R.drawable.button_backgroup_green);

                    } catch (JSONException e) {
                        btn_search.setEnabled(true);
                        btn_search.setBackgroundResource(R.drawable.button_backgroup_green);
                        new SweetAlertDialog(Staging_Detail_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        } catch (JSONException e) {
            btn_search.setEnabled(true);
            btn_search.setBackgroundResource(R.drawable.button_backgroup_green);
            new SweetAlertDialog(Staging_Detail_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

    private void Get_Schedule_ID(String pc_no, String control_no, String case_no) {
        staging_list.clear();
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "get_staging_id");
            json.put("pc_no", pc_no);
            json.put("control_no", control_no);
            json.put("case_no", case_no);

            new AsyncHttpClient(getApplicationContext()
                    , Settings.getMgmtList().get("web_api") + "/api_tablet.php"
                    , json.toString()
            ) {
                @Override
                public void onFinished(String response, int resp_code) {
                    Log.d(getString(R.string.tag), "response: " + response);

                    try {
                        JSONArray jArray = new JSONArray(response);
                        Log.d(getString(R.string.tag), "response json length: " + jArray.length());

                        if (jArray.length()==0){
                            staging_list.clear();
                            edt_model.setText("");
                            txt_model.setText("");
                            edt_dest.setText("");
                            txt_dest.setText("");
                            edt_pclot.setText("");
                            txt_pc_lot.setText("");
                            edt_model_type.setText("");
                            txt_type.setText("");
                            edt_packing_date.setText("");
                            txt_packing.setText("");
                            edt_packing_date.setText("");
                            txt_packing_line.setText("");
                            Toast.makeText(Staging_Detail_Activity.this,"Not found schedule",Toast.LENGTH_SHORT).show();

                        }else {
                            Log.d(getString(R.string.tag), "else: " + response);
                            String control_old = "old", before_color = "white";

                            for (int i = 0; i < jArray.length(); i++){
                                Log.d(getString(R.string.tag), "for: " + i);
                                JSONObject obj = jArray.getJSONObject(i);

                                String staging_act_dt = jArray.getJSONObject(i).getString("staging_act_dt");
                                if (staging_act_dt.trim().equals("")||staging_act_dt.trim().equals("null")){
                                    staging_act_dt = "";
                                }else {
                                    JSONObject array_date = obj.getJSONObject("staging_act_dt");
                                    staging_act_dt = array_date.getString("date");
                                    staging_act_dt = staging_act_dt.substring(0,19);
                                }
                                Log.d(getString(R.string.tag), "staging_act_dt: " + staging_act_dt);

                                String bg_color;
                                String control_new = jArray.getJSONObject(i).getString("control_no");
                                Log.d(getString(R.string.tag), "control_no: " + control_no);

                                if(control_new.trim().equals(control_old)){
                                    control_old = control_new;
                                    bg_color = before_color;

                                }else {
                                    if(before_color.trim().equals("white")){
                                        before_color = "blue";

                                    }else{
                                        before_color = "white";
                                    }
                                    control_old = control_new;
                                    bg_color = before_color;
                                }
                                Log.d(getString(R.string.tag), "bg_color: " + bg_color);
                                staging_list.add(new Staging_detail_list(
                                        String.valueOf(i+1),
                                        jArray.getJSONObject(i).getString("schedule_id"),
                                        jArray.getJSONObject(i).getString("dist").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("dist"),
                                        jArray.getJSONObject(i).getString("model_no").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("model_no"),
                                        jArray.getJSONObject(i).getString("model_type").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("model_type"),
                                        jArray.getJSONObject(i).getString("part_name"),
                                        jArray.getJSONObject(i).getString("item_no"),
                                        jArray.getJSONObject(i).getString("part_no"),
                                        jArray.getJSONObject(i).getString("control_no"),
                                        jArray.getJSONObject(i).getString("case_no"),
                                        jArray.getJSONObject(i).getString("part_color").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("part_color"),
                                        jArray.getJSONObject(i).getString("pc_no").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("pc_no"),
                                        jArray.getJSONObject(i).getString("line_no").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("line_no"),
                                        jArray.getJSONObject(i).getString("maker_code"),
                                        jArray.getJSONObject(i).getString("maker_name").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("maker_name"),
                                        jArray.getJSONObject(i).getString("receive_plan_qty").trim().equals("null") ? "0" : jArray.getJSONObject(i).getString("receive_plan_qty"),
                                        jArray.getJSONObject(i).getString("receive_act_qty").trim().equals("null") ? "0" : jArray.getJSONObject(i).getString("receive_act_qty"),
                                        jArray.getJSONObject(i).getString("staging_plan_qty").trim().equals("null") ? "0" : jArray.getJSONObject(i).getString("staging_plan_qty"),
                                        jArray.getJSONObject(i).getString("staging_act_qty").trim().equals("null") ? "0" : jArray.getJSONObject(i).getString("staging_act_qty"),
                                        staging_act_dt,
                                        jArray.getJSONObject(i).getString("staging_user_id").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("staging_user_id"),
                                        jArray.getJSONObject(i).getString("url_meiji_card").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("url_meiji_card"),
                                        jArray.getJSONObject(i).getString("url_packing_method").trim().equals("null") ? "" : jArray.getJSONObject(i).getString("url_packing_method"),
                                        jArray.getJSONObject(i).getString("status"),
                                        bg_color,
                                        jArray.getJSONObject(i).getString("case_packing_seq")));

                            }
                            String model_no = jArray.getJSONObject(0).getString("model_no").trim().equals("null") ? "" : jArray.getJSONObject(0).getString("model_no").trim();
                            Log.d(getString(R.string.tag), "model_no: " + model_no);
                            String dest = jArray.getJSONObject(0).getString("dist").trim().equals("null") ? "" : jArray.getJSONObject(0).getString("dist").trim();
                            Log.d(getString(R.string.tag), "dest: " + dest);
                            String pc_no = jArray.getJSONObject(0).getString("pc_no").trim().equals("null") ? "" : jArray.getJSONObject(0).getString("pc_no").trim();
                            Log.d(getString(R.string.tag), "pc_no: " + pc_no);
                            String model_type = jArray.getJSONObject(0).getString("model_type").trim().equals("null") ? "" : jArray.getJSONObject(0).getString("model_type").trim();
                            Log.d(getString(R.string.tag), "model_type: " + model_type);
                            String line_no = jArray.getJSONObject(0).getString("line_no").trim().equals("null") ? "" : jArray.getJSONObject(0).getString("line_no").trim();
                            Log.d(getString(R.string.tag), "line_no: " + line_no);
                            String outer_plan_date = jArray.getJSONObject(0).getString("outer_plan_date");
                            if (outer_plan_date.trim().equals("")||outer_plan_date.trim().equals("null")){
                                outer_plan_date = "";
                            }else {
                                JSONObject array_date = jArray.getJSONObject(0).getJSONObject("outer_plan_date");
                                outer_plan_date = array_date.getString("date");
                                outer_plan_date = outer_plan_date.substring(0,10);
                            }
                            Log.d(getString(R.string.tag), "outer_plan_date: " + outer_plan_date);
                            edt_model.setText(model_no);
                            txt_model.setText(model_no);
                            edt_dest.setText(dest);
                            txt_dest.setText(dest);
                            edt_pclot.setText(pc_no);
                            txt_pc_lot.setText(pc_no);
                            edt_model_type.setText(model_type);
                            txt_type.setText(model_type);
                            edt_packing_date.setText(outer_plan_date);
                            txt_packing.setText(outer_plan_date);
                            edt_packing_line.setText(line_no);
                            txt_packing_line.setText(line_no);
                            Log.d(getString(R.string.tag), "set text: completed" + outer_plan_date);
                            btn_search.setEnabled(false);
                            btn_search.setBackgroundResource(R.drawable.button_backgroup_gray);
                            Log.d(getString(R.string.tag), "set btn: completed" + outer_plan_date);
                        }
                        staging_adapter_detail = new Staging_Adapter_Detail(staging_list, Staging_Detail_Activity.this, Staging_Detail_Activity.this);
                        view_staging_detail.setAdapter(staging_adapter_detail);
                        Log.d(getString(R.string.tag), "set view");

                    } catch (JSONException e) {
                        new SweetAlertDialog(Staging_Detail_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        } catch (JSONException e) {
            new SweetAlertDialog(Staging_Detail_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

    @Override
//    public void onClickRow(String schedule_id, String url_meiji_card, String url_packing_method) {
    public void onClickRow(String pc_no, String control_no, String part_no, String part_color,
                           String url_meiji_card, String url_packing_method, String str_case_no,
                           String packing_no) {
//        str_schedule_id = schedule_id;
        str_pc_no = pc_no;
        str_control_no = control_no;
        str_part_no = part_no;
        str_part_color = part_color;
        str_url_meiji_card = url_meiji_card;
        str_url_packing_method = url_packing_method;
        Str_case_no = str_case_no;
        str_packing_no = packing_no;
        Log.d(getString(R.string.tag), "onClickRow : "+ str_url_meiji_card+"|"+ str_url_packing_method+"|");

        layout_staging_detail.setVisibility(View.GONE);
        Layout_choice_pdf.setVisibility(View.VISIBLE);


        if (!str_url_meiji_card.trim().equals("")){
            btn_meiji_card.setEnabled(true);
            btn_meiji_card.setBackgroundResource(R.drawable.button_backgroup_menu);

        }
        if (!str_url_packing_method.trim().equals("")){
            btn_packing.setEnabled(true);
            btn_packing.setBackgroundResource(R.drawable.button_backgroup_menu);
        }
    }

    @Override
    public void onMessage(WebSocket webSocket, String text) {
        Log.d(getString(R.string.tag), String.format("%s : received -> \"%s\"", this.getLocalClassName(),
                text));
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    JSONObject jsonObject = new JSONObject(text);
                    JSONObject j_ext;

                    switch (WsProtocol.COMMAND.valueOf(jsonObject.getString("cmd"))) {
//                        case DATA_REDRAW_REQUEST:
//                            spinner_status.setSelection(position);
//                            str_status = spinner_status.getSelectedItem().toString().trim();
//                            if (str_status.equals("All")) {
//                                str_status = "";
//                            }
//
//                            str_outer_plan_date = edt_packing_date.getText().toString().trim();
//                            Get_Schedule(str_status, str_outer_plan_date);
//
//                            break;

                        case STAGING_DATA_TABLE_DISPLAY_REQUEST:
                            if (isOpenPDF) {
                                finishActivity(pdf_content);
                            }
                            j_ext = new JSONObject(jsonObject.getString("ext"));
//                            String schedule_id = j_ext.getString("schedule_id");
//                            Log.d(getString(R.string.tag),"schedule_id"+schedule_id);

                            //model PPP --> show 1 case, other model --> shop all case
                            String control_no = j_ext.getString("control_no");
                            String pc_no = j_ext.getString("pc_no");
                            String case_no = j_ext.getString("case_no");
                            Get_Schedule_ID(pc_no, control_no, case_no);
                            break;


                        case HELLO:
                            j_ext = new JSONObject(jsonObject.getString("ext"));
                            WsClient.getInstance().client_id = j_ext.getInt("id");

                            j_ext = new JSONObject();
                            j_ext.put("device_id", Settings.getDeviceNo());
                            j_ext.put("user_id", Settings.getLoginUser().getId());
                            j_ext.put("device_type", getString(R.string.device_type));
                            j_ext.put("pair_id", Settings.getDeviceHT().getDevice_id());
                            j_ext.put("pair_dev_type", getString(R.string.pair_dev_type));
                            WsClient.getInstance().sendMessage(
                                    WsProtocol.encapsulation(
                                            WsProtocol.COMMAND.REGISTER_REQUEST.toString(),
                                            j_ext
                                    )
                            );
                            break;

                        case AREA_CHANGE_NOTIFY_REQUEST:
                            Log.d(getString(R.string.tag), "cmd : AREA_CHANGE_NOTIFY_REQUEST");

                            j_ext = new JSONObject(jsonObject.getString("ext"));
                            String user_id = j_ext.getString("user_id");
                            String device_id = j_ext.getString("device_id");
                            String device_type = j_ext.getString("device_type");
                            String str_stage = j_ext.getString("area");
                            Log.d(getString(R.string.tag), "AREA_CHANGE :" + user_id + "|" + device_id + "|" + device_type + "|" + str_stage);

                            Settings.setArea_stage(str_stage);

                            WsClient.getInstance().sendMessage(
                                    WsProtocol.encapsulation(
                                            WsProtocol.COMMAND.AREA_CHANGE_NOTIFY_ACK.toString(),
                                            j_ext
                                    )
                            );
                            if (!str_stage.equals("STAGING") ) {

                                Intent resultIntent = new Intent();
                                setResult(Activity.RESULT_OK, resultIntent);
                                finish();
                            }

                            break;

                        case MEIJI_CARD_DISPLAY_REQUEST:
                            Log.d(getString(R.string.tag), "cmd : MEIJI_CARD_DISPLAY_REQUEST");

                            j_ext = new JSONObject(jsonObject.getString("ext"));
                            str_url_meiji_card = j_ext.getString("url_meiji_card");
//                            str_schedule_id = j_ext.getString("schedule_id");
                            str_pc_no = j_ext.getString("pc_no");
                            str_control_no = j_ext.getString("control_no");
                            str_part_no = j_ext.getString("part_no");
                            str_part_color = j_ext.getString("part_color");
                            Str_case_no = j_ext.getString("case_no");
                            str_packing_no = j_ext.getString("packing_no");

                            Log.d(getString(R.string.tag), "url_meiji_card : " + str_url_meiji_card);
//                            Log.d(getString(R.string.tag), "schedule_id : " + str_schedule_id);

                            str_url_meiji_card = str_url_meiji_card.replace("'\'","");
                            String[] tokens = str_url_meiji_card.split("/");
                            if (tokens.length == 5) {
                                str_url_meiji_card = tokens[4].toString();

                                try {
                                    WsClient.getInstance().sendMessage(
                                            WsProtocol.encapsulation(
                                                    WsProtocol.COMMAND.MEIJI_CARD_DISPLAY_ACK.toString(),
                                                    null
                                            )
                                    );

                                } catch (JSONException e) {
                                    new SweetAlertDialog(Staging_Detail_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                            .setTitleText("ERROR")
                                            .setContentText(e.getMessage())
                                            .show();

                                } catch (Exception e) {
                                    new SweetAlertDialog(Staging_Detail_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                            .setTitleText("ERROR")
                                            .setContentText(e.getMessage())
                                            .show();
                                }

                                Log.d(getString(R.string.tag), "path_pdf1 : " + str_url_meiji_card);

                                String url_pdf = Settings.getMgmtList().get("web_api") + "/res/MeijiCard/" + str_url_meiji_card;
                                Log.d(getString(R.string.tag), "path_pdf : " + url_pdf);

                                if (isOpenPDF) {
                                    finishActivity(pdf_content);
                                }

                                intent_pdf = new Intent();
                                intent_pdf.setDataAndType(Uri.parse(url_pdf), "application/pdf");
                                startActivityForResult(intent_pdf, pdf_content);
                                isOpenPDF = true;

                                //send even log
                                j_ext = new JSONObject();
                                j_ext.put("user_id", Settings.getLoginUser().getId());
                                j_ext.put("device_id", Settings.getDeviceNo());
                                j_ext.put("device_type", getString(R.string.device_type));
//                                j_ext.put("job_id", str_job_id);
                                j_ext.put("event", WsProtocol.EVENT.TB_STAGING_MONITOR_MEIJI_CARD_SUCCESS);
                                j_ext.put("status", ProductionSchedule.STATUS.WORKING);
                                j_ext.put("stage", ProductionSchedule.STAGE.STAGING);
//                                j_ext.put("schedule_id", str_schedule_id);
                                j_ext.put("pc_no", str_pc_no);
                                j_ext.put("control_no", str_control_no);
                                j_ext.put("part_no", str_part_no);
                                j_ext.put("part_color", str_part_color);
                                j_ext.put("case_no", Str_case_no);
                                j_ext.put("packing_no", str_packing_no);
                                WsClient.getInstance().sendMessage(
                                        WsProtocol.encapsulation(
                                                WsProtocol.COMMAND.EVENT_LOG_REQUEST.toString(),
                                                j_ext
                                        )
                                );
                            }else {
                                new SweetAlertDialog(Staging_Detail_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                        .setTitleText("WARNING")
                                        .setContentText("Meiji card file not found!")
                                        .show();
                            }

                            break;

                        case RESET_ACK:

                            break;
                    }
                } catch (JSONException e) {
                    new SweetAlertDialog(Staging_Detail_Activity.this, SweetAlertDialog.ERROR_TYPE)
                            .setTitleText("ERROR")
                            .setContentText(e.getMessage())
                            .show();
                } catch (Exception e) {
                    if (e.getMessage().trim().equals("The server might crash")){
                        WsClient.getInstance().connect();
                    }
                }
            }
        });
    }

    @Override
    public void onFinished(String result) {

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.d("onActivityResult3", String.valueOf(requestCode+"|"+resultCode));
        if (resultCode == Activity.RESULT_OK){
            finish();
        }

    }
}