package com.tomas.ht_ydt;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.keyence.autoid.sdk.scan.DecodeResult;
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.AsyncTcpClient;
import com.tomas.ht_ydt.lib.common.ScrollToTrick;
import com.tomas.ht_ydt.lib.common.Utils;
import com.tomas.ht_ydt.lib.common.AsyncHttpClient;

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

import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.stream.Collectors;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class OutboundDetail_Activity extends Scanner implements View.OnClickListener {
    Calendar calendar;
    SimpleDateFormat date;
    TextView txt_user, txt_device, txt_part_no, txt_part_name, txt_total, txt_date, txtc_unit, txt_message;
    EditText edtc_qty;
    Button btn_confirm, btn_clear;
    ImageButton imb_back;
    DecimalFormat decimalFormat;
    Bundle bundle;
    AlertProgress alert;
    String str_today, l_part_no, l_lot_no, l_serial, l_label_id, str_menu, str_sch_id, str_order, str_part_no, str_part_name, str_supplier, str_location,
            str_plan_qty, str_act_qty, str_control_unit, key_map_label, str_action_det, str_dest_location_id;
    Double sum_total = 0.0, d_plan_qty = 0.0, d_act_plan_qty = 0.0,plan_remain_qty = 0.0, act_scan_qty = 0.0, act_stock_qty = 0.0;

    TableLayout tbl_stock_fifo;
    ScrollView scr_contents;
    JSONObject  label;
    boolean  b_confirm, use_fifo;
    List<Payload_list> payload_label, payload_repack, payload_print;
    Map<String, JSONObject> stock_fifo, repack_label;
    Map<String, Payload_list> map_payload, map_payload_repack;
    LinearLayout layout_edit;

    Comparator<JSONObject> comparator = (JSONObject o1, JSONObject o2) -> {
        try {
            return o1.getInt("id") - o2.getInt("id");
        } catch (Exception e) {
            return 0;
        }
    };

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

        b_confirm = false;
        use_fifo = false;

        stock_fifo = new LinkedHashMap<>();
        repack_label = new LinkedHashMap<>();
        map_payload = new LinkedHashMap<>();
        map_payload_repack = new LinkedHashMap<>();
        payload_label = new ArrayList<Payload_list>();
        payload_repack = new ArrayList<Payload_list>();
        payload_print = new ArrayList<Payload_list>();

        decimalFormat = new DecimalFormat("#,##0.00");
        alert = new AlertProgress(OutboundDetail_Activity.this);
        calendar = Calendar.getInstance();
        date = new SimpleDateFormat("dd/MM/yyyy");
        str_today = date.format(calendar.getTime());

        bundle = getIntent().getExtras();

        str_menu = Settings.getMENU().toString();
        Log.d(getString(R.string.tag), "Menu: " + str_menu);

        tbl_stock_fifo = (TableLayout) findViewById(R.id.tbl_stock_fifo);
        scr_contents = (ScrollView) findViewById(R.id.scr_contents);

        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);
        txt_part_name = (TextView) findViewById(R.id.txt_part_name);
        txt_total = (TextView) findViewById(R.id.txt_total);
        txt_date = (TextView) findViewById(R.id.txt_date);
        txt_date.setText(str_today);

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

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

            str_sch_id = bundle.getString("schedule_id");
            str_order = bundle.getString("order_no");
            str_part_no = bundle.getString("part_no");
            str_part_name = bundle.getString("part_name");
            str_location = bundle.getString("location");
            str_plan_qty = bundle.getString("plan_qty");
            str_act_qty = bundle.getString("act_qty");
            str_supplier = bundle.getString("supplier");
//            str_control_unit = bundle.getString("control_unit");
            str_control_unit = bundle.getString("unit_qty");
            str_action_det = bundle.getString("action_det");
            str_dest_location_id = bundle.getString("dest_location_id");

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

            d_plan_qty = Double.parseDouble(str_plan_qty);
            d_act_plan_qty = Double.parseDouble(str_act_qty);
            plan_remain_qty = (d_plan_qty - d_act_plan_qty);
            Log.d(getString(R.string.tag), "remain_qty =  " + plan_remain_qty + "(" + d_plan_qty + "-" + d_act_plan_qty + ")");

            txt_part_no.setText(str_part_no);
            txt_part_name.setText(str_part_name);
            txt_total.setText(String.format("%.2f/%.2f",d_act_plan_qty,d_plan_qty)+" "+str_control_unit);
            //if scan add to map
            Get_StockFifo(str_part_no, plan_remain_qty, "", "");

    }

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

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

            case R.id.btn_confirm:
                if (b_confirm == false) {
                    Block_button();
                    if (repack_label.size() == 0){
                        SendOutbound();
                    }else {
                        Check_LabelRepack();
                    }
                }
                break;


            case R.id.btn_ok:
                hideKeyboard(this);
                txt_message.setText("");
                Check_Input(key_map_label);
                break;

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


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

    private void Clear_layout_edit() {
        layout_edit.setVisibility(View.GONE);
        edtc_qty.setHint("");
        edtc_qty.setText("");
        txtc_unit.setText("");
        txt_message.setText("");
    }
    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);
    }

    private void Clear_data() {
        Unblock_button();
        act_scan_qty = 0.0;
        b_confirm = false;
        use_fifo = false;
        stock_fifo.clear();
        repack_label.clear();
        map_payload.clear();
        map_payload_repack.clear();
        payload_label.clear();
        payload_repack.clear();
        payload_print.clear();
        Get_StockFifo(str_part_no, plan_remain_qty, "", "");
    }

    @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){
             l_part_no = tokens[0].trim();
             l_lot_no = tokens[1].trim();
             l_serial = tokens[2].trim();
             l_label_id = tokens[3].trim();

//             if (act_scan_qty >= plan_remain_qty){
//                 showWarning("The planned quantity has been exceeded.");
//                 return;
//             }

             if (str_part_no.trim().equalsIgnoreCase(l_part_no)){
                 Check_label();
             }else {
                 showWarning("Part No. not match!!");
             }


            }else {
             showWarning("Invalid QR code!");

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

    private void Check_label() {
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "LABEL/DETAIL");
            json.put("id", l_label_id);
            json.put("parts_no", l_part_no);
            json.put("lot_no", l_lot_no);
            json.put("serial_no", l_serial);

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

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

                        if (jArray.length() == 0){
                            showWarning("Label not found!!");
                        }else {
                           label = jArray.getJSONObject(0);
                            // Check label status
                            if (label.getInt("status") != 2) {
                                showWarning("Invalid Label Status!!");
                                return;
                            }

                            //convert unit qty
                            try {
                                JSONObject json = new JSONObject();
                                json.put("cmd", "conversion-unit");
                                json.put("parts_no", label.getString("lbl_part_no"));
                                json.put("qty",  label.getString("act_stock_qty"));
                                json.put("from_unit", label.getString("control_unit"));
                                json.put("to_unit",str_control_unit );

                                new AsyncHttpClient(getApplicationContext(),
                                        Settings.getMgmtList().get("web_api") + "/ht_api.php",
                                        json.toString()) {
                                    @Override
                                    protected void onFinished(String response, int resp_code) {
                                        try{
                                            JSONArray jArray = new JSONArray(response);
                                            Log.d(getString(R.string.tag), "response: " + response);
                                            if (jArray.length() == 0){
                                                showError("Not found packing standard");

                                            }else {
                                                act_stock_qty = jArray.getJSONObject(0).getDouble("qty");
                                                Alert_Edit_Qty();
                                            }
                                        }catch (JSONException e) {
                                            showError(e.getMessage());
                                        }
                                    }
                                }.execute();
                            }catch (JSONException e){
                                showError(e.getMessage());
                            }
                        }
                    } catch (JSONException e) {
                        showError(e.getMessage());
                    }
                }
            }.execute();

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

    private void Alert_Edit_Qty() {
        Log.d(getString(R.string.tag), "act_stock_qty of label: " + act_stock_qty);
        try {
            key_map_label = label.getString("lot_no").trim()+label.getString("last_location_id");
            if (stock_fifo.containsKey(key_map_label)) {
                Log.d(getString(R.string.tag), "have fifo: ");

                //check Duplicated
                JSONObject item = stock_fifo.get(key_map_label);
                Log.d(getString(R.string.tag), "label_list: " + item.get("label_list") + "label_id: " + item.get("id"));
                if (((HashMap<String, JSONObject>) item.get("label_list")).keySet().contains(label.getString("id"))) {
                    showWarning("Duplicated scan Label!!");
                    redrawStockFifo(null);
                    return;

                } else {
                    use_fifo = true;


                }
            } else {//new lot_no & location
                use_fifo = false;

            }
            Double remain_plan = (d_plan_qty - act_scan_qty);
            if (remain_plan >= act_stock_qty){
                edtc_qty.setHint(String.format("%.2f",act_stock_qty));
                edtc_qty.setText(String.format("%.2f",act_stock_qty));
            }else {
                edtc_qty.setHint(String.format("%.2f",remain_plan));
                edtc_qty.setText(String.format("%.2f",remain_plan));
            }
            //alert edit qty
            layout_edit.setVisibility(View.VISIBLE);
            txtc_unit.setText(" / "+String.format("%.2f",act_stock_qty)+" "+str_control_unit);
        } catch (JSONException e) {
            showError(e.getMessage());
        }
    }
    private void Check_Input(String key_map) {
        try {
            Log.d(getString(R.string.tag), "act_stock_qty of label: " + act_stock_qty);
            txt_message.setText("");
            String input = edtc_qty.getText().toString().trim();
            input = input.trim().equals("") ? "0" : input.trim();
            Double qty_input = Double.valueOf(input);

            Double pre_act_qty = (act_scan_qty + qty_input);
            Log.d(getString(R.string.tag), "pre_act_qty: " + pre_act_qty + "/" + qty_input);

//            if (input.trim().equals("0")) {//Enter zero/blank
            if (Utils.CompareDouble(qty_input , 0.0) ){
                txt_message.setText("Can't enter the ZERO qty! ");

            } else if (qty_input > act_stock_qty) {//EXCEED act qty
                txt_message.setText("Can't enter the EXCEED qty! ");

            } else if (pre_act_qty > d_plan_qty) {//Exceed the total plan
                txt_message.setText("Can't enter Exceed the total plan! ");

            } else {
                Clear_layout_edit();
                if (use_fifo == true) {
                    JSONObject item = stock_fifo.get(key_map);
                    if (qty_input < act_stock_qty) {// repack
                            Log.d(getString(R.string.tag), "repack: ");
                            Double l_remain_qty = (act_stock_qty - qty_input);
                            Log.d(getString(R.string.tag), "repack: " + l_remain_qty);
                            label.put("repack_flag", "1");
                            label.put("remain_qty", l_remain_qty); // remain label : inbound
                            label.put("pick_qty", qty_input);// pick : outbound
                            item.put("act_qty", qty_input + item.getDouble("act_qty")); //fifo sum act
                            repack_label.put(label.getString("id"), label);
                    } else {
                            Log.d(getString(R.string.tag), "All box: ");
                            Log.d(getString(R.string.tag), "act_stock_qty == input");
                            label.put("repack_flag", "0");
                            label.put("remain_qty", "0");
                            label.put("pick_qty", qty_input);
                            item.put("act_qty", item.getDouble("act_qty") + act_stock_qty);
                    }
                        Map<String, JSONObject> label_tmps;
                        if (item.has("label_list")) {
                            label_tmps = (Map<String, JSONObject>) item.get("label_list");
                        } else {
                            label_tmps = new LinkedHashMap<>();
                        }
                        label_tmps.put(label.getString("id"), label);
                        item.put("label_list", label_tmps);
                        Log.d(getString(R.string.tag), "label_list: " + item.get("label_list"));

                }else {
                    if (qty_input < act_stock_qty) {// repack
                        Double l_remain_qty = (act_stock_qty - qty_input);
                        label.put("repack_flag", "1");
                        label.put("remain_qty", l_remain_qty); // remain label : inbound
                        label.put("pick_qty", qty_input);// pick : outbound
                        repack_label.put(label.getString("id"), label);
                    } else {
                        label.put("repack_flag", "0");
                        label.put("remain_qty", "0");
                        label.put("pick_qty", qty_input);
                    }

                    JSONObject j_a = new JSONObject();
                    Map<String, JSONObject> label_tmps;
                    label_tmps = new LinkedHashMap<>();
                    label_tmps.put(label.getString("id"), label);

                    j_a.put("id", stock_fifo.size() + 1);
                    j_a.put("item_id", label.getString("lbl_part_no"));
                    j_a.put("lot_no", label.getString("lot_no"));
                    j_a.put("location_id", label.getString("last_location_id"));
                    j_a.put("pick_qty", qty_input);
                    j_a.put("act_qty", qty_input);
                    j_a.put("label_list", label_tmps);
                    j_a.put("qty", "0");

                    stock_fifo.put(key_map_label, j_a);
                }
            }
            redrawStockFifo(null);
        }catch (JSONException e) {
        showError(e.getMessage());
        }
    }

    private void Check_LabelRepack() {
        payload_repack.clear();
        payload_label.clear();
        map_payload.clear();
        map_payload_repack.clear();

        List<JSONObject> requests = new ArrayList<>();
        int[] completedRequests = {0};  // Using an array to modify it inside the async callback
            for (String key : repack_label.keySet()) {
                try {
                    JSONObject item = repack_label.get(key);
                    String l_label_id = item.getString("id").trim();
                    Double l_remain_qty = item.getDouble("remain_qty");

                    try {
                        Log.d(getString(R.string.tag), "Issue_RepackLabel: " + l_label_id + "/" + l_remain_qty);
                        JSONObject json = new JSONObject();
                        json.put("cmd", "RELABELING/CONFIRM/PREPARE");
                        json.put("ref_label_id", l_label_id);
                        json.put("new_qty", l_remain_qty);
                        json.put("package_id", str_control_unit);
                        json.put("user_id", Settings.getLoginUser().getId());

                        requests.add(json); // Collect request

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

        for (JSONObject json : requests) {
            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")) {
                            String value = jsonObject.getString("value");
                            JSONArray jArray = new JSONArray(value);

                            for (int i = 0; i < jArray.length(); i++) {
                                String id_label = jArray.getJSONObject(i).getString("id");
                                String payload = jArray.getJSONObject(i).getString("payload");
                                String issue_qty = jArray.getJSONObject(i).getString("issue_qty");
                                String reprint_ref_id = jArray.getJSONObject(i).getString("reprint_ref_id");
                                String content_label = i == 0 ? "LABEL-RE" : "LABEL";

                                map_payload.put(id_label, new Payload_list(id_label, content_label, payload, issue_qty, reprint_ref_id));

                                // label repack only: pick qty & remain qty
                                payload_label.add(new Payload_list(id_label, content_label, payload, issue_qty, reprint_ref_id));

                                if (i == 0) { // label repack only: pick qty: black label
                                    payload_repack.add(new Payload_list(id_label, "LABEL-RE", payload, issue_qty, reprint_ref_id));
                                    map_payload_repack.put(id_label, new Payload_list(id_label, "LABEL-RE", payload, issue_qty, reprint_ref_id));
                                }
                            }

                            Log.d(getString(R.string.tag), "payload_repack: " + payload_repack.size());

                        } else {
                            showWarning("Can't prepare the label!!");
                        }

                    } catch (JSONException e) {
                        e.printStackTrace();
                    } finally {
                        // Increment the completed requests counter
                        completedRequests[0]++;
                        // Check if all requests have completed
                        if (completedRequests[0] == requests.size()) {
                            // All requests are complete, proceed with next actions
                            proceedAfterRequests();
                        }
                    }
                }
            }.execute();
        }
    }

    private void proceedAfterRequests() {
        Log.d(getString(R.string.tag), "count map_payload: " + map_payload.size());

        if (map_payload.size() == 0) {
            showError("The map_payload has no data");
        } else {
            AlertConfirmPrint_Repack();
        }
    }


    private void Get_StockFifo(String parts_no, Double qty, String unit_qty, String section) {
        stock_fifo.clear();
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "QUERY/STOCK/FIFO");
            json.put("parts_no", parts_no);
            json.put("qty", qty);
            json.put("unit_qty", unit_qty);
            if (Settings.getMENU().trim().equals(ActionType.Menu.DELIVERY_OUTBOUND.toString())) {
                json.put("section", "");
            }else {
                json.put("section", Settings.getLoginUser().getDepartment());
            }

            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);
                        for (int i = 0; i < jArray.length(); i++) {
                            jArray.getJSONObject(i).put("act_qty", 0);
                            jArray.getJSONObject(i).put("label_list", new HashMap<String, JSONObject>());
                            stock_fifo.put(
                                    jArray.getJSONObject(i).getString("lot_no")+jArray.getJSONObject(i).getString("location_id")
                                    , jArray.getJSONObject(i)
                            );
                        }
                        redrawStockFifo(null);
                    } catch (JSONException e) {
                        showError(e.getMessage());
                    }
                }
            }.execute();

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

    private void redrawStockFifo(String scroll_to_item) {

        Log.d(getString(R.string.tag), "redrawStockFifo() called");

        TableRow scroll_to_row = null;

        try {
            Context context = getApplicationContext();

            // clear tbl_serial_scan
            tbl_stock_fifo.removeAllViews();

            int i = 0;
            Double sum_act_qty = 0.0;

            int colorYellow = Color.argb(0xff, 0xff, 0xff, 0x00);
            int colorGreen = Color.argb(0xff, 0x00, 0xff, 0x00);
            int colorRed = Color.argb(0xff, 0xff, 0x00, 0x00);
            int colorBlack = Color.argb(0xff, 0x00, 0x00, 0x00);
            int colorWhite = Color.argb(0xff, 0xff, 0xff, 0xff);

            SortedSet<JSONObject> items = new TreeSet<>(comparator);
            items.addAll(stock_fifo.values());
            for (JSONObject item : stock_fifo.values()) {

                int bgColor = Color.argb((++i % 2) == 0 ? 0x30 : 0x10, 0xaa, 0xaa, 0xaa);
                int bgColorStatus = bgColor;
                int textColor = colorBlack;

                //JSONObject item = mapItems.get(key);
                String id = item.getString("id");
                String lot_no = item.getString("lot_no");
                String location_id = item.getString("location_id");
                String qty = String.format("%.2f/%.2f", item.getDouble("act_qty"), item.getDouble("qty"));
                String status = "";
                Log.d(getString(R.string.tag), "stock_fifo: "+id+"|"+ lot_no+"|"+location_id+"|"+qty);
                sum_act_qty = (sum_act_qty +item.getDouble("act_qty"));
                Log.d(getString(R.string.tag), "act_plan_qty: "+sum_act_qty);


                if (item.getDouble("act_qty") >= item.getDouble("qty")) {
                    bgColorStatus = colorGreen;
                    status = "OK";
                } else if (item.getDouble("act_qty") > 0) {
                    bgColorStatus = colorYellow;
                    status = "WORKING";
                }

                TableRow tableRow = new TableRow(context);
                TableRow.LayoutParams layoutParams = new TableRow.LayoutParams(
                        TableLayout.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT);
                layoutParams.setMargins(1, 1, 1, 1);
                tableRow.setLayoutParams(layoutParams);

                int width = 300;
                int col_height = 40;
                int[] col_width = {8, 25, 21, 34, 15};

                TextView textView = new TextView(context);
                textView.setText(id);
                textView.setWidth(width * col_width[0] / 100);
                textView.setHeight(col_height);
                textView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
                textView.setBackgroundColor(bgColor);
                textView.setTextColor(textColor);
                textView.setPadding(1, 5, 0, 0);
                textView.setLayoutParams(layoutParams);
                tableRow.addView(textView);

                textView = new TextView(context);
                textView.setText(lot_no);
                textView.setWidth(width * col_width[1] / 100);
                textView.setHeight(col_height);
                textView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
                textView.setBackgroundColor(bgColor);
                textView.setTextColor(textColor);
                textView.setPadding(1, 5, 0, 0);
                textView.setLayoutParams(layoutParams);
                tableRow.addView(textView);

                textView = new TextView(context);
                textView.setText(location_id);
                textView.setWidth(width * col_width[2] / 100);
                textView.setHeight(col_height);
                textView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
                textView.setBackgroundColor(bgColor);
                textView.setTextColor(textColor);
                textView.setPadding(1, 5, 0, 0);
                textView.setLayoutParams(layoutParams);
                tableRow.addView(textView);

                textView = new TextView(context);
                textView.setText(qty);
                textView.setWidth(width * col_width[3] / 100);
                textView.setHeight(col_height);
                textView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
                textView.setBackgroundColor(bgColor);
                textView.setTextColor(textColor);
                textView.setSingleLine(false);
                textView.setPadding(1, 5, 0, 0);
                textView.setLayoutParams(layoutParams);
                tableRow.addView(textView);

//                textView = new TextView(context);
//                textView.setText(unit);
//                textView.setWidth(width * col_width[4] / 100);
//                textView.setHeight(col_height);
//                textView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
//                textView.setBackgroundColor(bgColorStatus);
//                textView.setTextColor(textColor);
//                textView.setPadding(1, 5, 0, 0);
//                textView.setLayoutParams(layoutParams);
//                tableRow.addView(textView);

                textView = new TextView(context);
                textView.setText(status);
                textView.setWidth(width * col_width[4] / 100);
                textView.setHeight(col_height);
                textView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
                textView.setBackgroundColor(bgColorStatus);
                textView.setTextColor(textColor);
                textView.setPadding(1, 5, 0, 0);
                textView.setLayoutParams(layoutParams);
                tableRow.addView(textView);

                tbl_stock_fifo.addView(tableRow);

                if (scroll_to_item == null) { // latest schedule is auto focus
                    scroll_to_row = tableRow;
                } else if (item.getString("id").equalsIgnoreCase(scroll_to_item)) {
                    scroll_to_row = tableRow;
                }
            }

            act_scan_qty = (d_act_plan_qty + sum_act_qty);
            txt_total.setText(String.format("%.2f/%.2f",act_scan_qty,d_plan_qty)+" "+str_control_unit);

            // scroll to last item added
            if (scroll_to_row != null)
                scr_contents.post(new ScrollToTrick(scr_contents, scroll_to_row));
        } catch (Exception e) {
            Log.e(getString(R.string.tag), e.getMessage());
            e.printStackTrace();
        }
    }


    private void AlertConfirmPrint_Repack() {
        SweetAlertDialog d = new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE);
        d.setCancelable(false);
        d.setTitleText("WARNING");
        d.setContentText("Print all remaining labels?");
        d.setCancelText("No");
        d.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
            @Override
            public void onClick(SweetAlertDialog sDialog) {
                sDialog.dismiss();
                payload_print = payload_repack.stream()
                        .collect(Collectors.toList());

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

                } else {
                    Log.d(getString(R.string.tag), "payload_print No: " + payload_print.size());
                    Print_Label();
                }
            }
        });
        d.setConfirmText("Yes");
        d.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
            @Override
            public void onClick(SweetAlertDialog sDialog) {
                sDialog.dismiss();
                payload_print = payload_label.stream()
                        .collect(Collectors.toList());
                if (Settings.getMgmtList().get("skip_print").trim().equals("1")) {
                    AlertConfirmPrint();

                } else {
                    Log.d(getString(R.string.tag), "payload_print yes: " + payload_print.size());
                    Print_Label();
                }
            }
        });
        d.show();
    }

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

        String tmp_label = "";
            for (int i = 0; i < payload_print.size(); i++) {
                Payload_list payload_l = payload_print.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();
                    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) {
            showWarning("Please check the label status on Pegasus!");

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

    }

    private void Confirm_Label() {
        Log.d(getString(R.string.tag), "payload_print: " + payload_print.size());
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "RELABELING/CONFIRM/CONFIRM");
            JSONArray jArray = new JSONArray();
            for (int i = 0; i < payload_print.size(); i++){
                Payload_list list = payload_print.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){
                            SendOutbound();

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

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

    private void SendOutbound() {
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "OUTBOUND/SCHEDULE/DETAIL/CONFIRM");
            JSONArray jsonArray = new JSONArray();

            for (JSONObject item : stock_fifo.values()) {
                Map<String, JSONObject> label_tmps = (Map<String, JSONObject>) item.get("label_list");
                for (JSONObject label : label_tmps.values()) {
                    Map<String, String> jsonParams = new HashMap<>();
                    jsonParams.put("item_id", label.getString("lbl_part_no"));
                    jsonParams.put("item_name", label.getString("lbl_part_name").trim());
                    jsonParams.put("lot_no", label.getString("lot_no"));

                    if (label.getString("repack_flag").trim().equals("0")) {
                        jsonParams.put("ref_sch_id", str_sch_id);
                    }else {
                        jsonParams.put("ref_sch_id", "0");
                    }
                    jsonParams.put("order_no", str_order);
                    jsonParams.put("package_id", label.getString("lbl_unit"));
                    jsonParams.put("unit_qty", label.getString("control_unit"));
                    jsonParams.put("package_qty", label.getString("act_stock_qty"));
                    jsonParams.put("qty", label.getString("act_stock_qty"));
                    jsonParams.put("location_id", label.getString("last_location_id"));
                    jsonParams.put("location_name", label.getString("last_location_name").trim().equals("null") ? "": label.getString("last_location_name").trim());
                    jsonParams.put("label_id", label.getString("id"));
                    jsonParams.put("inspection_flg", "0");
                    jsonParams.put("status", "2");
                    jsonParams.put("slip_divide", "4");
                    jsonParams.put("create_user_id", Settings.getLoginUser().getId());
                    jsonParams.put("ng", label.getString("lbl_ng"));
                    jsonParams.put("supplier_id", label.getString("lbl_supplier_id"));
                    jsonParams.put("supplier_name", label.getString("lbl_supplier").trim().equals("null") ? "": label.getString("lbl_supplier").trim());
                    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), "Outbound 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), "Outbound success: " + response);
                            if (repack_label.size() > 0 ){
                                SendInbound();
                            }else {

                                if (Settings.getMENU().trim().equals(ActionType.Menu.DELIVERY_OUTBOUND.toString())){
                                    finish();
                                }else {
                                    Inbound_Production();
                                }
                            }
                        }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 SendInbound() {
        try {
            JSONObject json = new JSONObject();
            Map<String, String> jsonParams = new HashMap<>();
            json.put("cmd", "INBOUND/MANUAL/DETAIL/CONFIRM");
            JSONArray jsonArray = new JSONArray();

            for (String key : map_payload.keySet()){
                Payload_list payload_label = map_payload.get(key);

                for (String K : repack_label.keySet()){
                    JSONObject item_label = repack_label.get(K);
                    jsonParams.put("ref_sch_id", str_sch_id);
                    jsonParams.put("label_id", payload_label.getId());
                    jsonParams.put("package_qty", payload_label.getQty());
                    jsonParams.put("qty",payload_label.getQty());
                    jsonParams.put("item_id", item_label.getString("lbl_part_no"));
                    jsonParams.put("lot_no", item_label.getString("lot_no"));
                    jsonParams.put("item_name", item_label.getString("lbl_part_name"));
                    jsonParams.put("package_id", item_label.getString("lbl_unit"));
                    jsonParams.put("unit_qty", item_label.getString("control_unit"));
                    jsonParams.put("location_id", item_label.getString("last_location_id"));
                    jsonParams.put("location_name", item_label.getString("last_location_name").trim().equals("null") ? "" : item_label.getString("last_location_name"));
                    jsonParams.put("inspection_flg","0");
                    jsonParams.put("status", "1");
                    jsonParams.put("slip_divide", "3");
                    jsonParams.put("create_user_id", Settings.getLoginUser().getId());
                    jsonParams.put("ng", item_label.getString("lbl_ng"));
                    jsonParams.put("supplier_id", item_label.getString("lbl_supplier_id").trim().equals("null") ? "" : item_label.getString("lbl_supplier_id"));
                    jsonParams.put("supplier_name", item_label.getString("lbl_supplier").trim().equals("null") ? "" : item_label.getString("lbl_supplier"));

                }
                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),"Inbound response"+ response);
                        String status = jsonObject.getString("status");
                        int affected_rows = jsonObject.getInt("affected_rows");

                        if (status.trim().equals("success") && affected_rows > 0){
                            SendOutbound_repack();

                        }else {
                            Unblock_button();
                            String error = jsonObject.getString("error");
                            showError(error);

                        }
                    }catch (JSONException e) {
                        Unblock_button();
                        showError(e.getMessage());
                    }
                }
            }.execute();
        }catch (Exception e) {
            Unblock_button();
            showError(e.getMessage());
        }
    }
    private void SendOutbound_repack() {
        Log.d(getString(R.string.tag), "map_payload_repack: " + map_payload_repack.size());
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "OUTBOUND/SCHEDULE/DETAIL/CONFIRM");
            JSONArray jsonArray = new JSONArray();

            for (String K : map_payload_repack.keySet()) {
                Payload_list out = map_payload_repack.get(K);
                String label_id = out.getId();
                String reprint_ref_id = out.getReprint_ref_id();

                JSONObject item_label = repack_label.get(reprint_ref_id);

                Map<String, String> jsonParams = new HashMap<>();
                jsonParams.put("item_id", item_label.getString("lbl_part_no"));
                jsonParams.put("item_name", item_label.getString("lbl_part_name"));
                jsonParams.put("lot_no", item_label.getString("lot_no"));
                jsonParams.put("ref_sch_id", str_sch_id);
                jsonParams.put("order_no", str_order);
                jsonParams.put("package_id", item_label.getString("lbl_unit"));
                jsonParams.put("unit_qty", item_label.getString("control_unit"));
//                jsonParams.put("package_qty", item_label.getString("pick_qty"));
//                jsonParams.put("qty", item_label.getString("pick_qty"));
                jsonParams.put("package_qty", out.getQty());
                jsonParams.put("qty", out.getQty());
                jsonParams.put("location_id", item_label.getString("last_location_id"));
                jsonParams.put("location_name", item_label.getString("last_location_name").trim().equals("null") ? "" : item_label.getString("last_location_name"));
                jsonParams.put("label_id",label_id);
                jsonParams.put("inspection_flg", "0");
                jsonParams.put("status", "2");
                jsonParams.put("slip_divide", "4");
                jsonParams.put("create_user_id", Settings.getLoginUser().getId());
                jsonParams.put("ng", item_label.getString("lbl_ng"));
                jsonParams.put("supplier_name", item_label.getString("lbl_supplier_id").trim().equals("null") ? "" : item_label.getString("lbl_supplier_id"));
                jsonParams.put("supplier_id", item_label.getString("lbl_supplier").trim().equals("null") ? "" : item_label.getString("lbl_supplier"));

                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), "Outbound_Re 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) {
                            if (Settings.getMENU().trim().equals(ActionType.Menu.DELIVERY_OUTBOUND.toString())){
                                finish();
                            }else {
                                Inbound_Production();
                            }
                        }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 Inbound_Production() {
        //inbound stock_fifo : repack_flag = 0, map_payload_repack
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "INBOUND/PRODUCTION/MANUAL/DETAIL/CONFIRM");
            JSONArray jsonArray = new JSONArray();

            for (JSONObject item : stock_fifo.values()) {
                Map<String, JSONObject> label_tmps = (Map<String, JSONObject>) item.get("label_list");
                for (JSONObject label : label_tmps.values()) {
                    if (label.getString("repack_flag").trim().equals("0")) {
                        Map<String, String> jsonParams = new HashMap<>();
                        jsonParams.put("ref_sch_id", str_sch_id);
                        jsonParams.put("order_no", str_order);
                        jsonParams.put("label_id", label.getString("id"));
                        jsonParams.put("package_qty", label.getString("act_stock_qty"));
                        jsonParams.put("qty",label.getString("act_stock_qty"));
                        jsonParams.put("item_id", label.getString("lbl_part_no"));
                        jsonParams.put("item_name", label.getString("lbl_part_name"));
                        jsonParams.put("lot_no", label.getString("lot_no"));
                        jsonParams.put("package_id", str_control_unit);
                        jsonParams.put("unit_qty", label.getString("control_unit"));
                        jsonParams.put("location_id",str_dest_location_id );
                        jsonParams.put("location_name", Settings.getMap_location().get(str_dest_location_id).getName().trim().equals("null")?"":Settings.getMap_location().get(str_dest_location_id).getName().trim());
                        jsonParams.put("inspection_flg","0");
                        jsonParams.put("status", "1");
                        jsonParams.put("slip_divide", "3");
                        jsonParams.put("create_user_id", Settings.getLoginUser().getId());
                        jsonParams.put("ng", label.getString("lbl_ng"));
                        jsonParams.put("supplier_id", label.getString("lbl_supplier_id").trim().equals("null") ? "" : label.getString("lbl_supplier_id"));
                        jsonParams.put("supplier_name", label.getString("lbl_supplier").trim().equals("null") ? "" : label.getString("lbl_supplier"));
                        JSONObject jsonObject = new JSONObject(jsonParams);
                        jsonArray.put(jsonObject);
                    }
                }
            }

            if (map_payload_repack.size() > 0){
                for (String K : map_payload_repack.keySet()) {
                    Payload_list out = map_payload_repack.get(K);
                    String label_id = out.getId();
                    String reprint_ref_id = out.getReprint_ref_id();
                    JSONObject item_label = repack_label.get(reprint_ref_id);

                    Map<String, String> jsonParams = new HashMap<>();
                    jsonParams.put("ref_sch_id", str_sch_id);
                    jsonParams.put("order_no", str_order);
                    jsonParams.put("label_id",label_id);

                    jsonParams.put("item_id", item_label.getString("lbl_part_no"));
                    jsonParams.put("item_name", item_label.getString("lbl_part_name"));
                    jsonParams.put("lot_no", item_label.getString("lot_no"));
                    jsonParams.put("package_qty", item_label.getString("pick_qty"));
                    jsonParams.put("package_id", str_control_unit);
                    jsonParams.put("qty", out.getQty());
                    jsonParams.put("unit_qty", item_label.getString("control_unit"));
                    jsonParams.put("location_id",str_dest_location_id );
                    jsonParams.put("location_name", Settings.getMap_location().get(str_dest_location_id).getName().trim().equals("null")?"":Settings.getMap_location().get(str_dest_location_id).getName().trim());
                    jsonParams.put("inspection_flg","0");
                    jsonParams.put("status", "1");
                    jsonParams.put("slip_divide", "3");
                    jsonParams.put("create_user_id", Settings.getLoginUser().getId());
                    jsonParams.put("ng", item_label.getString("lbl_ng"));
                    jsonParams.put("supplier_name", item_label.getString("lbl_supplier_id").trim().equals("null") ? "" : item_label.getString("lbl_supplier_id"));
                    jsonParams.put("supplier_id", item_label.getString("lbl_supplier").trim().equals("null") ? "" : item_label.getString("lbl_supplier"));

                    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),"Inbound response"+ response);
                        String status = jsonObject.getString("status");
                        int affected_rows = jsonObject.getInt("affected_rows");

                        if (status.trim().equals("success") && affected_rows > 0){
                            finish();

                        }else {
                            Unblock_button();
                            String error = jsonObject.getString("error");
                            showError(error);

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

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