package com.tomastc.bta500;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewParent;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
import android.widget.Toast;

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 com.keyence.autoid.sdk.scan.DecodeResult;
import com.tomastc.bta500.lib.ActionListenerCallback;
import com.tomastc.bta500.lib.CompletionInput;
import com.tomastc.bta500.lib.KeyMapping;
import com.tomastc.bta500.lib.Scanner;
import com.tomastc.bta500.lib.ScheduleQRCode;
import com.tomastc.bta500.lib.SerialNo;
import com.tomastc.bta500.lib.Settings;
import com.tomastc.bta500.lib.SpinAdapter;
import com.tomastc.bta500.lib.SpinAdapter_UserLogin;
import com.tomastc.bta500.lib.UserInfo;
import com.tomastc.bta500.lib.UserLogin_list;
import com.tomastc.bta500.lib.WorkShopNo;
import com.tomastc.bta500.lib.common.AsyncTcpClient;
import com.tomastc.bta500.lib.common.DatetimeUtil;
import com.tomastc.bta500.lib.common.AsyncHttpClient;
import com.tomastc.bta500.lib.common.MyAlertDialog;
import com.tomastc.bta500.lib.common.Utils;

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

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

final public class CompletionActivity extends Scanner {

    private Button btn_reprint, btn_delete, btn_label, btn_cancel;
    private EditText txt_item_code, txt_fg_item_code, txt_target_qty, txt_total_qty_ok, txt_total_qty_ng, txt_box_qty_ok, txt_box_qty_ng;
    private TextView lbl_shift_code, lbl_work_shop_no, lbl_title, txt_item_name;

    private ScheduleQRCode scheduleQRCode;
    private SpinAdapter_UserLogin workshopNoArrayAdapter;

    private int scan_step = 0, position_ws = 0;
    private String current_slip_code = "";
    private static int __MIN_INTERVAL_TIME = 30;
    private Spinner spinner_ws;
    ConstraintLayout layout_Outstanding;
    RecyclerView view_Outstanding;
    Button btn_close;
    List<Outstanding_List> list_out;
    Outstanding_Adapter outstanding_adapter;


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

        default_view = (EditText) findViewById(R.id.txt_label_issue_tmp);
        layout_Outstanding = (ConstraintLayout)findViewById(R.id.layout_Outstanding);
        list_out = new ArrayList<Outstanding_List>();

        // Button
        btn_reprint = (Button) findViewById(R.id.btn_reprint);
        btn_delete = (Button) findViewById(R.id.btn_delete);
        btn_label = (Button) findViewById(R.id.btn_label);
        btn_cancel = (Button) findViewById(R.id.btn_cancel);
        btn_close = (Button) findViewById(R.id.btn_close);

        txt_item_code = (EditText) findViewById(R.id.txt_item_code);
        txt_item_name = (EditText)findViewById(R.id.txt_item_name);
        txt_fg_item_code = (EditText) findViewById(R.id.txt_fg_item_code);
        txt_target_qty = (EditText) findViewById(R.id.txt_target_qty);
        txt_total_qty_ok = (EditText) findViewById(R.id.txt_total_qty_ok);
        txt_total_qty_ng = (EditText) findViewById(R.id.txt_total_qty_ng);
        txt_box_qty_ok = (EditText) findViewById(R.id.txt_box_qty_ok);
        txt_box_qty_ng = (EditText) findViewById(R.id.txt_box_qty_ng);

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


        lbl_shift_code = (TextView) findViewById(R.id.lbl_shift_code);
//        lbl_work_shop_no = (TextView) findViewById(R.id.lbl_work_shop_no);
        lbl_shift_code.setText("Shift code : " + Settings.getShiftCode().getId());
//        lbl_work_shop_no.setText("Work shop no : " + Settings.getWorkShopNo().getId());

        lbl_title = (TextView) findViewById(R.id.label_title);

        if (Settings.getWorkMode()== Settings.WorkMode.COMPLETION) {
            lbl_title.setText("Completion");
            txt_box_qty_ng.setBackgroundColor(getColor(R.color.silver));
            txt_box_qty_ng.setEnabled(false);
        } else {
            lbl_title.setText("NG Label");
            txt_box_qty_ok.setBackgroundColor(getColor(R.color.silver));
            txt_box_qty_ok.setEnabled(false);
        }

        spinner_ws = (Spinner)findViewById(R.id.spiner_ws);

        UserLogin_list[] userLogin_lists = new UserLogin_list[Settings.getUserLogin_list().size()];
        for (int i = 0; i < Settings.getUserLogin_list().size(); i++){

            String user_id = Settings.getUserLogin_list().get(i).getUser_id();
            String user_name = Settings.getUserLogin_list().get(i).getUser_name();
            String shift = Settings.getUserLogin_list().get(i).getShift();
            String ws_cd = Settings.getUserLogin_list().get(i).getWs_cd();
            String ws_no = Settings.getUserLogin_list().get(i).getWs_no();
            String mc_line_no = Settings.getUserLogin_list().get(i).getMc_line_no();
            String ws_desc = Settings.getUserLogin_list().get(i).getWs_desc();
            String upd_date = Settings.getUserLogin_list().get(i).getUpd_date();
            String upd_user_id = Settings.getUserLogin_list().get(i).getUpd_user_id();
            String print_preset = Settings.getUserLogin_list().get(i).getPrint_preset();

            userLogin_lists[i] = new UserLogin_list(user_id, user_name, shift, ws_cd, ws_no, mc_line_no, ws_desc,upd_date, upd_user_id ,print_preset);

        }
        workshopNoArrayAdapter = new SpinAdapter_UserLogin(
                getApplicationContext(), R.layout.spinner_usr_list,userLogin_lists);
        spinner_ws.setAdapter(workshopNoArrayAdapter);

        spinner_ws.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                position_ws = position;
                Log.d(getString(R.string.tag), "onItemSelected: " + position_ws);
                Log.d(getString(R.string.tag), Settings.getUserLogin_list().get(position_ws).getUser_id()
                        + "|" + Settings.getUserLogin_list().get(position_ws).getUser_name()
                        + "|" + Settings.getUserLogin_list().get(position_ws).getWs_no());

                resetForm();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

//        spinner_ws.setSelection(position_ws);

        Log.d(getString(R.string.tag), Settings.getUserLogin_list().get(position_ws).getUser_id() + "|" + Settings.getUserLogin_list().get(position_ws).getWs_no());
        Log.d(getString(R.string.tag), "position_ws_create: " + position_ws);

        // Set default
        resetForm();


        // Event
        txt_box_qty_ok.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//                try {
//                    if (txt_box_qty_ok.getText().toString().isEmpty())
//                        return;
//
//                    Log.d(getString(R.string.tag), charSequence.toString());
//                    Log.d(getString(R.string.tag), txt_box_qty_ok.getText().toString());
//
//                    int target_qty = Integer.parseInt(txt_target_qty.getText().toString());
//                    int current_qty = Integer.parseInt(txt_total_qty_ok.getText().toString())
//                            + Integer.parseInt(txt_box_qty_ok.getText().toString());
//                    if (current_qty > target_qty) {
//                        Toast.makeText(getApplicationContext(), "The Qty amount is exceed the target Qty!"
//                                , Toast.LENGTH_LONG).show();
//                    }
//
//                    Utils.hideKeyboardFrom(getApplicationContext(), default_view);
//                } catch (Exception e) {
//                    Log.e(getString(R.string.tag), e.getMessage());
//                }

            }

            @Override
            public void afterTextChanged(Editable editable) {

            }
        });

        btn_label.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // Check click by customize button P2
                if (!btn_label.isEnabled())
                    return;

                // Disable button
                btn_label.setEnabled(false);

                // Flow lock *remark supported print service lock version 1.2.4 #updated 2022-03-07
                // Check status of slip, validation and Item no matched
                try {
                    // send JSON request
                    JSONObject json = new JSONObject();
                    json.put("cmd", "get-last-slip-status");
                    json.put("ws_cd", scheduleQRCode.getElements().get("ws_cd"));
                    json.put("item_no", scheduleQRCode.getElements().get("item_no"));
                    json.put("doc_no", scheduleQRCode.getDocumentNo());

                    new AsyncHttpClient(getApplicationContext()
                            ,Settings.getMgmtList().get("web_api") + "/nst_compl_input.php"
                            , json.toString()
                    ) {
                        @Override
                        public void onFinished(String response, int resp_code) {
                            String err_msg = "Server connection failed!\nPlease contact leader.";
                            Boolean isWaitingForMatch = false;
                            CompletionInput.Status status = CompletionInput.Status.CANCEL;
                            CompletionInput.JoinTableFlag joinTableFlag = null;
                            Log.d(getString(R.string.tag), "response: " + response);
                            try {
                                JSONArray jsonArray = new JSONArray(response);
                                if (jsonArray.length() != 0) {
                                    try {
                                        // send JSON request
                                        JSONObject json = jsonArray.getJSONObject(0);
                                        status = CompletionInput.Status.fromId(
                                                Integer.parseInt(json.getString("Doc_Status"))
                                        );
                                        joinTableFlag = CompletionInput.JoinTableFlag.fromId(
                                                Integer.parseInt(json.getString("JON_TBL_FLAG"))
                                        );
                                        if (status == CompletionInput.Status.OK
                                                && joinTableFlag == CompletionInput.JoinTableFlag.NEW) {
                                            throw new Exception(String.format("Please match previous slip! Slip no. %s", json.getString("SLIP_NO")));
                                        } else if (Integer.parseInt(json.getString("time_in_sec")) < __MIN_INTERVAL_TIME) {
                                            throw new Exception("You're doing it wrong process !");
                                        }
                                    } catch (Exception e) {
                                        throw e;
                                    }
                                }
                                Check_pre_print();
                            } catch (Exception e) {

                                alertError(e.getMessage(),
                                        new ActionListenerCallback() {

                                            @Override
                                            public void onActionSuccess(String successMessage) {
                                            }

                                            @Override
                                            public void onActionFailure(Throwable throwableError) {

                                            }
                                        }
                                );
                                Log.e(getString(R.string.tag), "ERROR: " + e.getMessage());
                                btn_label.setEnabled(true);
                            }
                        }

                        @Override
                        protected void onError(Exception e) {

                        }
                    }.execute();

                } catch (Exception e) {

                    alertError(e.getMessage(),
                            new ActionListenerCallback() {

                                @Override
                                public void onActionSuccess(String successMessage) {
                                }

                                @Override
                                public void onActionFailure(Throwable throwableError) {

                                }
                            }
                    );
                    Log.e(getString(R.string.tag), "ERROR: " + e.getMessage());
                    btn_label.setEnabled(true);
                }


            }
        });
        btn_reprint.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showReprintDialog();
            }
        });
        btn_delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                showDeleteDialog();
            }
        });
        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // stop activity
                finish();
            }
        });

        btn_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                layout_Outstanding.setVisibility(View.GONE);
            }
        });


        default_view.requestFocus();

    }



    private void confirmation(String msg, int color, boolean isBtnOkShow, ActionListenerCallback callback) {
        RelativeLayout layout = (RelativeLayout) findViewById(R.id.popupLayout1);
        TextView lbl_msg = (TextView) findViewById(R.id.popupLayout1_txt);
        Button btnOk = (Button) findViewById(R.id.popupLayout1_btn1);
        Button btnCancel = (Button) findViewById(R.id.popupLayout1_btn2);

        lbl_msg.setText(msg);
        lbl_msg.setTextColor(color);
        btnOk.setVisibility(isBtnOkShow ? View.VISIBLE : View.INVISIBLE);
        layout.setVisibility(RelativeLayout.VISIBLE);
        btnOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    ((View) view.getParent().getParent()).setVisibility(View.GONE);
                    callback.onActionSuccess("");
                } catch (Exception e) {
                    // In case if item is the top most view
                };
            }
        });
        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    ((View) view.getParent().getParent()).setVisibility(View.GONE);
                    callback.onActionFailure(null);
                } catch (ClassCastException e) {
                    // In case if item is the top most view
                };
            }
        });

    }

    private void alertOk(String msg, ActionListenerCallback callback) {
        // Enable the ENT key down, it must current focus on multiline text input
        default_view.requestFocus();

        RelativeLayout layout = (RelativeLayout) findViewById(R.id.popupLayout2);
        TextView lbl_msg = (TextView) findViewById(R.id.popupLayout2_txt);
        Button btn = (Button) findViewById(R.id.popupLayout2_btn1);

        lbl_msg.setText(msg);
        lbl_msg.setTextColor(getColor(R.color.black));
        layout.setVisibility(RelativeLayout.VISIBLE);
        btn.setBackgroundColor(getColor(R.color.green));
        btn.setTextColor(getColor(R.color.white));
        btn.setText("OK [ENT]");
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // stop activity
                try {
                    ((View) view.getParent().getParent()).setVisibility(View.GONE);
                    callback.onActionSuccess("");
                } catch (Exception e) {
                    // In case if item is the top most view
                };
            }
        });

    }

    private void alertError(String msg, ActionListenerCallback callback) {
        // Enable the ENT key down, it must current focus on multiline text input
        default_view.requestFocus();

        RelativeLayout layout = (RelativeLayout) findViewById(R.id.popupLayout2);
        TextView lbl_msg = (TextView) findViewById(R.id.popupLayout2_txt);
        Button btn = (Button) findViewById(R.id.popupLayout2_btn1);

        lbl_msg.setText(msg);
        lbl_msg.setTextColor(getColor(R.color.red));
        layout.setVisibility(RelativeLayout.VISIBLE);
        btn.setBackgroundColor(getColor(R.color.red));
        btn.setTextColor(getColor(R.color.white));
        btn.setText("NG [ENT]");
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // stop activity
                try {
                    ((View) view.getParent().getParent()).setVisibility(View.GONE);
                    callback.onActionSuccess("");
                } catch (Exception e) {
                    // In case if item is the top most view
                };
            }
        });

    }

    private void showReprintDialog() {
        RelativeLayout layout = (RelativeLayout) findViewById(R.id.reprintLayout);
        EditText txt_serial_no = (EditText) findViewById(R.id.txt_reprint_serial_no);
        TextView lbl_msg = (TextView) findViewById(R.id.txt_reprint_error);
        Button btn_ok = (Button) findViewById(R.id.reprintLayout_btn1);
        Button btn_cancel = (Button) findViewById(R.id.reprintLayout_btn2);

        lbl_msg.setText("");
        txt_serial_no.setText("");
        txt_serial_no.requestFocus();
        layout.setVisibility(RelativeLayout.VISIBLE);
        btn_ok.setEnabled(true);
        txt_serial_no.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (!b) { // lost focus
                    Utils.hideKeyboardFrom(getApplicationContext(), default_view);
                }
            }
        });
        btn_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // stop activity
                if (!btn_ok.isEnabled())
                    return;

                btn_ok.setEnabled(false);

                try {
                    if (txt_serial_no.getText().toString().trim().isEmpty()) {
                        lbl_msg.setText("No Serial no.");
//                    } else if (txt_serial_no.getText().toString().length() != 10) {
//                        lbl_msg.setText("Reprint Serial no 10digit.");
                    } else {
                        try {
                            // send JSON request
                            JSONObject json = new JSONObject();
                            json.put("cmd", "reprint");
                            json.put("slip_cd", txt_serial_no.getText().toString().trim());

                            new AsyncHttpClient(getApplicationContext()
                                    ,Settings.getMgmtList().get("web_api") + "/nst_compl_input.php"
                                    , json.toString()
                            ) {
                                @SuppressLint("StaticFieldLeak")
                                @Override
                                public void onFinished(String response, int resp_code) {
                                    String err_msg = "";
                                    Log.d(getString(R.string.tag), "response: " + response);
                                    try {
                                        err_msg = "Server connection failed!\nPlease contact leader.";
                                        JSONObject jsonObject = new JSONObject(response);
                                        if (jsonObject.getString("affected_rows").equals("1")) {

                                            // Send data to printer controller
                                            String payload = String.format(
                                                    "%s %s%s\r\n%s%s"
                                                    , "PST"
                                                    , jsonObject.getJSONObject("slip_detail").getString("preset")
                                                    , ( jsonObject.getJSONObject("slip_detail").getString("ng").trim()
                                                            .equals("1") ? "-NG" : "")
                                                    , "\"R\""
                                                    , jsonObject.getJSONObject("slip_detail").getString("payload")
                                            );
                                            new AsyncTcpClient(getApplicationContext(),
                                                    Settings.getMgmtList().get("printer_server_ip"),
                                                    Integer.parseInt(Settings.getMgmtList().get("printer_server_port")),
                                                    payload
                                            ) {
                                                @Override
                                                protected void onFinished(String response) {
                                                    Log.d(getString(R.string.tag), "TCP response: " + response);

                                                    if (response.equals("OK")) {
                                                        layout.setVisibility(RelativeLayout.GONE);
                                                        alertOk("Reprint OK.", new ActionListenerCallback() {
                                                            @Override
                                                            public void onActionSuccess(String successMessage) {
                                                            }

                                                            @Override
                                                            public void onActionFailure(Throwable throwableError) {

                                                            }
                                                        });
                                                    } else {

                                                        alertError("Can not connect to print server!",
                                                                new ActionListenerCallback() {

                                                                    @Override
                                                                    public void onActionSuccess(String successMessage) {
                                                                    }

                                                                    @Override
                                                                    public void onActionFailure(Throwable throwableError) {

                                                                    }
                                                                }
                                                        );
                                                    }
                                                    btn_ok.setEnabled(true);
                                                }
                                            }.execute();

                                        } else {
                                            err_msg = "Slip code not found!";
                                            throw new JSONException(err_msg);
                                        }
                                    } catch (JSONException e) {
                                        alertError(err_msg,
                                                new ActionListenerCallback() {

                                                    @Override
                                                    public void onActionSuccess(String successMessage) {
                                                    }

                                                    @Override
                                                    public void onActionFailure(Throwable throwableError) {

                                                    }
                                                }
                                        );
                                        Log.e(getString(R.string.tag), "ERROR: " + e.getMessage());
                                        btn_ok.setEnabled(true);
                                    }
                                }

                                @Override
                                protected void onError(Exception e) {

                                }
                            }
                                    .execute();

                        } catch (Exception e) {
                            Log.e(getString(R.string.tag), e.getMessage());
                            throw e;
                        }
                    }
                } catch (Exception e) {
                    btn_ok.setEnabled(true);
                };
            }
        });
        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // stop activity
                try {
                    ((View) view.getParent().getParent()).setVisibility(View.GONE);
                } catch (ClassCastException e) {
                    // In case if item is the top most view
                };
            }
        });
    }

    private void showDeleteDialog() {
        RelativeLayout layout = (RelativeLayout) findViewById(R.id.deleteLayout);
        EditText txt_serial_no = (EditText) findViewById(R.id.txt_delete_serial_no);
        TextView lbl_msg = (TextView) findViewById(R.id.txt_delete_error);
        Button btn_ok = (Button) findViewById(R.id.deleteLayout_btn1);
        Button btn_cancel = (Button) findViewById(R.id.deleteLayout_btn2);

        lbl_msg.setText("");
        txt_serial_no.setText("");
        txt_serial_no.requestFocus();
        btn_ok.setEnabled(true);
        layout.setVisibility(RelativeLayout.VISIBLE);
        txt_serial_no.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View view, boolean b) {
                if (!b) { // lost focus
                    Utils.hideKeyboardFrom(getApplicationContext(), default_view);
                }
            }
        });
        btn_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // stop activity
                if (!btn_ok.isEnabled())
                    return;

                btn_ok.setEnabled(false);

                try {
                    if (txt_serial_no.getText().toString().trim().isEmpty()) {
                        lbl_msg.setText("No Serial no.");
//                    } else if (txt_serial_no.getText().toString().length() != 10) {
//                        lbl_msg.setText("Delete Serial no 10digit.");
                    } else {
                        delete_slip();
                        try {
                            // send JSON request
                            JSONObject json = new JSONObject();
                            json.put("cmd", "search");
                            json.put("slip_cd", txt_serial_no.getText().toString().trim());

                            new AsyncHttpClient(getApplicationContext()
                                    ,Settings.getMgmtList().get("web_api") + "/nst_slip_detail.php"
                                    , json.toString()
                            ) {
                                @Override
                                public void onFinished(String response, int resp_code) {
                                    String err_msg = "";
                                    Log.d(getString(R.string.tag), "response: " + response);
                                    try {
                                        err_msg = "Server connection failed!\nPlease contact leader.";
                                        JSONArray jsonArray = new JSONArray(response);
                                        Log.d(getString(R.string.tag), "response: " + response);
                                        if (jsonArray.length() != 0) {
                                            try {
                                                // send JSON request
                                                JSONObject json = new JSONObject();
                                                json.put("cmd", "delete");
                                                json.put("slip_cd", txt_serial_no.getText().toString().trim());

                                                new AsyncHttpClient(getApplicationContext()
                                                        ,Settings.getMgmtList().get("web_api") + "/nst_compl_input.php"
                                                        , json.toString()
                                                ) {
                                                    @Override
                                                    public void onFinished(String response, int resp_code) {
                                                        String err_msg = "";
                                                        Log.d(getString(R.string.tag), "response: " + response);
                                                        try {
                                                            err_msg = "Server connection failed!\nPlease contact leader.";
                                                            JSONObject jsonObject = new JSONObject(response);
                                                            if (jsonObject.getString("status").equalsIgnoreCase("success")) {

//                                                                Toast.makeText(getApplicationContext(), "Label deleted"
//                                                                        , Toast.LENGTH_LONG).show();
//
//                                                                layout.setVisibility(RelativeLayout.GONE);
//                                                                alertOk("Delete OK.", new ActionListenerCallback() {
//                                                                    @Override
//                                                                    public void onActionSuccess(String successMessage) {
//                                                                    }
//
//                                                                    @Override
//                                                                    public void onActionFailure(Throwable throwableError) {
//
//                                                                    }
//                                                                });
                                                                //add 27/10/23 delete slip Restore ACTUAL_USAGE
                                                                try {
                                                                    // send JSON request
                                                                    JSONObject json = new JSONObject();
                                                                    json.put("cmd", "delete");
                                                                    json.put("slip_cd", txt_serial_no.getText().toString().trim());

                                                                    new AsyncHttpClient(getApplicationContext()
                                                                            ,Settings.getMgmtList().get("web_api") + "/nst_compo_detail.php"
                                                                            , json.toString()
                                                                    ) {
                                                                        @Override
                                                                        public void onFinished(String response, int resp_code) {
                                                                            String err_msg = "";
                                                                            Log.d(getString(R.string.tag), "response: " + response);
                                                                            try {
                                                                                err_msg = "Server connection failed!\nPlease contact leader.";
                                                                                JSONObject jsonObject = new JSONObject(response);
                                                                                String status = jsonObject.getString("status");
                                                                                int affected_rows = jsonObject.getInt("affected_rows");
//
                                                                                if (status.equals("success") && affected_rows > 0) {

                                                                                    Toast.makeText(getApplicationContext(), "Label deleted"
                                                                                    , Toast.LENGTH_LONG).show();

                                                                                    layout.setVisibility(RelativeLayout.GONE);
                                                                                    alertOk("Delete OK.", new ActionListenerCallback() {
                                                                                        @Override
                                                                                            public void onActionSuccess(String successMessage) {
                                                                                        }

                                                                                        @Override
                                                                                            public void onActionFailure(Throwable throwableError) {

                                                                                        }
                                                                                     });

                                                                                } else {
                                                                                    throw new JSONException("Update ACTUAL_USAGE Error! \n Please contact leader.");
                                                                                }
                                                                            } catch (JSONException e) {
                                                                                alertError(err_msg,
                                                                                        new ActionListenerCallback() {

                                                                                            @Override
                                                                                            public void onActionSuccess(String successMessage) {
                                                                                            }

                                                                                            @Override
                                                                                            public void onActionFailure(Throwable throwableError) {

                                                                                            }
                                                                                        }
                                                                                );
                                                                                Log.e(getString(R.string.tag), "ERROR: " + e.getMessage());
                                                                            } finally {
                                                                                btn_ok.setEnabled(true);
                                                                            }
                                                                        }
                                                                        @Override
                                                                        protected void onError(Exception e) {

                                                                        }
                                                                    }
                                                                            .execute();

                                                                } catch (Exception e) {
                                                                    Log.e(getString(R.string.tag), e.getMessage());
                                                                    throw e;
                                                                }
                                                            } else {
                                                                throw new JSONException(err_msg);
                                                            }
                                                        } catch (JSONException e) {
                                                            alertError(err_msg,
                                                                    new ActionListenerCallback() {

                                                                        @Override
                                                                        public void onActionSuccess(String successMessage) {
                                                                        }

                                                                        @Override
                                                                        public void onActionFailure(Throwable throwableError) {

                                                                        }
                                                                    }
                                                            );
                                                            Log.e(getString(R.string.tag), "ERROR: " + e.getMessage());
                                                        } finally {
                                                            btn_ok.setEnabled(true);
                                                        }
                                                    }

                                                    @Override
                                                    protected void onError(Exception e) {

                                                    }
                                                }
                                                        .execute();

                                            } catch (Exception e) {
                                                Log.e(getString(R.string.tag), e.getMessage());
                                                throw e;
                                            }
                                        } else {
                                            err_msg = "Slip code not found!";
                                            throw new JSONException(err_msg);
                                        }
                                    } catch (JSONException e) {
                                        alertError(err_msg,
                                                new ActionListenerCallback() {

                                                    @Override
                                                    public void onActionSuccess(String successMessage) {
                                                    }

                                                    @Override
                                                    public void onActionFailure(Throwable throwableError) {

                                                    }
                                                }
                                        );
                                        Log.e(getString(R.string.tag), "ERROR: " + e.getMessage());
                                        btn_ok.setEnabled(true);
                                    }
                                }

                                @Override
                                protected void onError(Exception e) {

                                }
                            }
                                    .execute();

                        } catch (Exception e) {
                            throw e;
                        }
                    }
                } catch (Exception e) {
                    // In case if item is the top most view
                    Log.e(getString(R.string.tag), e.getMessage());
                    btn_ok.setEnabled(true);
                };
            }
        });
        btn_cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // stop activity
                try {
                    ((View) view.getParent().getParent()).setVisibility(View.GONE);
                } catch (ClassCastException e) {
                    // In case if item is the top most view
                };
            }
        });
    }

    private void delete_slip() {
    }

    private void resetForm() {
        scan_step = 0;

        txt_item_code.setText("");
        txt_item_name.setText("");
        txt_fg_item_code.setText("");
        txt_target_qty.setText("");
        txt_total_qty_ok.setText("0");
        txt_total_qty_ng.setText("0");
        if (Settings.getWorkMode() == Settings.WorkMode.COMPLETION) {
            txt_box_qty_ok.setText("0");
            txt_box_qty_ng.setText("-");
        } else {
            txt_box_qty_ok.setText("-");
            txt_box_qty_ng.setText("0");
        }

        btn_label.setEnabled(false);

        scheduleQRCode = null;
    }

    public void processData(String data, DecodeResult.Result result, String codeType) {

        try {
            final String[] err_msg = {"Process error! Please contact leader."};

            Log.d(getString(R.string.tag), "data read:" + data);

            String[] tokens = data.split(getString(R.string.DELIMITER_SCAN_TOKEN));
            Log.d(getString(R.string.tag), Arrays.deepToString(tokens));

            switch (scan_step) {
                case 0:
                    if (tokens.length == 1) {
                        UserLogin_list userLogin_list = (UserLogin_list) workshopNoArrayAdapter.findItem(data);
                        if (userLogin_list != null) {
                            position_ws = workshopNoArrayAdapter.getPosition(userLogin_list);
                            Log.d(getString(R.string.tag), "workShopNo list index:" + position_ws);
                            spinner_ws.setSelection(position_ws);

                            Log.d(getString(R.string.tag), Settings.getUserLogin_list().get(position_ws).getUser_id()
                                    + "|" + Settings.getUserLogin_list().get(position_ws).getUser_name()
                                    + "|" + Settings.getUserLogin_list().get(position_ws).getWs_no());

                            resetForm();

                        } else {
                            Toast.makeText(getApplicationContext(), "Work shop no[" + data + "] not found!",
                                    Toast.LENGTH_LONG).show();
                        }
                    }else if (tokens.length==11) {
                        /*
                     QR Contents
                        • Production Date
                        • Work Shop Code
                        • Work Shop No
                        • Work Shop 2d Code
                        • Sequence Code
                        • Item code
                        • Item Description --> item  name?
                        • Production Quantity = qty
                        • Parent Item code
                        • Parent Item Description
                        • Completion Lot (qty)
                     */

                        // Matching the QRCode job with the login information
                        if (!Settings.getUserLogin_list().get(position_ws).getWs_cd().equalsIgnoreCase(tokens[1])
                                || !Settings.getUserLogin_list().get(position_ws).getWs_no().equalsIgnoreCase(tokens[2])
                        ) {
                            err_msg[0] = "Job isn't matched!\nPlease contact leader.";
                            Log.e(getString(R.string.tag), err_msg[0]);
                            alertError(err_msg[0],
                                    new ActionListenerCallback() {

                                        @Override
                                        public void onActionSuccess(String successMessage) {
                                            resetForm();
                                        }

                                        @Override
                                        public void onActionFailure(Throwable throwableError) {

                                        }
                                    }
                            );
                        } else {

                            // Keep schedule QRCode scan data
                            scheduleQRCode = new ScheduleQRCode(data, getString(R.string.DELIMITER_SCAN_TOKEN));

                            txt_item_code.setText(tokens[5]);
                            txt_item_name.setText(tokens[6]);
                            txt_fg_item_code.setText(tokens[8]);

                            txt_target_qty.setText(
                                    // Remove the decimal point
                                    //tokens[7]
                                    String.valueOf((int)Float.parseFloat(tokens[7]))
                            );
                            if (Settings.getWorkMode().equals(Settings.WorkMode.COMPLETION))
                                txt_box_qty_ok.setText(
                                        // Remove the decimal point
                                        //tokens[10]
                                        String.valueOf((int)Float.parseFloat(tokens[10]))
                                );

                            // get saved item from server
                            JSONObject json = new JSONObject();
                            json.put("cmd", "scan");
                            json.put("prod_date", tokens[0]);
                            json.put("ws_cd", tokens[1]);
                            json.put("ws_no", tokens[2]);
                            json.put("ws_2d", tokens[3]);
                            json.put("seq_cd", tokens[4]);
                            json.put("item_no", tokens[5]);
                            json.put("parenti_no", tokens[8]);
//                            json.put("scan_user", Settings.getUserInfoX().getId());
                            json.put("scan_user", Settings.getUserLogin_list().get(position_ws).getUser_id());
                            json.put("scan_date", DatetimeUtil.getDateTime("yyyy-MM-dd HH:mm:ss"));
                            json.put("upd_pgm", getString(R.string.prog_name));
                            json.put("shift", Settings.getShiftCode().getId());

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

                                    // Keep response data such as status, step_status, doc_no and serial_no
                                    try {
                                        err_msg[0] = "No data found!\nPlease contact leader.";
                                        JSONObject jsonObject = new JSONObject(response);
                                        scheduleQRCode.setDocumentNo(jsonObject.getString("doc_no"));
                                        scheduleQRCode.setStatus(ScheduleQRCode.ScheduleStatus.fromId(jsonObject.getInt("status")));
                                        scheduleQRCode.setStepStatus(ScheduleQRCode.ScheduleStepStatus.fromId(jsonObject.getInt("step_status")));
                                        scheduleQRCode.setTotalQty(jsonObject.getString("total_qty"));

                                        txt_total_qty_ok.setText(
                                                // Remove the decimal point
                                                //scheduleQRCode.getTotalQty()
                                                String.valueOf((int)Float.parseFloat(scheduleQRCode.getTotalQty()))
                                        );
                                        scheduleQRCode.setTotalNg(jsonObject.getString("total_ng"));
                                        txt_total_qty_ng.setText(
                                                // Remove the decimal point
                                                //scheduleQRCode.getTotalQty()
                                                String.valueOf((int)Float.parseFloat(scheduleQRCode.getTotalNg()))
                                        );

                                        JSONObject json = new JSONObject();
                                        json.put("cmd", "search");
                                        json.put("item_no", tokens[8]);
                                        new AsyncHttpClient(getApplicationContext()
                                                , Settings.getMgmtList().get("web_api") + "/nst_item_master.php"
                                                , json.toString()) {
                                            @Override
                                            protected void onFinished(String response, int resp_code) {
                                                Log.d(getString(R.string.tag), "response: " + response);
                                                try {
                                                    JSONArray jArray = new JSONArray(response);
                                                    for (int i = 0; i < jArray.length(); i++) {
                                                        scheduleQRCode.setData_Char8(jArray.getJSONObject(i).getString("DATA_CHAR8"));
                                                    }

                                                }catch (JSONException e) {
                                                    alertError(err_msg[0],
                                                            new ActionListenerCallback() {

                                                                @Override
                                                                public void onActionSuccess(String successMessage) {
                                                                    resetForm();
                                                                }

                                                                @Override
                                                                public void onActionFailure(Throwable throwableError) {

                                                                }
                                                            }
                                                    );
                                                    Log.e(getString(R.string.tag), "ERROR: " + e.getMessage());
                                                }
                                            }

                                            @Override
                                            protected void onError(Exception e) {

                                            }
                                        }.execute();


                                        switch (scheduleQRCode.getStatus()) {
                                            case NEW:
                                            case NOT_COMPLETED:
                                                if (scheduleQRCode.getStepStatus() == ScheduleQRCode.ScheduleStepStatus.OK) {
                                                    scan_step = 1;
                                                    btn_label.setEnabled(true);


                                                } else {
                                                    confirmation("Do you want to skip it? Please select a mode.",
                                                            getColor(R.color.red),
                                                            true,
                                                            new ActionListenerCallback() {
                                                                @Override
                                                                public void onActionSuccess(String successMessage) {
                                                                    scan_step = 1;
                                                                    btn_label.setEnabled(true);
                                                                }

                                                                @Override
                                                                public void onActionFailure(Throwable throwableError) {
                                                                    resetForm();
                                                                }
                                                            });
                                                }
                                                break;
                                            case COMPLETED:
                                                confirmation("Job has already ended.",
                                                        getColor(R.color.red),
                                                        false,
                                                        new ActionListenerCallback() {
                                                            @Override
                                                            public void onActionSuccess(String successMessage) {

                                                            }

                                                            @Override
                                                            public void onActionFailure(Throwable throwableError) {
                                                                resetForm();
                                                            }
                                                        });
                                                break;
                                            case NOT_FOUND:
                                            default:
                                                err_msg[0] = "Job not found! Please contact leader.";
                                                throw new JSONException(err_msg[0]);

                                        }


                                    } catch (JSONException e) {
                                        alertError(err_msg[0],
                                                new ActionListenerCallback() {

                                                    @Override
                                                    public void onActionSuccess(String successMessage) {
                                                        resetForm();
                                                    }

                                                    @Override
                                                    public void onActionFailure(Throwable throwableError) {

                                                    }
                                                }
                                        );
                                        Log.e(getString(R.string.tag), "ERROR: " + e.getMessage());
                                    }
                                }

                                @Override
                                protected void onError(Exception e) {

                                }
                            }
                                    .execute();
                        }
                    } else {
                        alertError("Scan result error[" + data + "]!",
                                new ActionListenerCallback() {

                                    @Override
                                    public void onActionSuccess(String successMessage) {
                                        resetForm();
                                    }

                                    @Override
                                    public void onActionFailure(Throwable throwableError) {

                                    }
                                }
                        );
                    }
                    break;
                case 1:
                    /*
                     QR Contents
                     ${SLIP_CD}
                     ${Shift_Code}
                     ${WS_CD}
                     ${MC_LineNo}
                     ${Item_no}
                     ${ParentI_No}
                     ${Compl_Lot}
                     ${Box_Qty}
                     ${Box_NG}
                     ${Scan_date:datetime(dd/mm/yyyy)}
                     ${Scan_date:datetime(hh:mm:ss)}
                     ${UPD_USER_ID}
                     ${Re_prt_flg}
                     ${DOC_NO}
                     */
                    if (tokens.length==14) {
                        // Check Slip type
                        if (
                                (
                                        Settings.getWorkMode().equals(Settings.WorkMode.COMPLETION)
                                                && Float.parseFloat(tokens[7]) == 0
                                )
                                || (
                                        Settings.getWorkMode().equals(Settings.WorkMode.NG_LABEL)
                                                && Float.parseFloat(tokens[8]) == 0
                                )
                        ) {

                            alertError("Invalid label type!",
                                    new ActionListenerCallback() {

                                        @Override
                                        public void onActionSuccess(String successMessage) {
                                        }

                                        @Override
                                        public void onActionFailure(Throwable throwableError) {
                                        }
                                    }
                            );
                        } else {
                            // Check status of slip, validation and Item no matched
                            try {
                                // send JSON request
                                JSONObject json = new JSONObject();
                                json.put("cmd", "search");
                                json.put("slip_cd", tokens[0].trim());

                                new AsyncHttpClient(getApplicationContext()
                                        ,Settings.getMgmtList().get("web_api") + "/nst_compl_input.php"
                                        , json.toString()
                                ) {
                                    @Override
                                    public void onFinished(String response, int resp_code) {
                                        String err_msg;
                                        Boolean isValid = false;
                                        CompletionInput.Status status = CompletionInput.Status.CANCEL;
                                        CompletionInput.JoinTableFlag joinTableFlag = null;
                                        Log.d(getString(R.string.tag), "response: " + response);
                                        try {
                                            err_msg = "Server connection failed!\nPlease contact leader.";
                                            JSONArray jsonArray = new JSONArray(response);
                                            if (jsonArray.length() != 0) {
                                                try {
                                                    // send JSON request
                                                    JSONObject json = jsonArray.getJSONObject(0);
                                                    isValid = true;
                                                    status = CompletionInput.Status.fromId(
                                                            Integer.parseInt(json.getString("doc_status"))
                                                    );
                                                    joinTableFlag = CompletionInput.JoinTableFlag.fromId(
                                                            Integer.parseInt(json.getString("jon_tbl_flag"))
                                                    );
                                                } catch (Exception e) {
                                                    Log.e(getString(R.string.tag), e.getMessage());
                                                }
                                            } else {
                                                err_msg = "Slip code not found!";
                                                throw new JSONException(err_msg);
                                            }
                                        } catch (JSONException e) {
                                            Log.e(getString(R.string.tag), "ERROR: " + e.getMessage());
                                        }

                                        if (tokens[4].trim().equalsIgnoreCase(txt_item_code.getText().toString())
                                                && isValid
                                                && status == CompletionInput.Status.OK
                                                && joinTableFlag == CompletionInput.JoinTableFlag.NEW
                                        ) {
                                            alertOk("Matched", new ActionListenerCallback() {
                                                @Override
                                                public void onActionSuccess(String successMessage) {

                                                    try {
                                                        // send JSON request
                                                        JSONObject json = new JSONObject();
                                                        json.put("cmd", "scan");
                                                        json.put("slip_cd", tokens[0]);

                                                        new AsyncHttpClient(getApplicationContext()
                                                                ,Settings.getMgmtList().get("web_api") + "/nst_compl_input.php"
                                                                , json.toString()
                                                        ) {
                                                            @Override
                                                            public void onFinished(String response, int resp_code) {
                                                                String err_msg = "";
                                                                Log.d(getString(R.string.tag), "response: " + response);
                                                                try {
                                                                    err_msg = "Server connection failed!\nPlease contact leader.";
                                                                    JSONObject jsonObject = new JSONObject(response);
                                                                    if (jsonObject.getString("status").equalsIgnoreCase("success")) {

                                                                        if ( Settings.getWorkMode().equals(Settings.WorkMode.COMPLETION) ) {
                                                                            txt_total_qty_ok.setText(
                                                                                    String.format("%.0f",
                                                                                            Float.parseFloat(txt_total_qty_ok.getText().toString())
                                                                                                    + Float.parseFloat((tokens[7]))));

                                                                            if (Float.parseFloat(txt_total_qty_ok.getText().toString())
                                                                                    >= Float.parseFloat(txt_target_qty.getText().toString())) {
                                                                                resetForm();
                                                                            }
                                                                        } else {
                                                                            resetForm();
                                                                        }
                                                                    } else {
                                                                        throw new JSONException(err_msg);
                                                                    }
                                                                } catch (JSONException e) {
                                                                    alertError(err_msg,
                                                                            new ActionListenerCallback() {

                                                                                @Override
                                                                                public void onActionSuccess(String successMessage) {
                                                                                }

                                                                                @Override
                                                                                public void onActionFailure(Throwable throwableError) {

                                                                                }
                                                                            }
                                                                    );
                                                                    Log.e(getString(R.string.tag), "ERROR: " + e.getMessage());
                                                                }
                                                            }

                                                            @Override
                                                            protected void onError(Exception e) {

                                                            }
                                                        }
                                                                .execute();

                                                    } catch (Exception e) {
                                                        Log.e(getString(R.string.tag), e.getMessage());
                                                    }
                                                }

                                                @Override
                                                public void onActionFailure(Throwable throwableError) {

                                                }
                                            });
                                        } else {
                                            alertError("Non-matched", new ActionListenerCallback() {
                                                @Override
                                                public void onActionSuccess(String successMessage) {

                                                }

                                                @Override
                                                public void onActionFailure(Throwable throwableError) {

                                                }
                                            });
                                        }
                                    }

                                    @Override
                                    protected void onError(Exception e) {

                                    }
                                }
                                        .execute();

                            } catch (Exception e) {
                                Log.e(getString(R.string.tag), e.getMessage());
                            }
                        }




                    } else {
                        alertError("Scan result error[" + data + "]!",
                                new ActionListenerCallback() {

                                    @Override
                                    public void onActionSuccess(String successMessage) {
                                    }

                                    @Override
                                    public void onActionFailure(Throwable throwableError) {
                                    }
                                }
                        );
                    }
                    break;
                default:
            }

            // always hide keyboard after scan
            Utils.hideKeyboardFrom(getApplicationContext(), default_view);

        } catch (Exception e) {
            alertError("Scan result error[" + data + "]!",
                    new ActionListenerCallback() {

                        @Override
                        public void onActionSuccess(String successMessage) {
                        }

                        @Override
                        public void onActionFailure(Throwable throwableError) {

                        }
                    }
            );
            Log.e(getString(R.string.tag), "ERROR: " + e.getMessage());
        }
    }

    private void Check_pre_print() throws Exception{
        try {

        // Check total qty
        if (Settings.getWorkMode().equals(Settings.WorkMode.COMPLETION)) {
            if ((Float.parseFloat(txt_box_qty_ok.getText().toString())
                    + Float.parseFloat(txt_total_qty_ok.getText().toString()))
                    > Float.parseFloat(txt_target_qty.getText().toString()) ) {
                throw new Exception("The box volume should not exceed the target amount.");
            }
            if (Float.parseFloat(txt_box_qty_ok.getText().toString())
                    <= 0 ) {
                throw new Exception("The box volume should not be zero.");
            }
        } else {
            if (Float.parseFloat(txt_box_qty_ng.getText().toString())
                    <= 0 ) {
                throw new Exception("The box volume should not be zero.");
            }
        }

        //add new condition 10/10/2023
        JSONObject json1 = new JSONObject();
        json1.put("cmd", "check_condition");
        json1.put("interlock", Settings.getWorkShopNo().getInterlock().toString().trim());
        json1.put("completion_qty",txt_box_qty_ok.getText().toString());
        json1.put("doc_no", scheduleQRCode.getDocumentNo());

        new AsyncHttpClient(getApplicationContext(),
                Settings.getMgmtList().get("web_api") + "/nst_compo_detail.php",
                json1.toString()) {
            @Override
            protected void onFinished(String response, int resp_code) {
                String err_msg = "Server connection failed!\nPlease contact leader.\n(check_condition)";
                Log.d(getString(R.string.tag), "response: " + response);
                try {
                    if (response.startsWith("[")) {
                        //JSON Array
                        JSONArray jArray = new JSONArray(response);
                        for (int i = 0; i < jArray.length(); i++) {
                            list_out.add(new Outstanding_List(
                                    jArray.getJSONObject(i).getString("ITEM_NO").trim(),
                                    jArray.getJSONObject(i).getString("Outstanding_usage").trim()));
                        }
                        outstanding_adapter = new Outstanding_Adapter(list_out, CompletionActivity.this);
                        view_Outstanding.setAdapter(outstanding_adapter);
                        layout_Outstanding.setVisibility(View.VISIBLE);

                    } else {
                        //JSON Object
                        JSONObject jsonObject = new JSONObject(response);
                        String status = jsonObject.getString("status");
                        int affected_rows = jsonObject.getInt("affected_rows");
                        if (status.equals("success") && affected_rows > 0) {
                            printSlip();

                        }else{
                            throw new JSONException("Update ACTUAL_USAGE Error! \n Please contact leader.");
                        }
                    }
                } catch (JSONException e) {
                    alertError(err_msg,
                            new ActionListenerCallback() {

                                @Override
                                public void onActionSuccess(String successMessage) {
                                }

                                @Override
                                public void onActionFailure(Throwable throwableError) {

                                }
                            }
                    );
                    Log.e(getString(R.string.tag), "ERROR: " + e.getMessage());
                    btn_label.setEnabled(true);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }

            @Override
            protected void onError(Exception e) {

            }
        }.execute();
        } catch (Exception e) {

            alertError(e.getMessage(),
                    new ActionListenerCallback() {

                        @Override
                        public void onActionSuccess(String successMessage) {
                        }

                        @Override
                        public void onActionFailure(Throwable throwableError) {

                        }
                    }
            );
            Log.e(getString(R.string.tag), "ERROR: " + e.getMessage());
            btn_label.setEnabled(true);
        }
    }


    private void printSlip() throws Exception {
        try {
//            // Check total qty
//            if (Settings.getWorkMode().equals(Settings.WorkMode.COMPLETION)) {
//                if ((Float.parseFloat(txt_box_qty_ok.getText().toString())
//                        + Float.parseFloat(txt_total_qty_ok.getText().toString()))
//                        > Float.parseFloat(txt_target_qty.getText().toString()) ) {
//                    throw new Exception("The box volume should not exceed the target amount.");
//                }
//                if (Float.parseFloat(txt_box_qty_ok.getText().toString())
//                        <= 0 ) {
//                    throw new Exception("The box volume should not be zero.");
//                }
//            } else {
//                if (Float.parseFloat(txt_box_qty_ng.getText().toString())
//                        <= 0 ) {
//                    throw new Exception("The box volume should not be zero.");
//                }
//            }

            // Get sequence ID
            JSONObject json = new JSONObject();
            json.put("cmd", "search");
//            json.put("scan_user", Settings.getUserInfoX().getId());
            json.put("scan_user", Settings.getUserLogin_list().get(position_ws).getUser_id());
            json.put("ws_2d", scheduleQRCode.getElements().get("ws_2d"));

            new AsyncHttpClient(getApplicationContext()
                    ,Settings.getMgmtList().get("web_api") + "/nst_serial_no.php"
                    , json.toString()
            ) {
                @Override
                public void onFinished(String response, int resp_code) {
                    String err_msg = "Server connection failed!\nPlease contact leader.";
                    try {
                        JSONArray jsonArray = new JSONArray(response);
                        Log.d(getString(R.string.tag), "response: " + response);
                        if (jsonArray.length() != 0) {
                            JSONObject serialNoObject = jsonArray.getJSONObject(0);
                            scheduleQRCode.setSerialNo(new SerialNo(
                                    serialNoObject.getString("ws_alias"),
                                    serialNoObject.getString("ws_desc"),
                                    serialNoObject.getString("ws_year"),
                                    serialNoObject.getString("ws_month"),
                                    serialNoObject.getString("ws_day"),
                                    serialNoObject.getInt("seq_no")
                            ));
                        } else {
                            err_msg = "Work shop 2D not found";
                            throw new JSONException(err_msg);
                        }

                        // Prepair SLIP_CD
                                /* Fix SLIP code to 4 digits and use D/M/Y from DB
                                * update on: 2022-02-24
                                String dt = DatetimeUtil.getDateTime("yyyy-M-dd");
                                String[] tokens = dt.split("-");
                                current_slip_code = String.format("W%s%s%c%s%03d",
                                        scheduleQRCode.getElements().get("ws_2d"),
                                        tokens[0].substring(tokens[0].length()-1),
                                        (char)('A' + (Integer.valueOf(tokens[1]) - 1)),
                                        tokens[2],
                                        scheduleQRCode.getSerialNo().getSeq_no()
                                );
                                 */
                        current_slip_code = String.format("W%s%s%s%s%04d",
                                scheduleQRCode.getElements().get("ws_2d"),
                                scheduleQRCode.getSerialNo().getWs_year(),
                                scheduleQRCode.getSerialNo().getWs_month(),
                                scheduleQRCode.getSerialNo().getWs_day(),
                                scheduleQRCode.getSerialNo().getSeq_no()
                        );



                        // send Slip-Detail together
                        String print_date = DatetimeUtil.getDateTime("yyyyMMddHHmmss");

                        // Send data to printer controller
                                                /*
                                                Reprint:word|
                                                SLIP_CD:word|
                                                Shift_Code:word|
                                                WS_DESC:word|
                                                WS_CD:word|
                                                MC_LineNo:word|
                                                Item_no:word|
                                                Item_desc:word|
                                                ParentI_No:word|
                                                ParentI_desc:word|
                                                Box_Qty:decimal|
                                                Scan_date:datetime(yyyyMMddHHmmss)|
                                                User_name:word|
                                                Compl_Lot:word|
                                                UPD_USER_ID:word|
                                                DOC_NO:word|
                                                Re_prt_flg:decimal
                                                 */
                        final String[] payload = {String.format("%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s",
                                "",
                                current_slip_code,
                                Settings.getShiftCode().getId(),
                                scheduleQRCode.getSerialNo().getWs_desc(),
                                scheduleQRCode.getElements().get("ws_cd"),
                                Settings.getUserLogin_list().get(position_ws).getMc_line_no(),
                                scheduleQRCode.getElements().get("item_no"),
                                scheduleQRCode.getElements().get("item_desc"),
                                scheduleQRCode.getElements().get("parenti_no"),
                                scheduleQRCode.getElements().get("parenti_desc"),
                                (Settings.getWorkMode().equals(Settings.WorkMode.COMPLETION)
                                        ? txt_box_qty_ok.getText() : txt_box_qty_ng.getText()),
                                print_date,
                                Settings.getUserLogin_list().get(position_ws).getUser_name(),
                                scheduleQRCode.getElements().get("compl_lot"),
                                Settings.getUserLogin_list().get(position_ws).getUser_id(),
                                scheduleQRCode.getDocumentNo(),
                                "1",
                                scheduleQRCode.getData_Char8()
                        )};

                        // Keep slip detail *remark update on version 1.2.4 2022-03-07
                        JSONObject slip_det = new JSONObject();
                        slip_det.put("slip_cd", current_slip_code);
                        slip_det.put("user_name",Settings.getUserLogin_list().get(position_ws).getUser_name());
                        slip_det.put("ng", Settings.getWorkMode().equals(Settings.WorkMode.NG_LABEL) ? 1 : 0);
                        slip_det.put("preset", Settings.getUserLogin_list().get(position_ws).getPrint_preset());
                        slip_det.put("payload", payload[0]);

                        // send JSON request
                        JSONObject json = new JSONObject();
                        json.put("cmd", "add");
                        json.put("ws_cd", scheduleQRCode.getElements().get("ws_cd"));
                        json.put("item_no", scheduleQRCode.getElements().get("item_no"));
                        json.put("slip_no", current_slip_code);
                        json.put("doc_no", scheduleQRCode.getDocumentNo());
                        json.put("ok_qty", txt_box_qty_ok.getText().toString().equals("-")?0:txt_box_qty_ok.getText());
                        json.put("ng_qty", txt_box_qty_ng.getText().toString().equals("-")?0:txt_box_qty_ng.getText());
                        json.put("doc_status", "0");
                        json.put("jon_tbl_flag", CompletionInput.JoinTableFlag.NEW.getId());
                        json.put("upd_pgm", getString(R.string.prog_name));
                        json.put("upd_user_id", Settings.getUserLogin_list().get(position_ws).getUser_id());
                        json.put("re_prt_flag", CompletionInput.ReprintFlag.NO.getId());
                        json.put("slip_detail", slip_det);

                        new AsyncHttpClient(getApplicationContext()
                                ,Settings.getMgmtList().get("web_api") + "/nst_compl_input.php"
                                , json.toString()
                        ) {
                            @Override
                            public void onFinished(String response, int resp_code) {
                                String err_msg = "";
                                Log.d(getString(R.string.tag), "response: " + response);
                                try {
                                    err_msg = "Server connection failed!\nPlease contact leader.";
                                    JSONObject jsonObject = new JSONObject(response);
                                    if (jsonObject.getString("status").equalsIgnoreCase("success")) {

//                                                String print_date = DatetimeUtil.getDateTime("yyyyMMddHHmmss");
//
//                                                // Send data to printer controller
//                                                /*
//                                                Reprint:word|
//                                                SLIP_CD:word|
//                                                Shift_Code:word|
//                                                WS_DESC:word|
//                                                WS_CD:word|
//                                                MC_LineNo:word|
//                                                Item_no:word|
//                                                Item_desc:word|
//                                                ParentI_No:word|
//                                                ParentI_desc:word|
//                                                Box_Qty:decimal|
//                                                Scan_date:datetime(yyyyMMddHHmmss)|
//                                                User_name:word|
//                                                Compl_Lot:word|
//                                                UPD_USER_ID:word|
//                                                DOC_NO:word|
//                                                Re_prt_flg:decimal
//                                                 */
//                                                String payload = String.format("%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s|%s",
//                                                        "",
//                                                        current_slip_code,
//                                                        Settings.getShiftCode().getId(),
//                                                        scheduleQRCode.getSerialNo().getWs_desc(),
//                                                        scheduleQRCode.getElements().get("ws_cd"),
//                                                        Settings.getWorkShopNo().getMc_line_no(),
//                                                        scheduleQRCode.getElements().get("item_no"),
//                                                        scheduleQRCode.getElements().get("item_desc"),
//                                                        scheduleQRCode.getElements().get("parenti_no"),
//                                                        scheduleQRCode.getElements().get("parenti_desc"),
//                                                        ( Settings.getWorkMode().equals(Settings.WorkMode.COMPLETION)
//                                                                ? txt_box_qty_ok.getText() : txt_box_qty_ng.getText() ),
//                                                        print_date,
//                                                        Settings.getUserInfoX().getDesc(),
//                                                        scheduleQRCode.getElements().get("compl_lot"),
//                                                        Settings.getUserInfoX().getId(),
//                                                        scheduleQRCode.getDocumentNo(),
//                                                        "1"
//                                                );
//
//                                                // Keep slip detail
//                                                JSONObject json = new JSONObject();
//                                                json.put("cmd", "add");
//                                                json.put("slip_cd", current_slip_code);
//                                                json.put("user_name", Settings.getUserInfoX().getDesc());
//                                                json.put("ng", Settings.getWorkMode().equals(Settings.WorkMode.NG_LABEL) ? 1 : 0);
//                                                json.put("preset", Settings.getWorkShopNo().getPrint_preset());
//                                                json.put("payload", payload);
//                                                new AsyncHttpClient(getApplicationContext()
//                                                        ,Settings.getMgmtList().get("web_api") + "/nst_slip_detail.php"
//                                                        , json.toString()
//                                                ) {
//                                                    @Override
//                                                    public void onFinished(String response, int resp_code) {
//                                                        Log.d(getString(R.string.tag), "Slip detail keep success.");
//                                                    }
//                                                }.execute();

                                        String tmp = String.format(
                                                "%s %s%s\r\n%s%s"
                                                , "PST"
                                                , Settings.getUserLogin_list().get(position_ws).getPrint_preset()
                                                , (Settings.getWorkMode().equals(Settings.WorkMode.NG_LABEL) ? "-NG" : "" )
                                                , ""
                                                , payload[0]
                                        );

//                                                alertOk("test", new ActionListenerCallback() {
//                                                    @Override
//                                                    public void onActionSuccess(String successMessage) {
//                                                    }
//
//                                                    @Override
//                                                    public void onActionFailure(Throwable throwableError) {
//
//                                                    }
//                                                });

                                        new AsyncTcpClient(getApplicationContext(),
                                                Settings.getMgmtList().get("printer_server_ip")
                                                , Integer.parseInt(Settings.getMgmtList().get("printer_server_port"))
                                                , tmp
                                        ) {
                                            @Override
                                            protected void onFinished(String response) {
                                                Log.d(getString(R.string.tag), "TCP response: " + response);

                                                if (response.equals("OK")) {
                                                    alertOk("Label printed",
                                                            new ActionListenerCallback() {

                                                                @Override
                                                                public void onActionSuccess(String successMessage) {
                                                                    btn_label.setEnabled(true);
                                                                }

                                                                @Override
                                                                public void onActionFailure(Throwable throwableError) {

                                                                }
                                                            }
                                                    );
                                                } else {

                                                    alertError("Can not connect to print server!",
                                                            new ActionListenerCallback() {

                                                                @Override
                                                                public void onActionSuccess(String successMessage) {
                                                                }

                                                                @Override
                                                                public void onActionFailure(Throwable throwableError) {

                                                                }
                                                            }
                                                    );
                                                }
                                                btn_label.setEnabled(true);
                                            }
                                        }.execute();
                                    } else {
                                        throw new JSONException(err_msg);
                                    }
                                } catch (JSONException e) {
                                    alertError(err_msg,
                                            new ActionListenerCallback() {

                                                @Override
                                                public void onActionSuccess(String successMessage) {
                                                }

                                                @Override
                                                public void onActionFailure(Throwable throwableError) {

                                                }
                                            }
                                    );
                                    Log.e(getString(R.string.tag), "ERROR: " + e.getMessage());
                                    btn_label.setEnabled(true);
                                }
                            }

                            @Override
                            protected void onError(Exception e) {

                            }
                        }
                                .execute();
                    } catch (JSONException e) {
                        alertError(err_msg,
                                new ActionListenerCallback() {

                                    @Override
                                    public void onActionSuccess(String successMessage) {
                                    }

                                    @Override
                                    public void onActionFailure(Throwable throwableError) {

                                    }
                                }
                        );
                        Log.e(getString(R.string.tag), "ERROR: " + e.getMessage());
                        btn_label.setEnabled(true);
                    }
                }

                @Override
                protected void onError(Exception e) {

                }
            }.execute();

        } catch (Exception e) {

            alertError(e.getMessage(),
                    new ActionListenerCallback() {

                        @Override
                        public void onActionSuccess(String successMessage) {
                        }

                        @Override
                        public void onActionFailure(Throwable throwableError) {

                        }
                    }
            );
            Log.e(getString(R.string.tag), "ERROR: " + e.getMessage());
            btn_label.setEnabled(true);
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        //Log.d(getString(R.string.tag), String.format("Enter key up = %d", keyCode));
        RelativeLayout layout_confirm = (RelativeLayout) findViewById(R.id.popupLayout1);
        RelativeLayout layout_reprint = (RelativeLayout) findViewById(R.id.reprintLayout);
        RelativeLayout layout_delete = (RelativeLayout) findViewById(R.id.deleteLayout);
        Button btnP1;
        Button btnP2;

        // Mapping to multiple layers button
        if (layout_confirm.getVisibility()==View.VISIBLE) {
            btnP1 = (Button) findViewById(R.id.popupLayout1_btn1);
            btnP2 = (Button) findViewById(R.id.popupLayout1_btn2);
        } else if (layout_reprint.getVisibility()==View.VISIBLE) {
            btnP1 = (Button) findViewById(R.id.reprintLayout_btn1);
            btnP2 = (Button) findViewById(R.id.reprintLayout_btn2);
        } else if (layout_delete.getVisibility()==View.VISIBLE) {
            btnP1 = (Button) findViewById(R.id.deleteLayout_btn1);
            btnP2 = (Button) findViewById(R.id.deleteLayout_btn2);
        } else {
            btnP1 = btn_cancel;
            btnP2 = btn_label;
        }

        if (keyCode >= KeyMapping.P1.getId()
                && keyCode <= KeyMapping.P4.getId())
        {
            switch (KeyMapping.fromId(keyCode)) {
                case P1:
                    btnP1.performClick();
                    break;

                case P2:
                    btnP2.performClick();
                    break;

                case P3:
                    btn_reprint.performClick();
                    break;

                case P4:
                    btn_delete.performClick();
                    break;

            }
        } else if (keyCode == KeyMapping.ENT.getId()) {
            Utils.hideKeyboardFrom(getApplicationContext(), default_view);

            RelativeLayout popupLayout2 = (RelativeLayout) findViewById(R.id.popupLayout2);
            if (popupLayout2.getVisibility() == RelativeLayout.VISIBLE) {
                Button btn = (Button) findViewById(R.id.popupLayout2_btn1);
                btn.performClick();
                return false;
            }
        }

        return super.onKeyUp(keyCode, event);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();


    }
}
