package com.tomas.ht_mast;

import androidx.appcompat.app.AppCompatActivity;

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

import com.keyence.autoid.sdk.scan.DecodeResult;
import com.tomas.ht_mast.ListData.Location_list;
import com.tomas.ht_mast.ListData.Payload_list;
import com.tomas.ht_mast.ListData.Supplier_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.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.LinkedHashMap;
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, txt_new_location;
    EditText edt_actual_qty;
//    Spinner spinner_location;
    Button btn_confirm, btn_clear;
    JSONObject first_label = null, second_label = null;
//    Map<String, JSONObject> allow_locations;
    String str_lot_no, l_location, l_part_no, new_location_name, str_serial_no, str_part_no;
    List<Payload_list> payload_list;
//    int scan_label = 0;
    int LABEL_QTY, PRINT_TIMES;
    AlertProgress alert;
    boolean print_label = false;
    private volatile boolean stopThread = true;
    DecimalFormat decimalFormat;
    Dialog dialog;

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

        stopThread = true;
        second_label = null;
        new_location_name = "";
//        allow_locations = new LinkedHashMap<>();
        payload_list = new ArrayList<Payload_list>();
        alert = new AlertProgress(ChangeLocation_Activity.this);

        decimalFormat = new DecimalFormat("#,#00.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);
        txt_new_location = (TextView) findViewById(R.id.txt_new_location);
        txt_new_location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                search_location();
            }
        });

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

//        spinner_location = (Spinner) findViewById(R.id.spinner_location);
//        spinner_location.setEnabled(false);

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

//        Get_Location();

    }

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

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

        // 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);
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String location = adapter.getItem(position);

                if (Settings.getMap_location().containsKey(location)){
                    Location_list list = Settings.getMap_location().get(location);
                    txt_new_location.setText(location);
                    new_location_name = list.getName();
                    dialog.dismiss();
                }

                Log.d(getString(R.string.tag), "new_location_name:" + new_location_name);
            }
        });
    }

    @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 == 7){
                txt_new_location.setEnabled(true);
                str_part_no = tokens[1];
                str_serial_no= tokens[6];
                str_lot_no = tokens[3];
                getLabelDetail();

            }else if (tokens.length == 3){//scan location
                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_lo[0].trim();
                l_part_no = tokens_lo[1].trim();

                if (Settings.getMap_location().containsKey(l_location)){
                    Location_list list = Settings.getMap_location().get(l_location);
                    txt_new_location.setText(l_location);
                    new_location_name = list.getName();
                    Log.d(getString(R.string.tag), "new_location_name:" + new_location_name);
                }else {
                    new SweetAlertDialog(ChangeLocation_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("WARNING")
                            .setContentText("not found location!")
                            .show();
                }

            }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("serial_no", str_serial_no);

            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_stock_qty.setText(decimalFormat.format(Double.parseDouble(label.getString("act_stock_qty"))));
                            txt_old_location.setText(label.getString("last_location_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_stock_qty.setText(decimalFormat.format(Double.parseDouble(label.getString("act_stock_qty"))));
                            txt_old_location.setText(label.getString("last_location_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();
        }
    }

    @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;

        }
    }

    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);
        txt_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());
        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;
                    new SweetAlertDialog(ChangeLocation_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                        .setTitleText("WARNING")
                                        .setContentText("Move qty error!!")
                                        .show();
                    return;
                }else {
                    print_label = true;
                }
            }

            new SweetAlertDialog(ChangeLocation_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("WARNING")
                    .setContentText("Click YES to confirm the location change?")
                    .setCancelText("No")
                    .showCancelButton(true)
                    .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sDialog) {
                            sDialog.cancel();
                        }
                    })
                    .setConfirmText("Yes")
                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sDialog) {
                            sDialog.cancel();

                            if (second_label == null) {
                                Prepare_Label();

                            }else {
                                MoveAllLocation();
                            }
                        }
                    })
                    .show();
        }else {
            new SweetAlertDialog(ChangeLocation_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("WARNING")
                    .setContentText("Please complete the information!")
                    .show();
        }
    }

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

            // Inbound
            JSONArray jArray = new JSONArray();
            jsonParams = new HashMap<>();
            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", txt_new_location.getText().toString().trim());
            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("location_name", allow_locations.get(first_label.getString("last_location_id")).getString("name"));
            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") + "/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") == 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("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(ChangeLocation_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(error)
                                    .show();
                        }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++){
                                payload_list.add(new Payload_list(
                                        jArray.getJSONObject(i).getString("id"),
                                        jArray.getJSONObject(i).getString("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(ChangeLocation_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                            .setTitleText("WARNING")
                                            .setContentText("Please setting printer")
                                            .show();
                                }else {
                                    Command_Print();
                                }
                            }
                        }
                    }catch (JSONException e) {
                        new SweetAlertDialog(ChangeLocation_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

        }catch (JSONException e) {
            new SweetAlertDialog(ChangeLocation_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(4000);
                    Log.d("Thread.sleep2", "stopThread: " + stopThread);

                } 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("Thread.sleep if", "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();
                        new SweetAlertDialog(ChangeLocation_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(ChangeLocation_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) {
                        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();
            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");
                            new SweetAlertDialog(ChangeLocation_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(error)
                                    .show();
                        }
                    }catch (JSONException e) {
                        new SweetAlertDialog(ChangeLocation_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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

    private void UpdateLocation() {
        Log.d(getString(R.string.tag), "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", 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("package_qty", first_label.getString("issue_qty"));
                jsParams.put("lot_no", first_label.getString("lot_no"));
                jsParams.put("qty", list.getQty());
                jsParams.put("location_id", txt_new_location.getText().toString().trim());
                jsParams.put("location_name",new_location_name);
//                jsParams.put("location_id", spinner_location.getSelectedItem().toString().trim());
//                jsParams.put("location_name", allow_locations.get(spinner_location.getSelectedItem().toString()).getString("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("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", allow_locations.get(first_label.getString("last_location_id")).getString("name"));
            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") + "/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);
                            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
    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 P3:
                    reset_view();
                    break;

                case P4://confirm
                    Confirm();
                    break;
            }
        }

        return super.onKeyUp(keyCode, event);
    }
}