package com.tomas.ht_mast;

import static android.content.ContentValues.TAG;

import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.text.InputType;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

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

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

import java.text.DecimalFormat;
import java.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 {
    TextView  txt_user, txt_device,txt_order_no, txt_date, txt_part_no, txt_part_name, txt_total, txt_header;
    Calendar calendar;
    SimpleDateFormat date;
    DecimalFormat decimalFormat;
    String str_today, str_mode, str_sch_id, str_order, str_part_no, str_part_name, str_rank, str_location, str_plan_qty,
    str_act_qty, str_inspection_flg, str_unit, t_order, t_part, t_dwg, t_lot_no, t_qty, t_rank, t_box ;
    Button btn_clear, btn_confirm;
    JSONObject  label;
    Bundle bundle;
    Double plan_qty = 0.0 , act_plan_qty = 0.0, remain_qty = 0.0, act_scan_qty = 0.0, act_stock_qty = 0.0;
    TableLayout tbl_stock_fifo;
    ScrollView scr_contents;
    Integer LABEL_QTY, PRINT_TIMES;
    List<Payload_list> payload_label, payload_repack, payload_print;
    AlertProgress alert;
    Map<String, JSONObject> stock_fifo, repack_label;
    Map<String, Payload_list>map_payload;
    private volatile boolean stopThread = true;
    boolean scan_label, b_confirm;

    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);
        alert = new AlertProgress(OutboundDetail_Activity.this);
        scan_label = false;
        b_confirm = false;

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

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

        calendar = Calendar.getInstance();
        date = new SimpleDateFormat("dd/MM/yyyy");
        str_today = date.format(calendar.getTime());

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

        txt_header = (TextView) findViewById(R.id.txt_header);
        txt_order_no = (TextView) findViewById(R.id.txt_order_no);
        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_total.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Alert_Change_Plan_Qty("Change Plan Qty.");

            }
        });
        
        btn_clear = (Button)findViewById(R.id.btn_clear);
        btn_confirm = (Button)findViewById(R.id.btn_confirm);
        
        bundle = getIntent().getExtras();
        str_mode = Settings.getActionType().toString();
        Log.d(getString(R.string.tag), "str_mode:" + str_mode);
                txt_header.setText("Outbound Detail");
                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_rank = bundle.getString("rank");
                str_location = bundle.getString("location");
                str_plan_qty = bundle.getString("plan_qty");
                str_act_qty = bundle.getString("act_qty");
                str_inspection_flg = bundle.getString("inspection_flg");
                str_unit = bundle.getString("unit");

                txt_order_no.setText(str_order);
                txt_part_no.setText(str_part_no);
                txt_part_name.setText(str_part_name);
                txt_total.setText( str_act_qty +"/"+str_plan_qty);

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

                //if scan add to map
                Get_StockFifo(str_part_no, remain_qty, "","");

                if (bundle.getBoolean("scan") == true) {
                    Scan_label(bundle.getString("label_scan"));
                }
        }

    private void Alert_Change_Plan_Qty(String msg) {
        final EditText editText = new EditText(OutboundDetail_Activity.this);
        editText.setBackgroundResource(R.drawable.img_background);
        editText.setGravity(Gravity.CENTER);
        editText.setInputType(InputType.TYPE_NUMBER_FLAG_DECIMAL);
        editText.setTextSize(20);
        editText.setHint(String.format("%.2f",plan_qty));

        SweetAlertDialog dialog = new SweetAlertDialog(OutboundDetail_Activity.this, SweetAlertDialog.NORMAL_TYPE)
                .setTitleText(msg)
                .setCancelText("Cancel")
                .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sDialog) {
                        sDialog.cancel();
                    }
                })
                .setConfirmText("OK")
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sDialog) {
                        sDialog.cancel();

                        if (scan_label == true){
                            new SweetAlertDialog(OutboundDetail_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("WARNING")
                                    .setContentText("Click \"Yes\" to confirm change plan qty!")
                                    .setCancelText("No")
                                    .showCancelButton(true)
                                    .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                        @Override
                                        public void onClick(SweetAlertDialog sDialog) {
                                            sDialog.cancel();
                                        }
                                    })
                                    .setConfirmText("Yes")
                                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                        @Override
                                        public void onClick(SweetAlertDialog sDialog) {
                                            sDialog.cancel();
                                            Double new_plan = Double.parseDouble(editText.getText().toString().trim());
                                            plan_qty = new_plan;
                                            txt_total.setText(String.format("%.2f/%.2f",act_scan_qty ,plan_qty));

                                            remain_qty = (plan_qty - act_plan_qty);
                                            Log.d(getString(R.string.tag), "remain_qty =  " + remain_qty +"("+plan_qty+"-"+act_plan_qty+")");
                                            Clear_data();
                                        }
                                    })
                                    .show();

                        }else {

                            Double new_plan = Double.parseDouble(editText.getText().toString().trim());
                            plan_qty = new_plan;
                            txt_total.setText(String.format("%.2f/%.2f",act_scan_qty,plan_qty));

                            remain_qty = (plan_qty - act_plan_qty);

                            Clear_data();
                        }
                    }

                });
        dialog.setCustomView(editText);
        dialog.show();
    }


    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);
            json.put("section", section);

            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) {
                        e.printStackTrace();
                    }
                }
            }.execute();

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

    }


    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 = item.getString("act_qty") + "/" + item.getString("qty");
//                String unit = item.get("")
                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, 17, 38, 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(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 = (act_plan_qty+sum_act_qty);
            txt_total.setText(String.format("%.2f/%.2f",act_scan_qty,plan_qty));

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


    @Override
    public void onClick(View v) {
        switch (v.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();
                    Check_total();
                }
                break;
        }
    }

    private void Clear_data() {
        Unblock_button();
        b_confirm = false;
        scan_label = false;
        stock_fifo.clear();
        repack_label.clear();
        Get_StockFifo(str_part_no, remain_qty, "", "");
    }

    private void Check_total() {
        Log.d(getString(R.string.tag), "Check_total: " + act_scan_qty+" | "+plan_qty);

        if (act_scan_qty < plan_qty) {
            new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("WARNING")
                    .setContentText("Quantity is small. Proceed with the process?")
                    .setCancelText("No")
                    .showCancelButton(true)
                    .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sDialog) {
                                Unblock_button();
                            sDialog.cancel();
                        }
                    })
                    .setConfirmText("Yes")
                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sDialog) {
                            sDialog.cancel();
                            if (payload_label.size() > 0) {
                                AlertConfirmPrint_Repack();

                            } else {
                                SendOutbound();
                            }

                        }
                    })
                    .show();
        }else {
            if (payload_label.size() > 0) {
                AlertConfirmPrint_Repack();

            } else {
                SendOutbound();
            }
        }
    }

    private void AlertConfirmPrint_Repack() {
        try {
            SweetAlertDialog sweetAlertDialog = new SweetAlertDialog(OutboundDetail_Activity.this, SweetAlertDialog.SUCCESS_TYPE);
            sweetAlertDialog.setTitleText("SUCCESS");
            sweetAlertDialog.setContentText("Do you want to print the new " + map_payload.get("1").getQty() + " " + label.getString("lbl_unit") + " label?");
            sweetAlertDialog.setCancelText("No");
            sweetAlertDialog.showCancelButton(true);
            sweetAlertDialog.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                @Override
                public void onClick(SweetAlertDialog sDialog) {
                    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());
                        Command_Print();
                    }
                    sDialog.cancel();
                }
            });
            sweetAlertDialog.setConfirmText("Yes");
            sweetAlertDialog.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                @Override
                public void onClick(SweetAlertDialog sDialog) {
                    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());
                        Command_Print();
                    }
                    sDialog.cancel();
                }
            });
            sweetAlertDialog.show();

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

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

        PRINT_TIMES = 0;
        LABEL_QTY = payload_print.size();
        stopThread = false;
        Log.d("Thread.sleep", "stopThread: " + stopThread + ":" + PRINT_TIMES+"-->"+LABEL_QTY);

        ExampleRunnable runnable = new ExampleRunnable();
        new Thread(runnable).start();

    }

    class ExampleRunnable implements Runnable {

        @Override
        public void run() {
            while (!stopThread) {
                try {
                    Print_Label();
                    Thread.sleep(1000);
                    Log.d("Thread.sleep2", "stopThread: " + stopThread);

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

    private void Print_Label() {
        Log.d(getString(R.string.tag), "PRINT_TIMES1: " + PRINT_TIMES+"="+LABEL_QTY);

        PRINT_TIMES = (PRINT_TIMES + 1);
        Log.d(getString(R.string.tag), "PRINT_TIMES2: " + PRINT_TIMES+"="+LABEL_QTY);

        if (PRINT_TIMES == LABEL_QTY){
            stopThread = true;
            Log.d("Thread.sleep if", "stopThread: " + stopThread);
        }

        Payload_list payload_l = payload_print.get(PRINT_TIMES-1);
        String payload = payload_l.getPayload();
        String scrap_flg = payload_l.getScrap_flg();
        Log.d("payload", payload_l.getId()+"|" + payload);

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

            String tmp = String.format(
                    "%s %s%s%s\r\n%s"
                    , "PST"
                    , Settings.getMgmtList().get("printer_preset")
                    , Settings.getPrinter()
                    , scrap_flg
//                    , Settings.getDeviceNo()
                    , payload

            );

            Log.d(getString(R.string.tag), "payload: " + payload);
            new AsyncTcpClient(getApplicationContext(),
                    Settings.getMgmtList().get("printer_server_host"),
                    Integer.parseInt(Settings.getMgmtList().get("printer_server_port")),
                    tmp
            ) {
                @Override
                protected void onFinished(String response) {
                    Log.d(getString(R.string.tag), "TCP response: " + response);

                    if (response.equals("OK")) {

                        if (stopThread == true) {
                            alert.dismiss();
                            AlertConfirmPrint();
                        }
                    } else {
                        Unblock_button();
                        alert.dismiss();
                        new SweetAlertDialog(OutboundDetail_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText("Can't connect to print server")
                                .show();

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

    private void AlertConfirmPrint() {
        new SweetAlertDialog(OutboundDetail_Activity.this, SweetAlertDialog.SUCCESS_TYPE)
                .setTitleText("SUCCESS")
                .setContentText("Click 'No' if nothing printed out?")
                .setCancelText("No")
                .showCancelButton(true)
                .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sDialog) {
                        Unblock_button();
                        sDialog.cancel();
                    }
                })
                .setConfirmText("Yes")
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sDialog) {
                        sDialog.cancel();
                        Confirm_Label();
                    }
                })
                .show();

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

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

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

        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("package_id", label.getString("control_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"); // OUT_STORE = 3;
                    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), "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();
                            }
                        }else{
                            Unblock_button();
                            showWarning("Can't Outbound");
                        }

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

                }
            }.execute();

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

    private void SendInbound() {
        Log.d(getString(R.string.tag), "SendInbound map_payload: " + map_payload.size());
        Log.d(getString(R.string.tag), "SendInbound repack_label: " + repack_label.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);

                for (String K : repack_label.keySet()){
                    JSONObject item_label = repack_label.get(K);
                    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.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("lbl_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),"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");
                            new SweetAlertDialog(OutboundDetail_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(error)
                                    .show();

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

    private void SendOutbound_repack() {
        Log.d(getString(R.string.tag), "SendInbound SendOutbound_repack: " +map_payload.size());
        Log.d(getString(R.string.tag), "label_id: " +map_payload.get("1").getId());

        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "OUTBOUND/SCHEDULE/DETAIL/CONFIRM");
            JSONArray jsonArray = new JSONArray();
//
            for (String K : repack_label.keySet()) {
                JSONObject item_label = repack_label.get(K);
                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("package_id", item_label.getString("lbl_unit"));
                jsonParams.put("unit_qty", item_label.getString("lbl_unit"));
                jsonParams.put("package_qty", item_label.getString("pick_qty"));
                jsonParams.put("qty", item_label.getString("pick_qty"));

                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", map_payload.get("1").getId());
                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), "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);
                            finish();

                        }else{
                            Unblock_button();
                            showWarning("Can't Outbound");
                        }

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

                }
            }.execute();

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

    }

    @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));
            Log.d(getString(R.string.tag), "getActionType:" + Settings.getActionType().trim());

            if (tokens.length == 7){
                Scan_label(data);

            }else {
                showWarning("Invalid QR Code!!");
            }
            Utils.hideKeyboardFrom(getApplicationContext(), default_view);

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

    private void Scan_label(String data) {
        Log.d(getString(R.string.tag), "Scan_label getActionType:" + Settings.getActionType().trim());

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

        t_order = tokens[0].trim();
        t_part = tokens[1].trim();
        t_dwg = tokens[2].trim();
        t_lot_no = tokens[3].trim();
        t_qty = tokens[4].trim();
        t_rank = tokens[5].trim();
        t_box = tokens[6].trim();//key of label

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

        String str_part_no_sub = txt_part_no.getText().toString().trim().substring(4);
        if (tokens[1].substring(4).trim().equals(str_part_no_sub)){
            Check_label();

        }else {
            showWarning("Part No. not match!!");
        }
    }


    private void Check_label() {
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "LABEL/DETAIL");
            json.put("order_no", t_order);
            json.put("parts_no", t_part);
            json.put("lot_no", t_lot_no);
            json.put("serial_no", t_box);

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

                                new AsyncHttpClient(getApplicationContext(),
                                        Settings.getMgmtList().get("web_api") + "/packing_standard_master.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){
                                                new SweetAlertDialog(OutboundDetail_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                                        .setTitleText("ERROR")
                                                        .setContentText("Not found packing standard")
                                                        .show();
                                                return;
                                            }else {
                                                act_stock_qty = jArray.getJSONObject(0).getDouble("qty");
                                                Log.d(getString(R.string.tag), "act_stock_qty: " + act_stock_qty);

                                                String key_map = label.getString("lot_no").trim()+label.getString("last_location_id");

                                                if (stock_fifo.containsKey(key_map)) {
                                                    Log.d(getString(R.string.tag), "have: ");
                                                    JSONObject item = stock_fifo.get(key_map);

                                                    //check Duplicated
                                                    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!!");

                                                        //remove

                                                    } else {
                                                        scan_label = true;

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

                                                        if (pre_act_qty > plan_qty){//check over plan
                                                            Log.d(getString(R.string.tag), "repack: ");
                                                            Double pick_qty = (plan_qty - act_scan_qty);
                                                            Log.d(getString(R.string.tag), "repack: "+pick_qty);

                                                            repack_label.put(label.getString("id"), label);
                                                            Issue_RepackLabel(label, pick_qty);

                                                            label.put("pick_qty", pick_qty); // Store the current picking qty
                                                            label.put("repack_flag", "1");

                                                            item.put("act_qty", pick_qty + item.getDouble("act_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);

                                                        } else {
                                                            Log.d(getString(R.string.tag), "All box: ");
//                                                            label.put("pick_qty", label.getDouble("act_stock_qty")); // Store the current picking qty
//                                                            item.put("act_qty", item.getDouble("act_qty")+label.getDouble("act_stock_qty"));
                                                            label.put("repack_flag", "0");
                                                            label.put("pick_qty", act_stock_qty);
                                                            item.put("act_qty", item.getDouble("act_qty")+act_stock_qty);
                                                            item.put("qty",item.getDouble("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 {//new lot_no & location
                                                    scan_label = true;
                                                    Log.d(getString(R.string.tag), "no: plan_qty"+plan_qty+"/"+act_plan_qty);

//                                                    Double pre_act_qty = (label.getDouble("act_stock_qty")+act_scan_qty);
                                                    Double pre_act_qty = (act_stock_qty + act_scan_qty);
                                                    Log.d(getString(R.string.tag), "pre_act_qty: "+pre_act_qty+"/"+act_scan_qty);
                                                    Double pick_qty = (plan_qty - act_scan_qty);
                                                    Log.d(getString(R.string.tag), "pick_qty: "+pick_qty);

//                                                    if (label.getDouble("act_stock_qty") < pick_qty) {
                                                    if (act_stock_qty < pick_qty) {
                                                        pick_qty = act_stock_qty;
                                                    }

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

//                                                    if (pick_qty != label.getDouble("act_stock_qty")) {

                                                    if (!Utils.CompareDouble(pick_qty,act_stock_qty )) {
                                                        // Automatic repack
                                                        Double finalPick_qty = pick_qty;
                                                        label.put("repack_flag", "1");
                                                        repack_label.put(label.getString("id"), label);
                                                        Issue_RepackLabel(label, finalPick_qty);
                                                    }else {
                                                        label.put("repack_flag", "0");
                                                    }

                                                    label.put("pick_qty", pick_qty);

                                                    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", pick_qty);// Store the current picking qty
                                                    j_a.put("act_qty", pick_qty);
                                                    j_a.put("label_list", label_tmps);
                                                    j_a.put("qty", "0");

                                                    stock_fifo.put(key_map, j_a);
                                                }
                                            }
                                            redrawStockFifo(null);
                                        }catch (JSONException e) {
                                            new SweetAlertDialog(OutboundDetail_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                                    .setTitleText("ERROR")
                                                    .setContentText(e.getMessage())
                                                    .show();
                                        }
                                    }
                                }.execute();
                            }catch (JSONException e){
                                e.printStackTrace();
                            }

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

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

    private void Issue_RepackLabel(JSONObject master_label, Double repack_qty) {
        payload_label.clear();
        payload_repack.clear();
        try {
            Log.d(getString(R.string.tag), "Issue_RepackLabel: " + master_label.getString("id").trim() + "/ "+repack_qty);

            JSONObject json = new JSONObject();
            json.put("cmd", "RELABELING/CONFIRM/PREPARE");
            json.put("ref_label_id", master_label.getString("id").trim());
            json.put("new_qty", repack_qty);
            json.put("user_id",Settings.getLoginUser().getId());

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

                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        String status = jsonObject.getString("status");

                        if (status.equals("success")) {
                            String value = jsonObject.getString("value");
                            JSONArray jArray = new JSONArray(value);

                            for (int i = 0; i < jArray.length(); i++) {
                                String  scrap_flg =  jArray.getJSONObject(i).getString("scrap_flg").trim();
                                if(scrap_flg.trim().equals("1")){
                                    scrap_flg =  "-SC";
                                }else {
                                    scrap_flg =  "";
                                }

                                map_payload.put(String.valueOf(i), new Payload_list(
                                        jArray.getJSONObject(i).getString("id"),
                                        scrap_flg,
                                        jArray.getJSONObject(i).getString("payload"),
                                        jArray.getJSONObject(i).getString("issue_qty")
                                ));
                                
                                payload_label.add( new Payload_list(
                                        jArray.getJSONObject(i).getString("id"),
                                        scrap_flg,
                                        jArray.getJSONObject(i).getString("payload"),
                                        jArray.getJSONObject(i).getString("issue_qty")
                                ));
                                
                                if (i == 0){
                                    payload_repack.add( new Payload_list(
                                            jArray.getJSONObject(i).getString("id"),
                                            scrap_flg,
                                            jArray.getJSONObject(i).getString("payload"),
                                            jArray.getJSONObject(i).getString("issue_qty")
                                    ));
                                }
                            }

                            Log.d(getString(R.string.tag), "payload: " + payload_label.size()+"|"+payload_repack.size());
                        } else {
                            showWarning("Can't prepare the label!!");
                        }

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

                }
            }.execute();

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



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

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

                case P3:
                    Clear_data();
                    break;

                case P4://confirm
                    if (b_confirm == false) {
                        Block_button();
                        Check_total();
                    }
                    break;
            }
        }

        return super.onKeyUp(keyCode, event);
    }

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