package com.tomas.ht_ydt;

import android.app.Activity;
import android.content.Context;
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.TextView;

import androidx.annotation.NonNull;
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.OutboundManual_Adapter;
import com.tomas.ht_ydt.ListData.LabelItem_Outbound_list;
import com.tomas.ht_ydt.ListData.Payload_list;
import com.tomas.ht_ydt.ListData.Rework_List;
import com.tomas.ht_ydt.lib.AlertProgress;
import com.tomas.ht_ydt.lib.KeyMapping;
import com.tomas.ht_ydt.lib.Scanner;
import com.tomas.ht_ydt.lib.Settings;
import com.tomas.ht_ydt.lib.common.AsyncHttpClient;
import com.tomas.ht_ydt.lib.common.AsyncTcpClient;
import com.tomas.ht_ydt.lib.common.Utils;

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

import java.text.DecimalFormat;
import java.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 java.util.stream.Collectors;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class OutboundManual_Activity extends Scanner implements View.OnClickListener, ClickItem_OutboundManual{
    Calendar calendar;
    SimpleDateFormat date, date_time_fm;
    TextView txt_user, txt_device, txt_part_no, txt_part_name, txt_total, txt_date, txtc_unit,txt_message;
    Button btn_confirm, btn_clear;
    ImageButton imb_back;
    AlertProgress alert;
    RecyclerView view_data;
    DecimalFormat decimalFormat;
    boolean b_confirm;
    Bundle bundle;
    String str_today, l_part_no, l_lot_no, l_serial, l_label_id, str_menu, str_part_no, str_part_name, update_label_id, dt_to_server;
    Double sum_total = 0.0, label_act_qty = 0.0, label_remain = 0.0;
    OutboundManual_Adapter label_adapter;
    List<Payload_list> payload_repack, payload_label, payload_print;
    Map<String, LabelItem_Outbound_list> map_label_scan;
    List<LabelItem_Outbound_list> list_label;
    LinearLayout layout_edit;
    EditText edtc_qty;
    Map<String, Payload_list>map_payload, map_payload_repack;
    Map<String, JSONObject> repack_label;

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

        b_confirm = false;
        map_label_scan = new LinkedHashMap<>();
        map_payload = new LinkedHashMap<>();
        map_payload_repack = new LinkedHashMap<>();
        repack_label = new LinkedHashMap<>();
        list_label = new ArrayList<LabelItem_Outbound_list>();
        payload_repack = new ArrayList<Payload_list>();
        payload_label = new ArrayList<Payload_list>();
        payload_print = new ArrayList<Payload_list>();

        decimalFormat = new DecimalFormat("#,##0.00");
        alert = new AlertProgress(OutboundManual_Activity.this);
        calendar = Calendar.getInstance();
        date = new SimpleDateFormat("dd/MM/yyyy");
        date_time_fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        str_today = date.format(calendar.getTime());

        bundle = getIntent().getExtras();

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

        Log.d(getString(R.string.tag), "crusher_ratio: " + Settings.getMgmtList().get("crusher_ratio"));


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

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

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

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

    }

    @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:
                Check_LabelRepack();
                break;

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

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



        }
    }



    private void Update_data() {
        repack_label.clear();
        Log.d(getString(R.string.tag), "update_label_id : "+update_label_id);
        Log.d(getString(R.string.tag), "label_act_qty : "+label_act_qty);
        String pick = edtc_qty.getText().toString().trim();
        pick = pick.trim().equals("") ? "0" : pick.trim();
        Double qty_pick = Double.valueOf(pick);

        if (qty_pick > label_act_qty){
            txt_message.setText("Cannot enter the EXCEED qty! ");

        }else if (pick.trim().equals("0")){
            txt_message.setText("Cannot enter the ZERO qty! ");

        } else {
            layout_edit.setVisibility(View.GONE);
            label_remain = (label_act_qty - qty_pick);
            Log.d(getString(R.string.tag), "label_remain : "+label_remain);

            LabelItem_Outbound_list item = map_label_scan.get(update_label_id);
            item.setPick_qty (String.valueOf(pick));
            item.setRemain_qty(String.valueOf(label_remain));
            map_label_scan.put(update_label_id,item);

            repack_label.put(update_label_id,null);

            Clear_layout_edit();
            Summary_data();
        }
    }

    private void Clear_layout_edit() {
        update_label_id = "";
        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_layout() {
        Unblock_button();
        b_confirm = false;
        map_label_scan.clear();
        map_payload.clear();
        map_payload_repack.clear();
        payload_label.clear();
        payload_print.clear();
        payload_repack.clear();
        Summary_data();

    }

    @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();
             Log.d(getString(R.string.tag), "l_label_id = " +l_label_id);

             if (map_label_scan.size() == 0){
                 Check_label();
             }else {
                 String part_no = txt_part_no.getText().toString().toString();
                 if (part_no.trim().equals(l_part_no)){
                     //check duplicate label
                     if (map_label_scan.containsKey(l_label_id)){
                         SweetAlertDialog d = new SweetAlertDialog(OutboundManual_Activity.this, SweetAlertDialog.WARNING_TYPE);
                         d.setCancelable(false);
                         d.setTitleText("WARNING");
                         d.setContentText("This label has been scanned.");
                         d.setCancelText("Delete");
                         d.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                             @Override
                             public void onClick(SweetAlertDialog sd) {
                                 sd.dismiss();
                                 map_label_scan.remove(l_label_id);
                                 Log.d(getString(R.string.tag), "delete size = " + map_label_scan.size());
                                 Summary_data();
                             }
                         });
                         d.setConfirmText("Continue");
                         d.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                             @Override
                             public void onClick(SweetAlertDialog sd) {
                                 sd.dismiss();
                             }
                         });
                         d.show();

                     }else {
                         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 {
                            int label_status = jArray.getJSONObject(0).getInt("status");
                            // Check label status
                            if (label_status!= 2) {
                                showWarning("Invalid Label Status!!");

                            }else {
                                str_part_no = jArray.getJSONObject(0).getString("lbl_part_no").trim();
                                str_part_name = jArray.getJSONObject(0).getString("lbl_part_name").trim();
                                map_label_scan.put(jArray.getJSONObject(0).getString("id"),
                                        new LabelItem_Outbound_list(
                                                "",
                                                jArray.getJSONObject(0).getString("id"),
                                                jArray.getJSONObject(0).getString("lot_no"),
                                                jArray.getJSONObject(0).getString("serial_no"),
                                                String.valueOf(label_status),
                                                jArray.getJSONObject(0).getString("issue_qty"),
                                                jArray.getJSONObject(0).getString("issue_stock_qty"),
                                                jArray.getJSONObject(0).getString("act_stock_qty"),
                                                jArray.getJSONObject(0).getString("control_unit"),
                                                jArray.getJSONObject(0).getString("lbl_supplier_id"),
                                                jArray.getJSONObject(0).getString("lbl_supplier"),
                                                jArray.getJSONObject(0).getString("lbl_part_no"),
                                                jArray.getJSONObject(0).getString("lbl_part_name"),
                                                jArray.getJSONObject(0).getString("lbl_unit"),
                                                jArray.getJSONObject(0).getString("lbl_ng"),
                                                jArray.getJSONObject(0).getString("last_location_id"),
                                                jArray.getJSONObject(0).getString("last_location_name"),
                                                jArray.getJSONObject(0).getString("lbl_order_no"),
                                                jArray.getJSONObject(0).getString("act_stock_qty"),
                                                "0",
                                                "OK"));

                                Log.d(getString(R.string.tag), "map_label: " + map_label_scan.size());
                                Summary_data();
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }.execute();

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

    private void Summary_data() {
        list_label.clear();
        sum_total = 0.0;
        int no = 0;
        Log.d(getString(R.string.tag),"mapItem"+ String.valueOf(map_label_scan.size()));

        if (map_label_scan.size() > 0) {
            for (String key : map_label_scan.keySet()) {
                LabelItem_Outbound_list item = map_label_scan.get(key);
                list_label.add(new LabelItem_Outbound_list(
                        String.valueOf(no+1),
                        item.getLabel_id(),
                        item.getLot_no(),
                        item.getSerial_no(),
                        item.getLabel_status(),
                        item.getIssue_qty(),
                        item.getIssue_stock_qty(),
                        item.getAct_stock_qty(),
                        item.getControl_unit(),
                        item.getLbl_supplier_id(),
                        item.getLbl_supplier(),
                        item.getLbl_part_no(),
                        item.getLbl_part_name(),
                        item.getLbl_unit(),
                        item.getLbl_ng(),
                        item.getLast_location_id(),
                        item.getLocation_name(),
                        item.getLbl_order_no(),
                        item.getPick_qty(),
                        item.getRemain_qty(),
                        item.getStatus()));

                Double qty = Double.parseDouble(item.getPick_qty());
                sum_total = (sum_total + qty);
                Log.d(getString(R.string.tag), "SUM " + String.valueOf(sum_total));
            }
            txt_total.setText(String.format("%.2f", sum_total));
            txt_part_name.setText(str_part_name);
            txt_part_no.setText(str_part_no);

        }else {
            txt_total.setText("0");
            txt_part_name.setText("");
            txt_part_no.setText("");

        }
        label_adapter = new OutboundManual_Adapter(list_label, this, this);
        view_data.setAdapter(label_adapter);
        Log.d(getString(R.string.tag), "set adapter");
    }

    @Override
    public void Item_Outbound_Manual(String id, String pick_qty, String act_stock_qty, String remain_qty, String unit) {
        Log.d(getString(R.string.tag), "update_label_id : "+id);
        Log.d(getString(R.string.tag), "label_act_qty : "+act_stock_qty);
        layout_edit.setVisibility(View.VISIBLE);
        update_label_id = id;
        label_act_qty = Double.parseDouble(act_stock_qty);
        edtc_qty.setHint(act_stock_qty);
        edtc_qty.setText(pick_qty);
        txtc_unit.setText(unit);

    }

    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 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
        if (repack_label.size() == 0){
            SendOutbound();
        }else {
            for (String keys : repack_label.keySet()) {
                LabelItem_Outbound_list item = map_label_scan.get(keys);
                String l_label_id = item.getLabel_id();
                String l_control_unit = item.getControl_unit();
                Double l_remain_qty = Double.valueOf(item.getRemain_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", l_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());
                }
            }
        }

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

// No further action here, processing handled in the callback
    }

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

        if (map_payload.size() > 0) {
            AlertConfirmPrint_Repack();
        } else {
            SendOutbound();
//            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();
//            }
        }
    }


    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) {
            Unblock_button();
            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() {
        Log.d(getString(R.string.tag), "SendOutbound: " + map_label_scan.size());
        calendar = Calendar.getInstance();
        calendar = (Calendar) calendar.clone();
        dt_to_server = date_time_fm.format(calendar.getTime());
        Log.d(getString(R.string.tag), "dt_to_server : " + dt_to_server);
        try {
            JSONObject json = new JSONObject();
            Map<String, String> jsonParams = new HashMap<>();
            json.put("cmd", "OUTBOUND/MANUAL/DETAIL/CONFIRM");
            JSONArray jsonArray = new JSONArray();

            for (String key : map_label_scan.keySet()){
                LabelItem_Outbound_list item = map_label_scan.get(key);

                jsonParams.put("label_id", item.getLabel_id());
                jsonParams.put("item_id",item.getLbl_part_no() );
                jsonParams.put("item_name", item.getLbl_part_name());
                jsonParams.put("lot_no", item.getLot_no());
                jsonParams.put("ref_sch_id", "0");
                jsonParams.put("package_id", item.getLbl_unit());
                jsonParams.put("unit_qty", item.getControl_unit());
                jsonParams.put("package_qty", item.getAct_stock_qty());
                jsonParams.put("qty", item.getAct_stock_qty());
                jsonParams.put("location_id", item.getLast_location_id());
                jsonParams.put("location_name", item.getLocation_name().trim().equals("null") ? "" : item.getLocation_name());
                jsonParams.put("order_no", "");
                jsonParams.put("ng", item.getLbl_ng());
                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("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);

                            if (map_payload.size() > 0){
                                SendInbound();
                            }else {
//                                finish();
                                showSuccess("Outbound Completed");
                                Clear_layout();
                            }
                        }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() {
        Log.d(getString(R.string.tag), "SendInbound map_payload: " + map_payload.size());
        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);
                String ref_id = payload_label.getReprint_ref_id();
                LabelItem_Outbound_list item_label = map_label_scan.get(ref_id);

                jsonParams.put("ref_sch_id", "0");
                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.getLbl_part_no());
                jsonParams.put("lot_no", item_label.getLot_no());
                jsonParams.put("item_name", item_label.getLbl_part_name());
                jsonParams.put("package_id", item_label.getLbl_unit());
                jsonParams.put("unit_qty", item_label.getControl_unit());
                jsonParams.put("location_id", item_label.getLast_location_id());
                jsonParams.put("location_name", item_label.getLocation_name().trim().equals("null") ? "" : item_label.getLocation_name());
                jsonParams.put("ng", item_label.getLbl_ng());
                jsonParams.put("supplier_id", item_label.getLbl_supplier_id().trim().equals("null") ? "" : item_label.getLbl_supplier_id().trim());
                jsonParams.put("supplier_name", item_label.getLbl_supplier().trim().equals("null") ? "" : item_label.getLbl_supplier().trim());
                jsonParams.put("inspection_flg","0");
                jsonParams.put("status", "1");
                jsonParams.put("slip_divide", "3");
                jsonParams.put("create_user_id", Settings.getLoginUser().getId());
                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){
                            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() {
        calendar = Calendar.getInstance();
        calendar = (Calendar) calendar.clone();
        dt_to_server = date_time_fm.format(calendar.getTime());
        Log.d(getString(R.string.tag), "dt_to_server : " + dt_to_server);
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "OUTBOUND/MANUAL/DETAIL/CONFIRM");
            JSONArray jsonArray = new JSONArray();
            Map<String, String> jsonParams = new HashMap<>();

            for (String key : map_payload_repack.keySet()) {
                Payload_list payload_label = map_payload_repack.get(key);
                String ref_id = payload_label.getReprint_ref_id();
                LabelItem_Outbound_list item_label = map_label_scan.get(ref_id);

                jsonParams.put("ref_sch_id", "0");
                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.getLbl_part_no());
                jsonParams.put("item_name", item_label.getLbl_part_name());
                jsonParams.put("lot_no",item_label.getLot_no());
                jsonParams.put("package_id", item_label.getLbl_unit());
                jsonParams.put("unit_qty", item_label.getControl_unit());
                jsonParams.put("location_id", item_label.getLast_location_id());
                jsonParams.put("location_name", item_label.getLocation_name().trim().equals("null") ? "" : item_label.getLocation_name());
                jsonParams.put("ng", item_label.getLbl_ng());
                jsonParams.put("supplier_id", item_label.getLbl_supplier_id().trim().equals("null") ? "" : item_label.getLbl_supplier_id().trim());
                jsonParams.put("supplier_name", item_label.getLbl_supplier().trim().equals("null") ? "" : item_label.getLbl_supplier().trim());
                jsonParams.put("inspection_flg", "0");
                jsonParams.put("status", "2");
                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);
                            showSuccess("Outbound Completed");
                            Clear_layout();
                        }else{
                            Unblock_button();
                            showWarning("Can't Outbound");
                        }

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