package com.tomas.ht_mast;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.constraintlayout.widget.ConstraintLayout;

import com.keyence.autoid.sdk.scan.DecodeResult;
import com.tomas.ht_mast.Adapter.FilterArray_Adapter;
import com.tomas.ht_mast.ListData.ItemMaster_list;
import com.tomas.ht_mast.ListData.Location_list;
import com.tomas.ht_mast.ListData.PackingStandard_list;
import com.tomas.ht_mast.ListData.Payload_list;
import com.tomas.ht_mast.lib.ActionType;
import com.tomas.ht_mast.lib.AlertProgress;
import com.tomas.ht_mast.lib.KeyMapping;
import com.tomas.ht_mast.lib.Scanner;
import com.tomas.ht_mast.lib.Settings;
import com.tomas.ht_mast.lib.common.AsyncHttpClient;
import com.tomas.ht_mast.lib.common.AsyncTcpClient;
import com.tomas.ht_mast.lib.common.DatetimeUtil;
import com.tomas.ht_mast.lib.common.Utils;

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

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class LabelDetail_Activity extends Scanner implements View.OnClickListener {
    LinearLayout layout_edt_act_qty, layout_per_box_old, layout_qty_pbox, layout_outbound_qty;
    ConstraintLayout layout_confirm_print;
    Calendar calendar;
    DecimalFormat decimalFormat, decimal_comma_fm;
    JSONObject label_detail = null;
    SimpleDateFormat date_lot_no, date_fm;
    TextView txt_header, txt_user, txt_device, txt_order_date, txt_order_no, txt_part_name, txt_qty, txt_per_box_old, txt_part_no, txt_etg;
    EditText edt_act_qty, edt_qty_per_box, edt_lot_no, edt_outbound_qty;
    Button btn_clear, btn_reprint, btn_confirm;
    Bundle bundle;
    Double f_act_qty, f_qty_pbox, f_outbound_qty, f_qty_per_box_old;
    String ref_label_id, str_date, str_lot_no, action_type, str_status,str_sch_id, str_order_no, str_order_date, str_part_no,
            str_part_name, str_qty,ButtonClick, str_unit_qty, str_qty_per_box;
    AlertProgress alert;
    int LABEL_QTY, PRINT_TIMES;
    private volatile boolean stopThread = true;
    List<Payload_list> payload_list;
    ArrayList<String> mainList;
    boolean b_confirm, ETG_label;
    Dialog dialog_search;



    @SuppressLint("SetTextI18n")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_label_detail);
        default_view = (EditText) findViewById(R.id.txt_label_issue_tmp);

        b_confirm = false;
        ETG_label = false;
        stopThread = true;

        decimalFormat = new DecimalFormat("##00.00");
        decimal_comma_fm = new DecimalFormat("#,#00.00");

        alert = new AlertProgress(LabelDetail_Activity.this);
        ButtonClick = ActionType.ButtonClick.NULL.toString();
        payload_list = new ArrayList<Payload_list>();
        mainList = new ArrayList<>();

        txt_user = (TextView) findViewById(R.id.txt_user);
        txt_user.setText("User : "+ Settings.getLoginUser().getName());

        txt_device = (TextView) findViewById(R.id.txt_device);
        txt_device.setText("Device : "+Settings.getDeviceNo());

        calendar = Calendar.getInstance();
        date_lot_no = new SimpleDateFormat("yyyy-MM-dd");
        str_lot_no = date_lot_no.format(calendar.getTime());
        date_fm = new SimpleDateFormat("dd/MM/yyyy");
        str_date = date_fm.format(calendar.getTime());

        layout_edt_act_qty = (LinearLayout)findViewById(R.id.layout_edt_act_qty);
        layout_per_box_old = (LinearLayout)findViewById(R.id.layout_per_box_old);
        layout_qty_pbox = (LinearLayout)findViewById(R.id.layout_qty_pbox);
        layout_outbound_qty = (LinearLayout)findViewById(R.id.layout_outbound_qty);


        txt_header = (TextView) findViewById(R.id.txt_header);
        txt_user = (TextView) findViewById(R.id.txt_user);
        txt_device = (TextView) findViewById(R.id.txt_device);
        txt_order_date = (TextView) findViewById(R.id.txt_date);
        txt_order_no = (TextView) findViewById(R.id.txt_order_no);
        txt_part_no = (TextView) findViewById(R.id.txt_part_no);
        txt_part_name = (TextView) findViewById(R.id.txt_part_name);
        txt_qty = (TextView) findViewById(R.id.txt_qty);
        txt_per_box_old = (TextView)findViewById(R.id.txt_per_box_old);
        txt_etg = (TextView)findViewById(R.id.txt_etg);
        txt_etg.setVisibility(View.GONE);


        edt_lot_no = (EditText) findViewById(R.id.edt_lot_no);
        edt_lot_no.setInputType(InputType.TYPE_NULL);
        edt_lot_no.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                final Calendar currentDate = Calendar.getInstance();
                new DatePickerDialog(LabelDetail_Activity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        str_lot_no =( year+"-"+
                                (String.format("%2s",monthOfYear + 1).replace(' ','0'))+"-"+
                                (String.format("%2s",dayOfMonth).replace(' ','0')));
                        edt_lot_no.setText(str_lot_no);
                    }
                }, currentDate.get(Calendar.YEAR), currentDate.get(Calendar.MONTH), currentDate.get(Calendar.DATE)).show();
            }
        });

        edt_act_qty = (EditText) findViewById(R.id.edt_act_qty);
        edt_act_qty.requestFocus();
        edt_act_qty.setShowSoftInputOnFocus(false);

        edt_qty_per_box = (EditText) findViewById(R.id.edt_qty_per_box);
        edt_qty_per_box.requestFocus();
        edt_qty_per_box.setShowSoftInputOnFocus(false);

        edt_outbound_qty = (EditText) findViewById(R.id.edt_outbound_qty);
        edt_outbound_qty.requestFocus();
        edt_outbound_qty.setShowSoftInputOnFocus(false);

        btn_clear = (Button) findViewById(R.id.btn_clear);
        btn_reprint = (Button) findViewById(R.id.btn_reprint);
        btn_confirm = (Button) findViewById(R.id.btn_confirm);

        action_type = Settings.getActionType().toString().trim();
        Log.d(getString(R.string.tag), "action_type: " + action_type);
        bundle = getIntent().getExtras();
        if (action_type.trim().equals(ActionType.Type.LABEL_SCHEDULE.toString())) {
            txt_header.setText("Label Detail");
            str_sch_id = bundle.getString("schedule_id");
            str_order_no = bundle.getString("order_no");
            str_order_date = bundle.getString("order_dt");
            str_part_no = bundle.getString("part_no");
            str_part_name = bundle.getString("part_name");
            str_qty = bundle.getString("plan_qty");
            str_unit_qty = bundle.getString("unit");
            str_status = bundle.getString("status");

            Log.d(getString(R.string.tag), "status: " + str_status);

            if (str_status.trim().equals("IMPORTED")||str_status.trim().equals("CONFIRMED")||str_status.trim().equals("WORKING")){
                btn_reprint.setVisibility(View.GONE);

            }else {//COMPLETE
                btn_reprint.setVisibility(View.VISIBLE);
                btn_confirm.setVisibility(View.GONE);
            }

            txt_order_date.setText(str_order_date);
            txt_order_no.setText(str_order_no);
            txt_part_no.setText(str_part_no);
            txt_part_name.setText(str_part_name);
            txt_qty.setText(decimal_comma_fm.format(Double.parseDouble(str_qty)));
//            edt_qty_per_box.setText(str_qty_per_box);
            edt_lot_no.setText(str_lot_no);

            Get_Packing(str_part_no,str_unit_qty);

        }else if (action_type.trim().equals(ActionType.Type.LABEL_MANUAL.toString())){
            txt_header.setText("Label Manual");
            txt_order_date.setText(str_date);
            txt_order_no.setBackgroundResource(R.drawable.textview_background_gray);
            txt_qty.setBackgroundResource(R.drawable.textview_background_gray);
            btn_reprint.setVisibility(View.GONE);
            edt_lot_no.setText(str_lot_no);
            txt_part_no.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    search_items();
                }
            });

        }else {//Relabeling
            txt_header.setText("Relabeling");
            txt_order_date.setBackgroundResource(R.drawable.textview_background_gray);
            txt_order_no.setBackgroundResource(R.drawable.textview_background_gray);
            txt_part_no.setBackgroundResource(R.drawable.textview_background_gray);
            txt_part_name.setBackgroundResource(R.drawable.textview_background_gray);
            edt_lot_no.setBackgroundResource(R.drawable.textview_background_gray);
            edt_lot_no.setEnabled(true);
            txt_qty.setBackgroundResource(R.drawable.textview_background_gray);
            btn_reprint.setVisibility(View.GONE);
            layout_edt_act_qty.setVisibility(View.GONE);
            layout_qty_pbox.setVisibility(View.GONE);
            layout_per_box_old.setVisibility(View.VISIBLE);
            layout_outbound_qty.setVisibility(View.VISIBLE);

        }
    }

    private void Get_Packing(String str_part_no, String str_unit_qty) {
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "conversion-unit");
            json.put("parts_no", str_part_no);
            json.put("qty", "1");
            json.put("from_unit", "BOX");
            json.put("to_unit", str_unit_qty);

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

                    try{
                        JSONArray jArray = new JSONArray(response);
                        str_qty_per_box =  jArray.getJSONObject(0).getString("qty").trim()== "null" ? "" : jArray.getJSONObject(0).getString("qty").trim();

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

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


    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.imb_back:
                finish();
                break;

            case R.id.btn_clear:
                Clear_layout();
                break;

            case R.id.btn_confirm:
                if (b_confirm == false) {
                    Block_button();
                    ButtonClick = ActionType.ButtonClick.CONFIRM.toString();
                    Check_Qty();
                }
                break;

            case R.id.btn_reprint:
                if (b_confirm == false) {
                    Block_button();
                    ButtonClick = ActionType.ButtonClick.REPRINT.toString();
                    Check_Qty();
                }
                break;
        }
    }

    private void Block_button() {
        b_confirm = true;
        btn_confirm.setEnabled(false);
        btn_confirm.setBackgroundResource(R.drawable.button_background_gray);
        btn_reprint.setEnabled(false);
        btn_reprint.setBackgroundResource(R.drawable.button_background_gray);
    }

    private void Unblock_button() {
        b_confirm = false;
        btn_confirm.setEnabled(true);
        btn_confirm.setBackgroundResource(R.drawable.button_background_blue);
        btn_reprint.setEnabled(true);
        btn_reprint.setBackgroundResource(R.drawable.button_background_green);
    }


    private void Check_Qty() {
        Log.d(getString(R.string.tag), "ButtonClick: " + ButtonClick);
        if (action_type.trim().equals(ActionType.Type.LABEL_SCHEDULE.toString())
            ||action_type.trim().equals(ActionType.Type.LABEL_MANUAL.toString())) {    //LABEL_SCHEDULE & LABEL_MANUAL

            if (edt_act_qty.getText().toString().equals("")||edt_qty_per_box.getText().toString().equals("")){
                new SweetAlertDialog(LabelDetail_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("WARNING")
                        .setContentText("Please complete the information")
                        .show();
                Unblock_button();
            }else {
                String str_qty_act = edt_act_qty.getText().toString();
                String s_qty_pbox = edt_qty_per_box.getText().toString();
                Double cv_pbox = Double.parseDouble(s_qty_pbox);

                f_act_qty = Double.parseDouble(str_qty_act);
                f_qty_pbox = cv_pbox;

                if ( Utils.CompareDouble(f_act_qty , 0.0) ||  Utils.CompareDouble(f_qty_pbox,0.0 )) {//|| f_act_qty < f_qty_pbox
                    new SweetAlertDialog(LabelDetail_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("WARNING")
                            .setContentText("Quantity is in error")
                            .show();
                    Unblock_button();
                }else{
                    Prepare_Label();
                }
            }
        }else{//RELABELING
            if (edt_outbound_qty.getText().toString().equals("")){
                new SweetAlertDialog(LabelDetail_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("WARNING")
                        .setContentText("Please complete the information")
                        .show();
                Unblock_button();
            }else {
                String str_outbound_qty = edt_outbound_qty.getText().toString();
//                String str_qty_pbox_old = txt_per_box_old.getText().toString();
                String str_qty_pbox_old = txt_qty.getText().toString();//issue_qty
                Double cv_pbox = Double.parseDouble(str_qty_pbox_old.replaceAll(",",""));

                f_outbound_qty = Double.parseDouble(str_outbound_qty);//outbound qty
                f_qty_per_box_old = cv_pbox;//qty per box old

                if ( Utils.CompareDouble(f_outbound_qty , 0.0)
                        ||  f_qty_per_box_old < f_outbound_qty
                        || Utils.CompareDouble(f_qty_per_box_old , f_outbound_qty )) {
                    new SweetAlertDialog(LabelDetail_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("WARNING")
                            .setContentText("Quantity is in error")
                            .show();
                    Unblock_button();
                }else{
                    Prepare_Label();
                }
            }
        }
    }

    private void Prepare_Label() {
        try {
            JSONObject json = new JSONObject();
            if (action_type.trim().equals(ActionType.Type.LABEL_SCHEDULE.toString())) {//LABEL_SCHEDULE
                if (ButtonClick.trim().equals(ActionType.ButtonClick.CONFIRM.toString())) {
                    json.put("cmd", "SCHEDULE/LABEL/DETAILS/CONFIRM/PREPARE"); //No.2
                    json.put("warehouse", ETG_label == true ? "ETG" : "");

                } else {//reprint
                    json.put("cmd", "SCHEDULE/LABEL/DETAILS/REPRINT/PREPARE"); //No.3
                }

                json.put("sch_id", str_sch_id);
                json.put("lot_no", edt_lot_no.getText().toString().trim());
                json.put("act_qty", String.valueOf(decimalFormat.format(f_act_qty)));
                json.put("qty_per_box",String.valueOf(decimalFormat.format(f_qty_pbox)));
                json.put("user_id",Settings.getLoginUser().getId());

            }else if (action_type.trim().equals(ActionType.Type.LABEL_MANUAL.toString())) {//LABEL_MANUAL
                json.put("cmd", "LABEL/MANUAL/CONFIRM/PREPARE");//No.6
                json.put("parts_no",txt_part_no.getText().toString().trim());
                json.put("act_qty", String.valueOf(decimalFormat.format(f_act_qty)));
                json.put("qty_per_box",String.valueOf(decimalFormat.format(f_qty_pbox)));
                json.put("lot_no", edt_lot_no.getText().toString().trim());
                json.put("user_id",Settings.getLoginUser().getId());
//                json.put("warehouse", ETG_label == true ? "ETG" : "");

            }else{//Relabeling
                json.put("cmd", "RELABELING/CONFIRM/PREPARE");//No.8
                json.put("ref_label_id", ref_label_id);
                json.put("new_qty", String.valueOf(decimalFormat.format(f_outbound_qty)));
                json.put("user_id",Settings.getLoginUser().getId());
            }

            json.put("lot_no", edt_lot_no.getText().toString().trim());
            json.put("user_id", Settings.getLoginUser().getId());

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

                    try{
                        JSONObject jsonObject = new JSONObject(response);
                        String status = jsonObject.getString("status");
                        if (status.trim().equals("error")){
                            String error = jsonObject.getString("error");
                            new SweetAlertDialog(LabelDetail_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(error)
                                    .show();
                            Unblock_button();
                        }else {
                            String value = jsonObject.getString("value");
                            JSONArray jArray = new JSONArray(value);
                            LABEL_QTY = jArray.length();

                            payload_list.clear();
                            for (int i = 0; i < jArray.length(); i++){
                                String  scrap_flg =  jArray.getJSONObject(i).getString("scrap_flg").trim();
                                if(scrap_flg.trim().equals("1")){
                                    scrap_flg =  "-SC";
                                }else {
                                    scrap_flg =  "";
                                }

                                payload_list.add(new Payload_list(
                                        jArray.getJSONObject(i).getString("id"),
                                        scrap_flg,
                                        jArray.getJSONObject(i).getString("payload"),
                                        jArray.getJSONObject(i).getString("issue_qty")));
                            }
                            //check printer

                                if (Settings.getMgmtList().get("skip_print").trim().equals("1")) {
                                    AlertConfirmPrint();

                                } else {
                                    if (Settings.getPrinter().trim().equals("")
                                            ||Settings.getPrinter().trim().equals(null)
                                            ||Settings.getPrinter().trim().equals("null")){
                                        new SweetAlertDialog(LabelDetail_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                                .setTitleText("WARNING")
                                                .setContentText("Please setting printer")
                                                .show();
                                    }else {
                                        Command_Print();
                                    }
                                }

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

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

    private void Command_Print() {
        alert.setMessage("           Printing label....         ");
        alert.show();

            PRINT_TIMES = 0;
            stopThread = false;
            Log.d("Thread.sleep", "stopThread: " + stopThread + ":" + PRINT_TIMES);

            ExampleRunnable runnable = new ExampleRunnable();
            new Thread(runnable).start();

    }
    class ExampleRunnable implements Runnable {
        @Override
        public void run() {
            while (!stopThread) {
                try {
                    Print_Label();
                    Thread.sleep(2000);

                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }



    private void Print_Label() {
        Log.d(getString(R.string.tag), "PRINT_TIMES1: " + PRINT_TIMES+"="+LABEL_QTY);

        PRINT_TIMES = (PRINT_TIMES + 1);
        Log.d(getString(R.string.tag), "PRINT_TIMES2: " + PRINT_TIMES+"="+LABEL_QTY);

        if (PRINT_TIMES == LABEL_QTY){
            stopThread = true;
            Log.d(getString(R.string.tag), "stopThread: " + stopThread);
        }

        Payload_list payload_l = payload_list.get(PRINT_TIMES-1);
        String payload = payload_l.getPayload();
        String scrap_flg = payload_l.getScrap_flg();
        Log.d("payload", payload_l.getId()+"|" + payload);

        String err_msg = "";
        try {
            err_msg = "Server connection failed!\nPlease contact leader.";

            String tmp = String.format(
                    "%s %s%s%s\r\n%s"
                    , "PST"
                    , Settings.getMgmtList().get("printer_preset")
                    , Settings.getPrinter()
                    , scrap_flg
//                    , Settings.getDeviceNo()
                    , payload

            );

            Log.d(getString(R.string.tag), "payload: " + payload);
            new AsyncTcpClient(getApplicationContext(),
                    Settings.getMgmtList().get("printer_server_host"),
                    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")) {
                        if (stopThread == true) {
                            alert.dismiss();
                            AlertConfirmPrint();

                        }
                    } else {
                        alert.dismiss();
                        Unblock_button();
                        new SweetAlertDialog(LabelDetail_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText("Can't connect to print server")
                                .show();

                    }
                }
            }.execute();
            throw new JSONException(err_msg);

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

    private void AlertConfirmPrint() {
            new SweetAlertDialog(LabelDetail_Activity.this, SweetAlertDialog.SUCCESS_TYPE)
                    .setTitleText("SUCCESS")
                    .setContentText("Click 'No' if nothing printed out?")
                    .setCancelText("No")
                    .showCancelButton(true)
                    .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sDialog) {
                            Unblock_button();
                            sDialog.cancel();
                        }
                    })
                    .setConfirmText("Yes")
                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sDialog) {
                            sDialog.cancel();
                            Confirm_Label();
                        }
                    })
                    .show();
    }

    private void Confirm_Label() {
        try {
            JSONObject json = new JSONObject();
            if (action_type.trim().equals(ActionType.Type.LABEL_SCHEDULE.toString())) {//LABEL_SCHEDULE
                if (ButtonClick.trim().equals(ActionType.ButtonClick.CONFIRM.toString())) {
                    json.put("cmd", "SCHEDULE/LABEL/DETAILS/CONFIRM/CONFIRM");//N0.4
                }else {//reprint
                    json.put("cmd", "SCHEDULE/LABEL/DETAILS/REPRINT/CONFIRM"); //No.5
                }
            }else if (action_type.trim().equals(ActionType.Type.LABEL_MANUAL.toString())) {//LABEL_MANUAL
                json.put("cmd", "LABEL/MANUAL/CONFIRM/CONFIRM");//No.7
            }else{//Relabeling
                json.put("cmd", "RELABELING/CONFIRM/CONFIRM");//No.9
            }
                JSONArray jArray = new JSONArray();
                for (int i = 0; i < payload_list.size(); i++){
                    Payload_list list = payload_list.get(i);
                    Map<String, String> jsParams = new HashMap<>();
                    jsParams.put("label_id", list.getId());
                    JSONObject jsonObject = new JSONObject(jsParams);
                    jArray.put(jsonObject);
                }
                json.put("value",jArray);

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

                    try{
                        JSONObject jsonObject = new JSONObject(response);
                        String status = jsonObject.getString("status");
                        int affected_rows = jsonObject.getInt("affected_rows");

                        if (status.trim().equals("success") && affected_rows > 0){
                            if (action_type.trim().equals(ActionType.Type.RELABELING.toString())){
                                UpdateLocation();
                            }else{
                                //SUCCESS
                                finish();
                            }
                        }else {
                            String error = jsonObject.getString("error");
                            new SweetAlertDialog(LabelDetail_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(error)
                                    .show();
                            Unblock_button();
                        }
                    }catch (JSONException e) {
                        new SweetAlertDialog(LabelDetail_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                        Unblock_button();
                    }
                }
            }.execute();

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

    private void UpdateLocation() {
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "edit");

            JSONArray jArray = new JSONArray();
            for (int i = 0; i < payload_list.size(); i++){
                Payload_list list = payload_list.get(i);

                Map<String, String> jsParams = new HashMap<>();
                jsParams.put("item_id", label_detail.getString("lbl_part_no") );
                jsParams.put("item_name", label_detail.getString("lbl_part_name").trim().equals("null") ? "" : label_detail.getString("lbl_part_name").trim());
                jsParams.put("supplier_id", label_detail.getString("lbl_supplier_id").trim().equals("null") ? "" : label_detail.getString("lbl_supplier_id").trim());
                jsParams.put("supplier_name", label_detail.getString("lbl_supplier").trim().equals("null") ? "" : label_detail.getString("lbl_supplier").trim());
                jsParams.put("package_id", label_detail.getString("lbl_unit"));
                jsParams.put("unit_qty", label_detail.getString("control_unit"));
                jsParams.put("package_qty", label_detail.getString("issue_qty"));
                jsParams.put("lot_no", label_detail.getString("lot_no"));
                jsParams.put("qty", list.getQty());
                jsParams.put("location_id",  label_detail.getString("last_location_id").trim().equals("null") ? "" : label_detail.getString("last_location_id").trim());
                jsParams.put("location_name", label_detail.getString("last_location_name").trim().equals("null") ? "" : label_detail.getString("last_location_name").trim());
                jsParams.put("label_id", list.getId());
                jsParams.put("inspection_flg", "0");
                jsParams.put("status", "1"); // STORE_IN(1)
                jsParams.put("slip_divide", "3");
                jsParams.put("create_user_id", Settings.getLoginUser().getId());

                JSONObject jsonObject = new JSONObject(jsParams);
                jArray.put(jsonObject);
            }
            json.put("inbound_data", jArray);

            Map<String, String> jsonParams;
            // Outbound
            jsonParams = new HashMap<>();
            jsonParams.put("item_id", label_detail.getString("lbl_part_no"));
            jsonParams.put("item_name", label_detail.getString("lbl_part_name").trim());
            jsonParams.put("customer_id", label_detail.getString("lbl_supplier_id").trim().equals("null") ? "" : label_detail.getString("lbl_supplier_id").trim());
            jsonParams.put("customer_name", label_detail.getString("lbl_supplier").trim().equals("null") ? "" : label_detail.getString("lbl_supplier").trim());
            jsonParams.put("package_id", label_detail.getString("lbl_unit"));
            jsonParams.put("unit_qty", label_detail.getString("control_unit"));
            jsonParams.put("package_qty", label_detail.getString("issue_qty"));
            jsonParams.put("lot_no", label_detail.getString("lot_no"));
            jsonParams.put("qty", label_detail.getString("issue_stock_qty"));
            jsonParams.put("location_id",  label_detail.getString("last_location_id").trim().equals("null") ? "" : label_detail.getString("last_location_id").trim());
            jsonParams.put("location_name", label_detail.getString("last_location_name").trim().equals("null") ? "" : label_detail.getString("last_location_name").trim());
            jsonParams.put("label_id", label_detail.getString("id"));
            jsonParams.put("status", "2"); // STORE_IN(1)
            jsonParams.put("slip_divide", "4");
            jsonParams.put("create_user_id", Settings.getLoginUser().getId());

            json.put("outbound_data", new JSONObject(jsonParams));

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

                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        String status = jsonObject.getString("status");

                        if (status.equals("success") && jsonObject.getInt("affected_rows") > 0){
                            Log.d(getString(R.string.tag), "new label: " + response);

                            finish();

                        } else {
                            Unblock_button();
                            showError("Change location failed[" + jsonObject.getString("error") + "]!!");
                        }

                    }catch (JSONException e) {
                        Unblock_button();
                        e.printStackTrace();
                    }
                }
            }.execute();

        } catch (Exception e) {
            Unblock_button();
            e.printStackTrace();
        }
    }


    private void search_items() {
        // Initialize dialog
        dialog_search = new Dialog(LabelDetail_Activity.this);
        dialog_search.setContentView(R.layout.dialog_searchable_spinner);
        dialog_search.getWindow().setLayout(300, 300);
        dialog_search.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
        dialog_search.show();
        // Initialize and assign variable
        EditText editText = dialog_search.findViewById(R.id.edit_text);
        ListView listView = dialog_search.findViewById(R.id.list_view);

//         Initialize array adapter
        ArrayAdapter<String> adapter = new ArrayAdapter<>
                (LabelDetail_Activity.this, android.R.layout.simple_list_item_1, Settings.getList_item());

        // set adapter
        listView.setAdapter(adapter);
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                adapter.getFilter().filter(s);
//                Filter_data(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String item_code = adapter.getItem(position);
                txt_part_no.setText(item_code);
                if (Settings.getMap_items().containsKey(item_code)){
                    ItemMaster_list item = Settings.getMap_items().get(item_code);
                    txt_part_name.setText(item.getItem_name());
                }
                Get_Packing(str_part_no,str_unit_qty);

                if (Settings.getMap_packing().containsKey(item_code)){
                    PackingStandard_list box = Settings.getMap_packing().get(item_code);
                    edt_qty_per_box.setText(box.getQty());
                    Log.d(getString(R.string.tag), "edt_qty_per_box: " + box.getQty());
                }
                dialog_search.dismiss();
            }
        });
    }

//    private void Filter_data() {
//        Filter_data("");
//    }
//
//    private void Filter_data(String keyword) {
//        itemSchedule_adapter = new ItemSchedule_Adapter(
//                doFilter(keyword)
//                , this, str_header, str_type);
//        recyclerView.setAdapter(null);
//        recyclerView.setAdapter(itemSchedule_adapter);
//    }

    @Override
    public void processData(String data, DecodeResult.Result result, String codeType) {
//        if (data.trim().equals("")|| !action_type.trim().equals(ActionType.Type.RELABELING.toString()))
//            return;

        if (data.trim().equals(""))
            return;
        try {
            Log.d(getString(R.string.tag), "data scan: " + data);
            String[] tokens = data.split(getString(R.string.DELIMITER_SCAN_TOKEN),-1);
            Log.d(getString(R.string.tag), Arrays.deepToString(tokens));

            if (tokens.length == 7){
                if (action_type.trim().equals(ActionType.Type.RELABELING.toString())) {
                    Label_Inquiry(tokens[0].trim(), tokens[1].trim(), tokens[3].trim(), tokens[6].trim());
                }

            } else {
                if (action_type.trim().equals(ActionType.Type.LABEL_SCHEDULE.toString())) {
                    if (txt_part_no.getText().toString().trim().equals("")) {
                        new SweetAlertDialog(LabelDetail_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("WARNING")
                                .setContentText("Please select parts no.")
                                .show();
                        return;
                    }

                    //check ETG label
                    String ETG_part_no = tokens[0].trim().substring(4, 11);
                    Log.e(getString(R.string.tag), "ETG_part_no: " + ETG_part_no);
                    String select_part = txt_part_no.getText().toString().trim().substring(4,11);
                    Log.e(getString(R.string.tag), "select_part: " + select_part);


                    if (ETG_part_no.trim().equals(select_part)) {
                        ETG_label = true;
                        txt_etg.setVisibility(View.VISIBLE);

                    }else {
                        new SweetAlertDialog(LabelDetail_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("WARNING")
                        .setContentText("ETG label not match!!")
                        .show();
                    }
                }
            }
            Utils.hideKeyboardFrom(getApplicationContext(), default_view);

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

    private void Label_Inquiry(String order_no, String parts_no, String lot_no, String box) {
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "RELABELING/LABEL/INQUIRY");
            json.put("order_no", order_no);
            json.put("parts_no", parts_no);
            json.put("lot_no", lot_no);
            json.put("serial_no", box);

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

                    try{
                        JSONObject jsonObject = new JSONObject(response);
                        String value = jsonObject.getString("value");
                        JSONArray jArray = new JSONArray(value);

                        if (jArray.length() == 0){
                            new SweetAlertDialog(LabelDetail_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("WARNING")
                                    .setContentText("Not found label!!")
                                    .show();
                            return;
                        }

                        if (action_type.trim().equals(ActionType.Type.RELABELING.toString())){
                            int status =  jArray.getJSONObject(0).getInt("status");
                            if (status != 2){
                                new SweetAlertDialog(LabelDetail_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                        .setTitleText("WARNING")
                                        .setContentText("Invalid label status!!")
                                        .show();
                                return;
                            }
                        }
                        label_detail = jArray.getJSONObject(0);
                        ref_label_id = jArray.getJSONObject(0).getString("id").trim();
                        txt_order_date.setText(DatetimeUtil.changeDateFormat(jArray.getJSONObject(0).getString("lbl_date"),"yyyy-MM-dd", "dd/MM/yyyy"));
                        txt_order_no.setText(jArray.getJSONObject(0).getString("lbl_order_no").trim());
                        txt_part_no.setText(jArray.getJSONObject(0).getString("lbl_part_no").trim());
                        txt_part_name.setText(jArray.getJSONObject(0).getString("lbl_part_name").trim());
                        edt_lot_no.setText(jArray.getJSONObject(0).getString("lot_no").trim());

                        String issue_qty = jArray.getJSONObject(0).getString("issue_qty").trim();
                        String qty_per_box = jArray.getJSONObject(0).getString("qty_per_box").trim().equals("null") ? jArray.getJSONObject(0).getString("issue_qty").trim():jArray.getJSONObject(0).getString("qty_per_box").trim();
                        ;
                        Log.d(getString(R.string.tag), "qty_per_box: " + qty_per_box);
                        Log.d(getString(R.string.tag), "issue_qty: " + issue_qty);
                        txt_qty.setText(decimal_comma_fm.format(Double.parseDouble(issue_qty)));
                        txt_per_box_old.setText(decimal_comma_fm.format(Double.parseDouble(qty_per_box)));

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

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

    private void Clear_layout() {
        b_confirm = false;
        ETG_label = false;
        txt_etg.setVisibility(View.GONE);

        if (action_type.trim().equals(ActionType.Type.LABEL_SCHEDULE.toString())){//LABEL_SCHEDULE
            edt_qty_per_box.setText(str_qty_per_box);
            edt_act_qty.setText("");

        }else if (action_type.trim().equals(ActionType.Type.LABEL_MANUAL.toString())){//label manual
            txt_part_no.setText("");
            txt_part_name.setText("");
            edt_qty_per_box.setText(str_qty_per_box);
            edt_act_qty.setText("");

        }else {//Relabeling
            txt_order_date.setText("");
            txt_order_no.setText("");
            txt_part_no.setText("");
            txt_part_name.setText("");
            edt_lot_no.setText("");
            txt_qty.setText("");
            txt_per_box_old.setText("");
            edt_outbound_qty.setText("");

        }
    }


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

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode >= KeyMapping.P1.getId()
                && keyCode <= KeyMapping.P4.getId())
        {
            switch (KeyMapping.fromId(keyCode)) {
                case P1:
                    finish();
                    break;

                case P2://reprint
                    if (action_type.trim().equals(ActionType.Type.LABEL_SCHEDULE.toString())) {
                        if (str_status.trim().equals("COMPLETED")) {
                            if (b_confirm == false) {
                                Block_button();
                                ButtonClick = ActionType.ButtonClick.REPRINT.toString();
                                Check_Qty();
                            }
                        }
                    }
                    break;

                case P3:
                    Clear_layout();
                    break;

                case P4://confirm
                    if (b_confirm == false) {
                        Block_button();
                        ButtonClick = ActionType.ButtonClick.CONFIRM.toString();
                        Check_Qty();
                    }

                    break;
            }
        }

        return super.onKeyUp(keyCode, event);
    }

}