package com.tomas.ht_ydt;

import android.app.Dialog;
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.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.keyence.autoid.sdk.scan.DecodeResult;
import com.tomas.ht_ydt.ListData.Location_list;
import com.tomas.ht_ydt.ListData.Payload_list;
import com.tomas.ht_ydt.lib.ActionType;
import com.tomas.ht_ydt.lib.AlertProgress;
import com.tomas.ht_ydt.lib.KeyMapping;
import com.tomas.ht_ydt.lib.Scanner;
import com.tomas.ht_ydt.lib.Settings;
import com.tomas.ht_ydt.lib.common.AsyncHttpClient;
import com.tomas.ht_ydt.lib.common.AsyncTcpClient;
import com.tomas.ht_ydt.lib.common.Utils;

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

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

import cn.pedant.SweetAlert.SweetAlertDialog;

public class ChangeLocation_Activity extends Scanner implements View.OnClickListener{
    TextView txt_user, txt_device,txt_parts_no, txt_parts_name, txt_lot_no
            , txt_old_location, txt_stock_qty, txt_control_unit, txt_control_unit2;
    EditText edt_actual_qty;
    Button btn_confirm, btn_clear;
    ImageButton imb_back;
    JSONObject first_label = null, second_label = null;
    String str_lot_no, l_location, l_part_no, new_location_name, str_serial_no, str_part_no, str_label_id;
    List<Payload_list> payload_list;
    int LABEL_QTY;
    AlertProgress alert;
    boolean print_label = false;
    DecimalFormat decimalFormat;
    Dialog dialog;
    Spinner spinner_new_location;

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

        second_label = null;
        new_location_name = "";
        payload_list = new ArrayList<Payload_list>();
        alert = new AlertProgress(ChangeLocation_Activity.this);

        decimalFormat = new DecimalFormat("#,##0.00");

        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());

        txt_parts_no = (TextView) findViewById(R.id.txt_parts_no);
        txt_parts_name = (TextView) findViewById(R.id.txt_parts_name);
        txt_lot_no = (TextView) findViewById(R.id.txt_lot_no);
        txt_old_location = (TextView) findViewById(R.id.txt_old_location);
        txt_stock_qty = (TextView) findViewById(R.id.txt_stock_qty);
        txt_control_unit = (TextView) findViewById(R.id.txt_control_unit);
        txt_control_unit2 = (TextView) findViewById(R.id.txt_control_unit2);
        spinner_new_location = (Spinner) findViewById(R.id.spinner_new_location);
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>
                (getApplicationContext(), R.layout.spinner_list, Settings.getList_location());
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner_new_location.setAdapter(dataAdapter);
        spinner_new_location.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                String select = spinner_new_location.getSelectedItem().toString().trim();
                Location_list list = Settings.getMap_location().get(select);
                new_location_name = list.getName();
                Log.d(getString(R.string.tag), "new_location_name:" + new_location_name);
            }

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

            }
        });

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

        btn_confirm = (Button) findViewById(R.id.btn_confirm);
        btn_clear = (Button) findViewById(R.id.btn_clear);
        imb_back = (ImageButton) findViewById(R.id.imb_back);

    }

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

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

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

        }
    }

    @Override
    public void processData(String data, DecodeResult.Result result, String codeType) {
        if (data.trim().equals(""))
            return;
        try {
            Log.d(getString(R.string.tag), "data read:" + data);

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

            if (tokens.length == 4){
                spinner_new_location.setEnabled(true);
                str_part_no = tokens[0].trim();
                str_lot_no = tokens[1].trim();
                str_serial_no = tokens[2].trim();
                str_label_id = tokens[3].trim();
                getLabelDetail();

            }else if(tokens.length == 2){//scan location [LOCATION CODE] │[ITEM CODE1],[ITEM CODE2],…
                String[] tokens_lo = data.split(getString(R.string.DELIMITER_SCAN_TOKEN),-1);
                Log.d(getString(R.string.tag), Arrays.deepToString(tokens_lo));
                l_location = tokens[0].trim();
                l_part_no = tokens[1].trim();
                String[] tokens_part = l_part_no.split(",",-1);

                if (Settings.getMap_location().containsKey(l_location)) {
                    Boolean search = false;
                    if (l_part_no.trim().equals("")) {//free location
                        spinner_new_location.setSelection(Settings.getList_location().indexOf(l_location));

                    } else {
                        for (int i = 0; i < tokens_part.length; i++) {
                            if (str_part_no.trim().equals(tokens_part[i])) {
                                search = true;
                                Location_list list = Settings.getMap_location().get(l_location);
                                spinner_new_location.setSelection(Settings.getList_location().indexOf(l_location));
                                new_location_name = list.getName();
                                Log.d(getString(R.string.tag), "new_location_name:" + new_location_name);
                                break;
                            } else {
                                search = false;
                            }
                        }//for

                        if (search == false) {
                            showWarning("not found location!");
                            return;
                        }
                    }
                }else {
                    showWarning("Location not found!");
                }
            }else {
                showWarning("Invalid QR code!!");
            }

            Utils.hideKeyboardFrom(getApplicationContext(), default_view);

        }catch (Exception e) {
            Log.e(getString(R.string.tag), "ERROR: " + e.getMessage());
        }
    }
    private void getLabelDetail() {
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "LABEL/STOCK/SUMMARY");
            json.put("parts_no", str_part_no);
            json.put("lot_no", str_lot_no);
            json.put("id", str_label_id);

            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{
                        JSONArray jArray = new JSONArray(response);
                        if (jArray.length() != 1) {
                            showWarning("Invalid label!!");
                            return;
                        }

                        JSONObject label = jArray.getJSONObject(0);

                        if (first_label == null && label.getInt("status")==2){//first scan label
                            first_label = label;
                            txt_parts_no.setText(label.getString("lbl_part_no").trim());
                            txt_parts_name.setText(label.getString("lbl_part_name").trim());
                            txt_lot_no.setText(label.getString("lot_no").trim());
                            txt_control_unit.setText(label.getString("control_unit").trim());
                            txt_control_unit2.setText(label.getString("control_unit"));
                            txt_stock_qty.setText(decimalFormat.format(Double.parseDouble(label.getString("act_stock_qty"))));
                            txt_old_location.setText(label.getString("last_location_id").trim());
//                            spinner_new_location.setSelection(Settings.getList_location().indexOf(label.getString("location_fix_id").trim()));

                        }else if (first_label != null && label.getInt("status") == 2
                                && first_label.getString("id").equalsIgnoreCase(label.getString("id"))){//second scan label
                            second_label = label;
                            txt_control_unit2.setText(label.getString("control_unit"));
                            edt_actual_qty.setText(label.getString("act_stock_qty"));
                            edt_actual_qty.setEnabled(false);

                        }else if (first_label != null && label.getInt("status") == 2
                                && !first_label.getString("id").equalsIgnoreCase(label.getString("id"))){//new  first scan label
                            first_label = label;
                            txt_parts_no.setText(label.getString("lbl_part_no").trim());
                            txt_parts_name.setText(label.getString("lbl_part_name").trim());
                            txt_lot_no.setText(label.getString("lot_no").trim());
                            txt_control_unit.setText(label.getString("control_unit").trim());
                            txt_control_unit2.setText(label.getString("control_unit"));
                            txt_stock_qty.setText(decimalFormat.format(Double.parseDouble(label.getString("act_stock_qty"))));
                            txt_old_location.setText(label.getString("last_location_id").trim());
//                            spinner_new_location.setSelection(Settings.getList_location().indexOf(label.getString("location_fix_id").trim()));


                        }else{
                            if (first_label != null) {
                                if (!first_label.getString("id").equalsIgnoreCase(label.getString("id"))) {
                                    showError("Label  mismatched!!");
                                    return;
                                }
                            } else {
                                showError("Invalid label status!!");
                                return;
                            }
                        }

                        btn_clear.setEnabled(true);
                        btn_clear.setBackgroundResource(R.drawable.button_background_yellow);
                        btn_confirm.setEnabled(true);
                        btn_confirm.setBackgroundResource(R.drawable.button_background_blue);


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

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

    private void reset_view() {
        btn_confirm.setEnabled(false);
        btn_confirm.setBackgroundResource(R.drawable.button_background_gray);
        btn_clear.setEnabled(false);
        btn_clear.setBackgroundResource(R.drawable.button_background_gray);

        txt_parts_no.setText("");
        txt_parts_name.setText("");
        txt_lot_no.setText("");
        txt_stock_qty.setText("");
        txt_control_unit.setText("");
        txt_control_unit2.setText("");
        txt_old_location.setText("");
        edt_actual_qty.setText("");
        edt_actual_qty.setEnabled(true);
        spinner_new_location.setEnabled(false);
        new_location_name = "";

        first_label =  null;
        second_label = null;
        print_label = false;

    }

    private void Confirm() {
        Log.d(getString(R.string.tag), "old label: " + first_label.length());
        //check loccation
        if (txt_old_location.getText().toString().trim().equals(spinner_new_location.getSelectedItem().toString())){
            showWarning("Can't move same location!!");
            return;
        }

        if (!edt_actual_qty.getText().toString().trim().equals("") && !edt_actual_qty.getText().toString().trim().equals("0") ){
            if (second_label == null){
                //check move qty != stock qty

                Double stock_qty = Double.parseDouble(txt_stock_qty.getText().toString().trim().replaceAll(",",""));
                Double move_qty = Double.parseDouble(edt_actual_qty.getText().toString().trim());
                if (move_qty >= stock_qty){
                    print_label = false;
                    showWarning("Move qty error!!");
                    return;
                }else {
                    print_label = true;
                }
            }
            SweetAlertDialog d = new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE);
            d.setCancelable(false);
            d.setTitleText("WARNING");
            d.setContentText("Click YES to confirm the location change?");
            d.setCancelText("No");
            d.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                @Override
                public void onClick(SweetAlertDialog sDialog) {
                    sDialog.dismiss();
                }
            });
            d.setConfirmText("Yes");
            d.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                @Override
                public void onClick(SweetAlertDialog sDialog) {
                    sDialog.dismiss();
                    if (second_label == null) {
                        Prepare_Label();

                    }else {
                        MoveAllLocation();
                    }
                }
            });
            d.show();

        }else {
            showWarning("Please complete the information!");

        }
    }

    private void MoveAllLocation() {
        Log.d(getString(R.string.tag), "MoveAllLocation: " );
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "CHANGE_LOCATION/UPDATE");
            Map<String, String> jsonParams;

            // Inbound
            JSONArray jArray = new JSONArray();
            jsonParams = new HashMap<>();
            jsonParams.put("ref_sch_id","");
            jsonParams.put("item_id", second_label.getString("lbl_part_no"));
            jsonParams.put("item_name", second_label.getString("lbl_part_name").trim());
            jsonParams.put("supplier_id", second_label.getString("lbl_supplier_id"));
            jsonParams.put("supplier_name", second_label.getString("lbl_supplier"));
            jsonParams.put("package_id", second_label.getString("lbl_unit"));
            jsonParams.put("unit_qty", second_label.getString("control_unit"));
            jsonParams.put("package_qty", second_label.getString("issue_qty"));
            jsonParams.put("lot_no", second_label.getString("lot_no"));
            jsonParams.put("qty", edt_actual_qty.getText().toString());
            jsonParams.put("location_id", spinner_new_location.getSelectedItem().toString());
            jsonParams.put("location_name",new_location_name);
            jsonParams.put("label_id", second_label.getString("id"));
            jsonParams.put("inspection_flg", "0");
            jsonParams.put("status", "1"); // STORE_IN(1)
            jsonParams.put("slip_divide", "3");
            jsonParams.put("create_user_id", Settings.getLoginUser().getId());
            JSONObject jsonObject = new JSONObject(jsonParams);
            jArray.put(jsonObject);
            json.put("inbound_data",jArray);

            // Outbound
            jsonParams = new HashMap<>();
            jsonParams.put("item_id", first_label.getString("lbl_part_no"));
            jsonParams.put("item_name", first_label.getString("lbl_part_name"));
            jsonParams.put("customer_id", first_label.getString("lbl_supplier_id"));
            jsonParams.put("customer_name", first_label.getString("lbl_supplier"));
            jsonParams.put("package_id", first_label.getString("lbl_unit"));
            jsonParams.put("unit_qty", first_label.getString("control_unit"));
            jsonParams.put("package_qty", first_label.getString("issue_qty"));
            jsonParams.put("lot_no", first_label.getString("lot_no"));
            jsonParams.put("qty", edt_actual_qty.getText().toString());
            jsonParams.put("location_id", first_label.getString("last_location_id"));
            jsonParams.put("location_name", Settings.getMap_location().get(first_label.getString("last_location_id").trim()).getName());
            jsonParams.put("label_id", first_label.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") + "/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.equals("success") && jsonObject.getInt("affected_rows") == 2){
                            Log.d(getString(R.string.tag), "new label: " + response);
                            reset_view();
                            showSuccess("Change location completed.");

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

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

                }
            }.execute();

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

    private void Prepare_Label() {
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "CHANGE_LOCATION/CONFIRM/PREPARE");
            json.put("ref_label_id", first_label.getString("id"));
            json.put("new_qty", edt_actual_qty.getText().toString().trim());
            json.put("user_id",Settings.getLoginUser().getId());
            json.put("lot_no", first_label.getString("lot_no"));
            json.put("package_id", first_label.getString("lbl_unit"));
            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");
                            showError(error);

                        }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 content_label = i == 0 ? "LABEL-RE" : "LABEL";
                                payload_list.add(new Payload_list(
                                        jArray.getJSONObject(i).getString("id"),
                                        content_label,
                                        jArray.getJSONObject(i).getString("payload"),
                                        jArray.getJSONObject(i).getString("issue_qty"),
                                        jArray.getJSONObject(i).getString("reprint_ref_id")));
                            }
                            //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")){
                                    showWarning("Please setting printer");

                                }else {
                                    Print_Label();
                                }
                            }
                        }
                    }catch (JSONException e) {
                        showError(e.getMessage());
                    }
                }
            }.execute();

        }catch (JSONException e) {
            showError(e.getMessage());
        }
    }

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

        String tmp_label = "";
        for (int i = 0; i < payload_list.size(); i++) {
            Payload_list payload_l = payload_list.get(i);
            String payload = payload_l.getPayload();
            String content_label = payload_l.getContent_label();
            String tmp = String.format(
                    "%s %s-%s%s\n%s"
                    , "PST"
                    , Settings.getPrinter()
                    , content_label
                    , ""
                    , payload+"\n");

            tmp_label = (tmp_label + tmp);


            Log.e(getString(R.string.tag), "payload tmp: " + tmp);
            }
            Log.e(getString(R.string.tag), "payload tmp_label: " + tmp_label);

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

                new AsyncTcpClient(getApplicationContext(),
                        Settings.getMgmtList().get("lpc_host"),
                        Integer.parseInt(Settings.getMgmtList().get("lpc_port")),
                        tmp_label+"\n\n\n"
                ) {
                    @Override
                    protected void onFinished(String response) {
                        Log.d(getString(R.string.tag), "TCP response: " + response);

                        if (response.equals("OK")) {
                            alert.dismiss();
                            AlertConfirmPrint();

                        } else {
                            alert.dismiss();
//                            Unblock_button();
                            showError("Can't connect to print server");
                        }
                    }
                }.execute();
                throw new JSONException(err_msg);

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

    }

    private void AlertConfirmPrint() {
        try {
            SweetAlertDialog d = new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE);
            d.setCancelable(false);
            d.setTitleText("WARNING");
            d.setContentText("Click 'No' if nothing printed out?");
            d.setCancelText("No");
            d.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                @Override
                public void onClick(SweetAlertDialog sDialog) {
                    sDialog.dismiss();
                }
            });
            d.setConfirmText("Yes");
            d.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                @Override
                public void onClick(SweetAlertDialog sDialog) {
                    sDialog.dismiss();
                    Confirm_Label();
                }
            });
            d.show();
        }catch (WindowManager.BadTokenException e) {
            showWarning("Please check the label status on Pegasus!");

        } catch (Exception e){
            showWarning("Please check the label status on Pegasus!");
        }
    }

    private void Confirm_Label() {
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "CHANGE_LOCATION/CONFIRM/CONFIRM");
            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){
                            //SUCCESS
                            UpdateLocation();
                        }else {
                            String error = jsonObject.getString("error");
                            showError(error);
                        }
                    }catch (JSONException e) {
                        showError(e.getMessage());
                    }
                }
            }.execute();

        }catch (JSONException e) {
            showError(e.getMessage());
        }
    }

    private void UpdateLocation() {
        Log.d(getString(R.string.tag), "UpdateLocation: " );
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "CHANGE_LOCATION/UPDATE");

            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("ref_sch_id","");
                jsParams.put("item_id", first_label.getString("lbl_part_no"));
                jsParams.put("item_name", first_label.getString("lbl_part_name").trim());
                jsParams.put("supplier_id", first_label.getString("lbl_supplier_id").trim().equals("null") ? "" : first_label.getString("lbl_supplier_id").trim());
                jsParams.put("supplier_name", first_label.getString("lbl_supplier").trim().equals("null") ? "" : first_label.getString("lbl_supplier").trim());
                jsParams.put("package_id", first_label.getString("lbl_unit"));
                jsParams.put("unit_qty", first_label.getString("control_unit"));
                jsParams.put("lot_no", first_label.getString("lot_no"));
                jsParams.put("package_qty", list.getQty());
                jsParams.put("qty", list.getQty());

                if (i == 0){
                    String old_location = txt_old_location.getText().toString();
                    jsParams.put("location_id",old_location );
                    jsParams.put("location_name",Settings.getMap_location().get(old_location).getName());
                }else {
                    jsParams.put("location_id", spinner_new_location.getSelectedItem().toString());
                    jsParams.put("location_name",new_location_name);
                }
                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("ref_sch_id","");
            jsonParams.put("item_id", first_label.getString("lbl_part_no"));
            jsonParams.put("item_name", first_label.getString("lbl_part_name").trim());
            jsonParams.put("customer_id", first_label.getString("lbl_supplier_id").trim().equals("null") ? "" : first_label.getString("lbl_supplier_id").trim());
            jsonParams.put("customer_name", first_label.getString("lbl_supplier").trim().equals("null") ? "" : first_label.getString("lbl_supplier").trim());
            jsonParams.put("package_id", first_label.getString("lbl_unit"));
            jsonParams.put("unit_qty", first_label.getString("control_unit"));
            jsonParams.put("package_qty", first_label.getString("issue_qty"));
            jsonParams.put("lot_no", first_label.getString("lot_no"));
            jsonParams.put("qty", txt_stock_qty.getText().toString().replace(",",""));
            jsonParams.put("location_id", first_label.getString("last_location_id"));
            jsonParams.put("location_name", Settings.getMap_location().get(first_label.getString("last_location_id").trim()).getName());
            jsonParams.put("label_id", first_label.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") + "/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.equals("success") && jsonObject.getInt("affected_rows") > 0){
                            Log.d(getString(R.string.tag), "new label: " + response);
                            showSuccess("Change location completed.");
                            reset_view();


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

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

                }
            }.execute();

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

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

                case P3:
                    btn_clear.performClick();
                    break;

                case P4:
                    btn_confirm.performClick();
                    break;
            }
        }

        return super.onKeyUp(keyCode, event);
    }

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