package com.tomas.ht_ydt;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Context;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.activity.EdgeToEdge;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.keyence.autoid.sdk.scan.DecodeResult;
import com.tomas.ht_ydt.Adapter.Rework_Adapter;
import com.tomas.ht_ydt.ListData.LabelItem_list;
import com.tomas.ht_ydt.ListData.OutBom_list;
import com.tomas.ht_ydt.ListData.OutProdFIFO;
import com.tomas.ht_ydt.ListData.Rework_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.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class NGInProcess_Activity extends Scanner implements View.OnClickListener, ClickItem_Rework  {
    //outbound from assy to inbound ng location

    TextView txt_user, txt_device, txt_part_no, txtc_part_no, txtc_unit;
    EditText edtc_qty, edtc_lot_no;
    Button btn_confirm, btn_clear;
    ImageButton imb_back;
    Spinner spinner_location;
    RecyclerView view_data;
    LinearLayout layout_edit;
    Calendar calendar;
    SimpleDateFormat date, date_time_fm;
    AlertProgress alert;
    String str_today, str_lot_no, str_part_no, bf_change_lot, bf_change_qty, material_parts_no, str_order;
    boolean b_confirm, edit_qty;
    Map<String, Rework_List> map_item_rework;
    Map<String, LabelItem_list> map_label_confirm;
    List<Rework_List> rework_lists;
    JSONArray j_schedules;
    Rework_Adapter reworkAdapter;
    Map<String, OutProdFIFO>map_out_fifo;

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

        b_confirm = false;
        edit_qty = false;

        map_item_rework = new LinkedHashMap<>();
        rework_lists = new ArrayList<Rework_List>();
        map_out_fifo = new LinkedHashMap<>();
        map_label_confirm = new LinkedHashMap<>();

        alert = new AlertProgress(NGInProcess_Activity.this);
        calendar = Calendar.getInstance();
        date = new SimpleDateFormat("yyyy-MM-dd");
        date_time_fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        str_today = date.format(calendar.getTime());

        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_part_no = (TextView) findViewById(R.id.txt_part_no);

        spinner_location = (Spinner)findViewById(R.id.spinner_location);
        ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>
                (getApplicationContext(), R.layout.spinner_list, Settings.getList_location_ng());
        dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spinner_location.setAdapter(dataAdapter);

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

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

        layout_edit = (LinearLayout) findViewById(R.id.layout_edit);
        txtc_part_no = (TextView) findViewById(R.id.txtc_part_no);
        txtc_unit = (TextView) findViewById(R.id.txtc_unit);
        edtc_qty = (EditText) findViewById(R.id.edtc_qty);

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

                final Calendar currentDate = Calendar.getInstance();
                new DatePickerDialog(NGInProcess_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')));
                        edtc_lot_no.setText(str_lot_no);
                    }
                }, currentDate.get(Calendar.YEAR), currentDate.get(Calendar.MONTH), currentDate.get(Calendar.DATE)).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();
                        Check_Stock();
                }

                break;

            case R.id.btn_ok:
                hideKeyboard(this);
                layout_edit.setVisibility(View.GONE);
                Update_Bom_list();
                break;

            case R.id.btn_cancel:
                hideKeyboard(this);
                layout_edit.setVisibility(View.GONE);
                Clear_layout_edit();
                break;
        }
    }



    private void Clear_layout_edit() {
        material_parts_no = "";
        txtc_part_no.setText("");
        edtc_qty.setText("");
        txtc_unit.setText("");
        edtc_lot_no.setText("");
        bf_change_lot = "";
        bf_change_qty = "";
    }

    private void Clear_layout() {
        edit_qty = false;
        b_confirm = false;
        j_schedules = null;
        map_label_confirm.clear();
        rework_lists.clear();
        map_item_rework.clear();
        txt_part_no.setText("");
        txt_part_no.setText("");
        spinner_location.setSelection(0);
        Clear_layout_edit();
        view_data();
    }

    private void Block_button() {
        b_confirm = true;
        btn_confirm.setEnabled(false);
        btn_confirm.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);
    }

    @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 == 2){
                if (txt_part_no.getText().toString().trim().equals("")){
                    showWarning("Please scan label!");
                    return;
                }
                String location = tokens[0].trim();
                String list_item = tokens[1].trim();
                String[] tokens_part = list_item.split(",",-1);

                if (Settings.getMap_location().containsKey(location)) {//check has location
                    if (list_item.trim().equals("")){//free location
                            spinner_location.setSelection(Settings.getList_location_ng().indexOf(location));

                    }else {
                        Boolean search = false;
                        for (int i = 0; i < tokens_part.length; i++) { //for check part can use
                            if (str_part_no.trim().equals(tokens_part[i])) {
                                search = true;
                                    spinner_location.setSelection(Settings.getList_location_ng().indexOf(location));
                                break;

                            } else {
                                search = false;
                            }
                        }//for

                        if (search == false) {
                            showWarning("Location not match!");
                            return;
                        }
                    }
                }else {
                    showWarning("Location not found!");
                }
            }else if (tokens.length == 4){
                Get_BOM(tokens[0].trim());

            }else {
                showWarning("Invalid QR code!");
            }
            Utils.hideKeyboardFrom(getApplicationContext(), default_view);
        } catch (Exception e) {
            Log.e(getString(R.string.tag), "ERROR: " + e.getMessage());
        }
    }

    private void Get_BOM(String parts_no) {
        map_item_rework.clear();
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "BOM");
            json.put("product_no", parts_no);

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/ht_api.php",
                    json.toString()) {
                @SuppressLint("StaticFieldLeak")
                @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){
                            txt_part_no.setText("");
                            str_part_no = "";
                            showWarning("BOM not found!");

                        }else {
                            for(int i = 0; i < jArray.length(); i++) {

                                map_item_rework.put(jArray.getJSONObject(i).getString("parts_no").trim(),
                                        new Rework_List(
                                                String.valueOf(i+1),
                                                jArray.getJSONObject(i).getString("id").trim(),
                                                jArray.getJSONObject(i).getString("parts_no").trim(),
                                                jArray.getJSONObject(i).getString("parts_name").trim(),
                                                str_today,
                                                "0.00",
                                                jArray.getJSONObject(i).getString("unit_qty").trim()));
                            }
                            str_part_no = parts_no;
                            txt_part_no.setText(str_part_no);
                            Log.d(getString(R.string.tag), "map_item_rework: " + map_item_rework.size());
                            view_data();
                        }
                    }catch (JSONException e) {
                        showError(e.getMessage());
                    }
                }
            }.execute();

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

    private void view_data() {
        rework_lists.clear();
        if (map_item_rework.size() > 0){
            for (String key : map_item_rework.keySet()){
                Rework_List item = map_item_rework.get(key);
                rework_lists.add(
                        new Rework_List(
                                item.getNo(),
                                item.getId(),
                                item.getPart_no(),
                                item.getParts_name(),
                                item.getLot_no(),
                                item.getQty(),
                                item.getUnit()));
            }
        }
        Log.d(getString(R.string.tag), "rework_lists: " + rework_lists.size());
        reworkAdapter = new Rework_Adapter(rework_lists, this, NGInProcess_Activity.this );
        view_data.setAdapter(reworkAdapter);
        Log.d(getString(R.string.tag), "set adapter");

    }

    @Override
    public void Item_Rework(String id, String part_no, String name, String qty, String unit, String lot_no) {
        Log.d(getString(R.string.tag), "click part : "+part_no);
        material_parts_no = part_no;
        bf_change_lot = lot_no;
        bf_change_qty = qty;
        layout_edit.setVisibility(View.VISIBLE);
        txtc_part_no.setText(part_no+"\n"+name);
        edtc_qty.setText(qty);
        txtc_unit.setText(unit);
        edtc_lot_no.setText(lot_no);
    }

    private void Update_Bom_list() {
        Log.d(getString(R.string.tag), "update parts : "+material_parts_no);
        String qty_update = edtc_qty.getText().toString().trim();
        String lot_update = edtc_lot_no.getText().toString().trim();
        qty_update = qty_update.trim().equals("") ? "0" : qty_update.trim();
        Double bf_qty, d_qty_update;
        bf_qty = Double.parseDouble(bf_change_qty);
        d_qty_update = Double.parseDouble(qty_update);

        if (!lot_update.trim().equals(bf_change_lot) || bf_qty > d_qty_update || bf_qty < d_qty_update) {
            edit_qty = true;
            Rework_List item = map_item_rework.get(material_parts_no);
            item.setQty(String.format("%.2f",d_qty_update));
            item.setLot_no(lot_update);
            map_item_rework.put(material_parts_no,item);
        }
        view_data();
        Clear_layout_edit();
    }

    private void Check_Stock() {
        try {
            JSONObject json = new JSONObject();
            Map<String, String> jsonParams = new HashMap<>();

            json.put("cmd", "QUERY/STOCK/CHECK");

            JSONArray jsonArray = new JSONArray();
            for (String key : map_item_rework.keySet()) {
                Rework_List item = map_item_rework.get(key);
                Double qty = Double.parseDouble(item.getQty());
                if (qty > 0) {
                    jsonParams.put("item_id", item.getPart_no());
                    jsonParams.put("section", Settings.getLoginUser().getDepartment());

                    JSONObject jsonObject = new JSONObject(jsonParams);
                    jsonArray.put(jsonObject);
                }
            }
            json.put("value",jsonArray);

            if (jsonArray.length() == 0){
                Unblock_button();
                return;
            }

            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 {
                        int count = 0;
                        String part = "";
                        JSONObject jsonObject = new JSONObject(response);
                        String value = jsonObject.getString("value");
                        JSONArray jArray = new JSONArray(value);
                            Log.d(getString(R.string.tag), "jArray: " + jArray.toString());

                            for (int i = 0; i < jArray.length(); i++) {
                                JSONArray innerArray = jArray.getJSONArray(i);
                                for (int j = 0; j < innerArray.length(); j++) {
                                    JSONObject itemObject = innerArray.getJSONObject(j);
                                    Double sum_qty = itemObject.getDouble("sum_qty");
                                    String item_id = itemObject.getString("item_id").trim();

                                    Rework_List item = map_item_rework.get(item_id);
                                    Double qty = Double.parseDouble(item.getQty());

                                    if (sum_qty < qty){
                                        String s = item_id;
//                                        String s = item_id+" = "+String.valueOf(sum_qty);
                                        part = s +" , "+(part);
                                        count++;
                                    }
                                }//for
                            }//for

                        Log.d(getString(R.string.tag), "count: " + count);
                        if (count > 0){
                            Unblock_button();
                            new SweetAlertDialog(NGInProcess_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("There is not enough stock.")
                                    .setContentText(part)
                                    .show();
                        }else {
//                            Log.d(getString(R.string.tag), "Get_FIFO: ");
                            Get_FIFO();
                        }
                    } catch (JSONException e) {
                        Unblock_button();
                        showError(e.getMessage());
                    }
                }
            }.execute();

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

    private void Get_FIFO() {
        try {
            JSONObject json = new JSONObject();
            Map<String, String> jsonParams = new HashMap<>();

            json.put("cmd", "QUERY/STOCK/FIFO/OUTBOUND");

            JSONArray jsonArray = new JSONArray();
            for (String key : map_item_rework.keySet()) {
                Rework_List item = map_item_rework.get(key);
                Double qty = Double.parseDouble(item.getQty());
                if (qty > 0) {
                    jsonParams.put("parts_no", item.getPart_no());
                    jsonParams.put("qty", item.getQty());
                    jsonParams.put("unit_qty", item.getUnit());
                    jsonParams.put("section", Settings.getLoginUser().getDepartment());

                    JSONObject jsonObject = new JSONObject(jsonParams);
                    jsonArray.put(jsonObject);
                }
            }
            json.put("value",jsonArray);

            if (jsonArray.length() == 0){
                Unblock_button();
                return;
            }

            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");
                        if (value == null || value.trim().equals("null") || value.isEmpty()){
                            finish();
                        }else {

                            JSONArray jArray = new JSONArray(value);
                            Log.d(getString(R.string.tag), "jArray: " + jArray.toString());
                            if (jArray.length() == 0) {
                                Unblock_button();
                                showWarning("Stock not found!");

                            } else {
                                for (int i = 0; i < jArray.length(); i++) {
                                    JSONArray innerArray = jArray.getJSONArray(i);
                                    for (int j = 0; j < innerArray.length(); j++) {
                                        JSONObject itemObject = innerArray.getJSONObject(j);
                                        String item_id = itemObject.getString("item_id").trim();
                                        String lot_no = itemObject.getString("lot_no").trim();
                                        String location_id = itemObject.getString("location_id").trim();
                                        String qty = itemObject.getString("qty").trim();
                                        String key = item_id + lot_no + location_id;

                                        map_out_fifo.put(key,
                                                new OutProdFIFO(
                                                        item_id,
                                                        lot_no,
                                                        location_id,
                                                        qty));

                                    }
                                }
                                OutboundProductionFIFO();
                                Log.d(getString(R.string.tag), "map_out_fifo: " + map_out_fifo.size());
                            }
                        }
                    } catch (JSONException e) {
                        Unblock_button();
                        showError(e.getMessage());
                    }
                }
            }.execute();

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

    }

    private void OutboundProductionFIFO() {
        calendar = Calendar.getInstance();
        calendar = (Calendar) calendar.clone();
        String dt_to_server = date_time_fm.format(calendar.getTime());
        Log.d(getString(R.string.tag), "dt_to_server : " + dt_to_server);
        str_order = "NG-IP "+dt_to_server;
        try {
            JSONObject json = new JSONObject();
            Map<String, String> jsonParams = new HashMap<>();
            json.put("cmd", "OUTBOUND/PRODUCTION/MANUAL/FIFO/CONFIRM");
            JSONArray jsonArray = new JSONArray();

            for (String key : map_out_fifo.keySet()){
                OutProdFIFO item = map_out_fifo.get(key);
                jsonParams.put("order_no", str_order);
                jsonParams.put("item_id",item.getItem_id());
                jsonParams.put("item_name", map_item_rework.get(item.getItem_id()).getParts_name());
                jsonParams.put("lot_no", item.getLot_no());
                jsonParams.put("package_id", map_item_rework.get(item.getItem_id()).getUnit());
                jsonParams.put("unit_qty", map_item_rework.get(item.getItem_id()).getUnit());
                jsonParams.put("package_qty", item.getQty());
                jsonParams.put("qty", item.getQty());
                jsonParams.put("location_id", item.getLocation_id());
                jsonParams.put("inspection_flg", "0");
                jsonParams.put("status", "2"); // OUT_STORE = 3;
                jsonParams.put("slip_divide", "4");
                jsonParams.put("create_user_id", Settings.getLoginUser().getId());
                jsonParams.put("create_dt", dt_to_server);

                JSONObject jsonObject = new JSONObject(jsonParams);
                jsonArray.put(jsonObject);
            }

            json.put("value",jsonArray);
            if (jsonArray.length() == 0)
                return;

            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.equals("success") && affected_rows > 0) {
                            Log.d(getString(R.string.tag), "success: " + response);
                            Prepare_Label();

                        }else{
                            Unblock_button();
                            showWarning("Can't Outbound");
                        }
                    } catch (JSONException e) {
                        Unblock_button();
                        showError(e.getMessage());
                    }
                }
            }.execute();

        } catch (Exception e) {
            Unblock_button();
            showError(e.getMessage());
        }
    }

    private void Prepare_Label() {
        try {
            JSONObject json = new JSONObject();
            Map<String, String> jsonParams = new HashMap<>();

            json.put("cmd", "LABEL/NG_IN_PROCESS/CONFIRM/PREPARE");
            JSONArray jsonArray = new JSONArray();
            for (String key : map_item_rework.keySet()) {
                Rework_List item = map_item_rework.get(key);
                Double qty = Double.parseDouble(item.getQty());
                if (qty > 0) {
                    jsonParams.put("parts_no", item.getPart_no());
                    jsonParams.put("lot_no", item.getLot_no());
                    jsonParams.put("ng_act_qty", item.getQty());
                    jsonParams.put("ng_qty_per_box", item.getQty());
                    jsonParams.put("user_id", Settings.getLoginUser().getId());

                    JSONObject jsonObject = new JSONObject(jsonParams);
                    jsonArray.put(jsonObject);
                }
            }
            json.put("value",jsonArray);

            if (jsonArray.length() == 0) {
                Unblock_button();
                return;
            }

            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);
                            Unblock_button();
                        }else {
                            String value = jsonObject.getString("value");
                            j_schedules = new JSONArray(value);
                            Confirm_Request_Print();

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

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

    private void Confirm_Request_Print() {
        try {
            SweetAlertDialog d = new SweetAlertDialog(NGInProcess_Activity.this, SweetAlertDialog.WARNING_TYPE);
            d.setCancelable(false);
            d.setTitleText("WARNING");
            d.setContentText("Do you want to print label?");
            d.setCancelText("No");
            d.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                @Override
                public void onClick(SweetAlertDialog sDialog) {
                    sDialog.dismiss();
                    Confirm_Label();
                }
            });
            d.setConfirmText("Yes");
            d.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                @Override
                public void onClick(SweetAlertDialog sDialog) {
                    sDialog.dismiss();
                    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")) {
                            Unblock_button();
                            showWarning("Please setting printer");

                        } else {
                            Print_Label();
                        }
                    }
                }
            });
            d.show();
        }catch (WindowManager.BadTokenException e) {
            Unblock_button();
            showWarning("Please check the label status on Pegasus!");

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

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

        String tmp_label = "";
        try {
            for (int i = 0; i < j_schedules.length(); i++) {
                String payload = j_schedules.getJSONObject(i).getString("payload");
                String content_label = j_schedules.getJSONObject(i).getString("content_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());
            }
        } 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();
                    Unblock_button();
                }
            });
            d.setConfirmText("Yes");
            d.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                @Override
                public void onClick(SweetAlertDialog sDialog) {
                    sDialog.dismiss();
                    Confirm_Label();
                }
            });
            d.show();
        } catch (WindowManager.BadTokenException e) {
            Unblock_button();
            showWarning("Please check the label status on Pegasus!");

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

    private void Confirm_Label() {
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "LABEL/MANUAL/CONFIRM/CONFIRM");

            JSONArray jArray = new JSONArray();
            for (int i = 0; i < j_schedules.length(); i++) {
                String label_id = j_schedules.getJSONObject(i).getString("id").trim();
                Map<String, String> jsParams = new HashMap<>();
                jsParams.put("label_id", label_id);
                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){
                            GET_Label_Detail();
                        }else {
                            String error = jsonObject.getString("error");
                            showError(error);
                            Unblock_button();
                        }
                    }catch (JSONException e) {
                        showError(e.getMessage());
                        Unblock_button();
                    }
                }
            }.execute();

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

    private void GET_Label_Detail() {
        map_label_confirm.clear();
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "LABEL/REWORK/DETAIL");
            JSONArray jArray = new JSONArray();
            for (int i = 0; i < j_schedules.length(); i++) {
                String label_id = j_schedules.getJSONObject(i).getString("id").trim();
                Map<String, String> jsParams = new HashMap<>();
                jsParams.put("id", label_id);
                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()) {
                @SuppressLint("StaticFieldLeak")
                @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);
                        Log.d(getString(R.string.tag), "jArray: " + jArray.toString());
                        if (jArray.length() == 0){
                            showError("LABEL/REWORK/DETAIL not found!");

                        }else {
                            for (int i = 0; i < jArray.length(); i++) {
                                JSONArray innerArray = jArray.getJSONArray(i);

                                for (int j = 0; j < innerArray.length(); j++) {
                                    JSONObject itemObject = innerArray.getJSONObject(j);
                                    String id = itemObject.getString("id");

                                    map_label_confirm.put( id,
                                            new LabelItem_list(
                                                    "",
                                                    id,
                                                    itemObject.getString("lot_no"),
                                                    itemObject.getString("serial_no"),
                                                    itemObject.getString("status"),
                                                    itemObject.getString("issue_qty"),
                                                    itemObject.getString("issue_stock_qty"),
                                                    itemObject.getString("act_stock_qty"),
                                                    itemObject.getString("control_unit"),
                                                    itemObject.getString("lbl_supplier_id"),
                                                    itemObject.getString("lbl_supplier"),
                                                    itemObject.getString("lbl_part_no"),
                                                    itemObject.getString("lbl_part_name"),
                                                    itemObject.getString("lbl_unit"),
                                                    itemObject.getString("lbl_ng"),
                                                    itemObject.getString("last_location_id").trim().equals("null")? "" : itemObject.getString("last_location_id").trim(),
                                                    itemObject.getString("last_location_name").trim().equals("null")? "" : itemObject.getString("last_location_name").trim(),
                                                    "",
                                                    "",
                                                    itemObject.getString("lbl_order_no").trim()));

                                    // Do something with the extracted "id" value, e.g., print it to the console:
                                    Log.d(getString(R.string.tag), "id: " + id.toString());
                                }
                            }
                            Log.d(getString(R.string.tag), "map_label : " + map_label_confirm.size());
//
                            Confirm_Inbound();
                        }
                    }catch (JSONException e) {
                        Unblock_button();
                        showError(e.getMessage());
                    }
                }
            }.execute();

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

    private void Confirm_Inbound() {
        try {
            JSONObject json = new JSONObject();
            Map<String, String> jsonParams = new HashMap<>();//sample data
            json.put("cmd", "INBOUND/MANUAL/DETAIL/CONFIRM");
            JSONArray jsonArray = new JSONArray();
            for (String key : map_label_confirm.keySet()){
                LabelItem_list item = map_label_confirm.get(key);
                jsonParams.put("order_no", str_order);
                jsonParams.put("item_id", item.getLbl_part_no());
                jsonParams.put("item_name", item.getLbl_part_name());
                jsonParams.put("supplier_id", item.getLbl_supplier_id().trim().equals("null") ? "" : item.getLbl_supplier_id().trim());
                jsonParams.put("supplier_name", item.getLbl_supplier().trim().equals("null") ? "" : item.getLbl_supplier().trim());
                jsonParams.put("package_id", item.getLbl_unit());
                jsonParams.put("package_qty",item.getIssue_qty());
                jsonParams.put("lot_no", item.getLot_no().trim());
                jsonParams.put("qty",item.getIssue_stock_qty());
                jsonParams.put("unit_qty", item.getControl_unit());
                jsonParams.put("location_id", spinner_location.getSelectedItem().toString().trim());
                jsonParams.put("location_name", Settings.getMap_location().get(spinner_location.getSelectedItem().toString().trim()).getName() );
                jsonParams.put("ref_sch_id", "0");
                jsonParams.put("label_id", item.getLabel_id());
                jsonParams.put("status",  "1");
                jsonParams.put("slip_divide", "3");
                jsonParams.put("create_user_id", Settings.getLoginUser().getId());
                jsonParams.put("inspection_flg", "0");
                jsonParams.put("ng", item.getLbl_ng());

                JSONObject jsonObject = new JSONObject(jsonParams);
                jsonArray.put(jsonObject);
            }
            json.put("value",jsonArray);

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

                        if (status.trim().equals("success") && affected_rows > 0){
                            Log.d(getString(R.string.tag), "success: " + response);
                            new SweetAlertDialog(NGInProcess_Activity.this, SweetAlertDialog.SUCCESS_TYPE)
                                    .setTitleText("INFORMATION")
                                    .setContentText("Operation Completed")
                                    .show();
                            Unblock_button();
                            Clear_layout();

                        }else {
                            String error = jsonObject.getString("error");
                            showError(error);
                            Unblock_button();
                        }
                    }catch (JSONException e) {
                        showError(e.getMessage());
                        Unblock_button();
                    }
                }
            }.execute();
        }catch (Exception e) {
            showError(e.getMessage());
            Unblock_button();
        }
    }

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

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