package com.tomas.ht_mast;

import static android.content.ContentValues.TAG;

import android.content.DialogInterface;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ScrollView;
import android.widget.TableLayout;
import android.widget.TextView;
import android.widget.Toast;

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_mast.Adapter.ItemLabel_out_sc_Adapter;
import com.tomas.ht_mast.ListData.ItemFifo_list;
import com.tomas.ht_mast.ListData.ItemHisto_list;
import com.tomas.ht_mast.ListData.LabelItem_out_sh_list;
import com.tomas.ht_mast.ListData.Payload_list;
import com.tomas.ht_mast.ListData.Payload_list_out;
import com.tomas.ht_mast.lib.ActionType;
import com.tomas.ht_mast.lib.AlertProgress;
import com.tomas.ht_mast.lib.KeyMapping;
import com.tomas.ht_mast.lib.Scanner;
import com.tomas.ht_mast.lib.Settings;
import com.tomas.ht_mast.lib.common.AsyncHttpClient;
import com.tomas.ht_mast.lib.common.AsyncTcpClient;
import com.tomas.ht_mast.lib.common.Utils;

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

import java.text.DecimalFormat;
import java.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 cn.pedant.SweetAlert.SweetAlertDialog;

public class Outbound_Activity extends Scanner implements View.OnClickListener {
    Calendar calendar;
    SimpleDateFormat date;
    DecimalFormat decimalFormat, format_comma;
    Bundle bundle;
    String str_header, str_type, str_title, str_id, str_part_no, str_name, str_date, t_order, t_part, t_dwg, t_lot_no, t_qty, t_rank, t_box, l_location;
    String datetime_to_server, str_is_status,str_mode, str_sch_id, str_order, str_lot_no, str_part_name,str_plan_qty,str_act_qty,label_id,label_id_old,keyitem
            , qty_old, str_location_id, label_id_new_re, label_id_new_unit,status_print,t_part_sub;
    TextView txt_user, txt_device, txt_header, txt_date, txt_parts_no, txt_parts_name, txt_order_no ;
    Button btn_confirm, btn_clear;
    TableLayout tbl_stock_fifo;
    ScrollView scr_contents;
    TextView txt_total;
    EditText  edit_tatal;
    JSONObject schedule, label;
    Map<String, JSONObject> stock_fifo, allow_locations, scan_label_history;
    ItemLabel_out_sc_Adapter label_adapter;
    Double sum_total = 0.0,d_act_qty = 0.0,d_plan_qty =0.0, d_total_net = 0.0,sum_qty = 0.0 , f_act_qty = 0.0, f_plan_qty = 0.0 ;
    Integer LABEL_QTY, PRINT_TIMES;
    List<Payload_list_out> payload_list;
    List<Payload_list_out> payload_list_2;
    List<Payload_list_out> payload_list_print;
    List<ItemFifo_list> itemFifo_lists;
    Map<String,ItemFifo_list> map_fifo;
    AlertProgress alert;
    Map<String, ItemHisto_list> map_history;
    private volatile boolean stopThread = true;
    Double new_qty = 0.0, amon_new_lablr_print = 0.0;
    RecyclerView view_data;
    boolean b_confirm;

    Map<String, LabelItem_out_sh_list> map_label , map_label_repck;
    List<LabelItem_out_sh_list> list_label;
    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_);
        default_view = (EditText) findViewById(R.id.txt_label_issue_tmp);

        b_confirm = false;

        allow_locations = new LinkedHashMap<>();
        stock_fifo = new LinkedHashMap<>();
        scan_label_history = new LinkedHashMap<>();
        list_label = new ArrayList<LabelItem_out_sh_list>();
        map_fifo = new LinkedHashMap<>();
        map_history = new LinkedHashMap<>();

        payload_list = new ArrayList<Payload_list_out>();
        payload_list_2 = new ArrayList<Payload_list_out>();
        map_label = new LinkedHashMap<>();
        map_label_repck = new LinkedHashMap<>();
        itemFifo_lists = new ArrayList<ItemFifo_list>();
        alert = new AlertProgress(Outbound_Activity.this);

        decimalFormat = new DecimalFormat("##0.00");
        format_comma = new DecimalFormat("#,##0");
        default_view = (EditText) findViewById(R.id.txt_label_issue_tmp);

        txt_user = (TextView) findViewById(R.id.txt_user);
        txt_device = (TextView) findViewById(R.id.txt_device);
        txt_header = (TextView) findViewById(R.id.txt_header);
        txt_date = (TextView)findViewById(R.id.txt_date);
        txt_parts_no = (TextView)findViewById(R.id.txt_part_no);
        txt_parts_name = (TextView)findViewById(R.id.txt_part_name);
        txt_total = (TextView) findViewById(R.id.txt_total);
        txt_order_no = (TextView)findViewById(R.id.txt_order_no);


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

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

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

        txt_user.setText("User : "+ Settings.getLoginUser().getName());
        txt_device.setText("Device : "+ Settings.getDeviceNo());
        sum_qty = 0.0;
        sum_total = 0.0;
        amon_new_lablr_print = 0.0;
        txt_date.setText(str_date);
        bundle = getIntent().getExtras();
        btn_confirm = (Button)findViewById(R.id.btn_confirm);
        str_mode = Settings.getActionType().toString();
        if (str_mode.trim().equals(ActionType.Type.OUTBOUND_WORK.toString()) || str_mode.trim().equals(ActionType.Type.OUTBOUND_PRODUCTION.toString())) {
            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_plan_qty = bundle.getString("plan_qty");
            str_act_qty = bundle.getString("act_qty");

            sum_total = Double.parseDouble(str_act_qty);
            d_act_qty = Double.parseDouble(str_act_qty);
            d_plan_qty = Double.parseDouble(str_plan_qty);
            d_total_net = d_plan_qty - d_act_qty ;

            if( Utils.CompareDouble(d_act_qty ,0.0)){
                d_plan_qty = d_plan_qty - d_act_qty ;
            }else{

            }

            txt_total.setText(format_comma.format(Math.round(d_act_qty)) +"/"+format_comma.format(Math.round(d_plan_qty)));
            txt_parts_no.setText(str_part_no);
            txt_parts_name.setText(str_part_name);
            txt_order_no.setText(str_order);
        }

        try {
            if (str_mode.trim().equals(ActionType.Type.OUTBOUND_WORK.toString()) || str_mode.trim().equals(ActionType.Type.OUTBOUND_PRODUCTION.toString())) {
               f_plan_qty = new Double(str_plan_qty).doubleValue();
               f_act_qty = new Double(str_act_qty).doubleValue();

                Log.d(getString(R.string.tag), "get Location & StockFifo");
                Get_Location(Settings.getLoginUser().getDepartment());
                Get_StockFifo(str_part_no
                        , f_plan_qty - f_act_qty
                        , ""
                        , ""
                );
                Get_LabelScanHistory(str_sch_id);
            } else {
                Log.d(getString(R.string.tag), "Schedule isn't in bundle.");
                schedule = null;
                Get_Location(Settings.getLoginUser().getDepartment());
            }

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

            txt_device.setText("Device : " + Settings.getDeviceNo());

            if(str_mode.trim().equals(ActionType.Type.OUTBOUND_WORK.toString())){
                txt_header.setText("Work Outbound");
            }else {
                txt_header.setText("Production Outbound");
            }
            txt_date.setText(str_date);
        } catch (Exception e) {
            Log.d(getString(R.string.tag), e.getMessage());
        }

        edit_tatal.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                Log.d("LOGER" , s.toString().trim()+"");
                Log.d("count" , count + "");
                if(s.length() == 0 || s.equals("") || edit_tatal.getText().equals("")){
                    d_plan_qty = 0.0;
                }else{
                    d_plan_qty = Double.parseDouble(s.toString());

                    f_plan_qty = d_plan_qty;
                    Get_StockFifo(str_part_no
                            , f_plan_qty - f_act_qty
                            , ""
                            , ""
                    );
                    txt_total.setText(Math.round(sum_total)+"/"+Math.round(d_plan_qty));
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }

    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++){
                            map_fifo.put(jArray.getJSONObject(i).getString("location_id").trim()+jArray.getJSONObject(i).getString("lot_no").trim(), new ItemFifo_list(
                                    jArray.getJSONObject(i).getString("id"),
                                    jArray.getJSONObject(i).getString("lot_no"),
                                    jArray.getJSONObject(i).getString("location_id"),
                                    "0",
                                    "",
                                    jArray.getJSONObject(i).getString("qty"),
                                    ""
                            ));
                        }

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

            }.execute();

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

    private void Update_FifoHistoryList() {

        if (map_history.size() == 0) return;

//        for (String key : map_history.keySet()){
//            ItemHisto_list list = map_history.get(key);
//            Log.d(getString(R.string.tag), "list.getId() : " + list.getId());
////        }
////             for (int i = 0; i < map_history.size(); i++){
////            ItemHisto_list list = map_history.get(i);
//            String a = list.getId();
//            Log.d(getString(R.string.tag), "list.getId() : " + a);
//            String Key_map = list.getLocation().trim()+list.getLot_no();
//            Log.d(getString(R.string.tag), "list.Key_map : " + Key_map);
////            String label_id_new = list.getId().trim();
//
//            if (map_fifo.containsKey(Key_map)) {
//                Log.d(getString(R.string.tag), "containsKey: if" + Key_map + "label_id "+ label_id);
//                ItemFifo_list item = map_fifo.get(Key_map);
//
//                for(String key2 : map_fifo.keySet()) {
//                    ItemFifo_list item2 = map_fifo.get(key2);
//                    keyitem = key2;
//                    if(Key_map.trim().equals(keyitem)){
//                        Integer qty = Integer.parseInt(item2.getQty());
//                        Integer qty_h = Integer.parseInt(list.getQty());
//                        Integer sum = qty +qty_h ;
//                        item.setQty(sum.toString());
//                        map_fifo.put(Key_map, item);
//                        View_data();
//                    }else{
//
//                    }
//
//                }
//            }else{
//
//
//                showWarning("Can't find it !!");
//                break;
//            }
//
//        }


    }
    private void Get_LabelScanHistory(String sch_id) {
        map_history.clear();
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "QUERY/LABEL/SCAN/HISTORY");
            json.put("ref_sch_id", sch_id);

            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);
                        Log.d(getString(R.string.tag), "jArray: " + jArray.length());
                        for(int i=0;i<jArray.length();i++) {
                            map_history.put(jArray.getJSONObject(i).getString("id").trim(),
                                    new ItemHisto_list(
                                    jArray.getJSONObject(i).getString("id"),
                                    jArray.getJSONObject(i).getString("lot_no"),
                                    jArray.getJSONObject(i).getString("location_id"),
                                    jArray.getJSONObject(i).getString("qty"),
                                    "",
                                    ""));
                            Log.d(TAG, "id map_history: " + jArray.getJSONObject(i).getString("id") );
                            Log.d(getString(R.string.tag), "map_history for: " + map_history.size());
                        }
                        Log.d(getString(R.string.tag), "map_history 1: " + map_history.size());

                    }catch (JSONException e) {
                        e.printStackTrace();
                    }
                    Log.d(getString(R.string.tag), "map_history 2: " + map_history.size());
                    Update_FifoHistoryList();

                }
            }.execute();

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

    }

    private void Get_Location(String section) {
        allow_locations.clear();
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "list");

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/location_master.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++) {
                            allow_locations.put(
                                    jArray.getJSONObject(i).getString("id")
                                    , jArray.getJSONObject(i)
                            );
                        }

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

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

    }

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

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

            case R.id.btn_confirm:
                if (b_confirm == false) {
                    Block_button();
                    Check_In_out();
                }
                break;
        }
    }

    private void Block_button() {
        b_confirm = true;
        btn_confirm.setEnabled(false);
        btn_confirm.setBackgroundResource(R.drawable.button_background_gray);
    }

    private void Unblock_button() {
        b_confirm = false;
        btn_confirm.setEnabled(true);
        btn_confirm.setBackgroundResource(R.drawable.button_background_blue);
    }

    private void Clear_data() {
        b_confirm = false;
        map_label.clear();
        map_fifo.clear();
        map_label_repck.clear();
        map_history.clear();
        Get_StockFifo(str_part_no
                , f_plan_qty - f_act_qty
                , ""
                , ""
        );
        Get_LabelScanHistory(str_sch_id);
        sum_total = Double.parseDouble(str_act_qty);
        View_data();
    }


    @Override
    public void processData(String data, DecodeResult.Result result, String codeType) {
        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));

            data = data.trim();
            if (tokens.length == 7) {
                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
                Log.d(getString(R.string.tag), "token:" + tokens.length);
                t_part_sub = t_part.trim().substring(4);
                Log.d(TAG, "processData: t_part_sub"+ t_part_sub + "str_part_no "+str_part_no);

                String str_part_no_sub = txt_parts_no.getText().toString().trim().substring(4);
                Log.d(TAG, "processData: str_part_no_sub"+str_part_no_sub);

                if (str_part_no_sub.equals(t_part_sub)) {
                    Log.d(TAG, "processData:str_part_no_sub " + str_part_no +"t_part_sub "+t_part_sub);
                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() != 1) {
                                    showWarning("Label data not found!!");
                                    return;
                                }
                                if (sum_total >= d_plan_qty) {
                                    showWarning("The planned quantity has been exceeded.");
                                    return;
                                }
                                String label_id_chek = jArray.getJSONObject(0).getString("id");


                                label = jArray.getJSONObject(0);

                                // Check label status
                                String status_label = jArray.getJSONObject(0).getString("status").trim();
                                String lbl_part_no = jArray.getJSONObject(0).getString("lbl_part_no").trim();
                                if (status_label.trim().equals("2") && lbl_part_no.trim().substring(4).equals(t_part_sub)) {
//                                    Double qty_label = (sum_total + Math.round(Double.parseDouble(jArray.getJSONObject(0).getString("act_stock_qty").trim())));
                                    String keymap_check = jArray.getJSONObject(0).getString("last_location_id").trim() + jArray.getJSONObject(0).getString("lot_no").trim();

                                    if(map_label.size() > 0){
//                                        for (String key : map_label.keySet()) {
//                                            LabelItem_out_sh_list item = map_label.get(key);
//                                            if (label_id_chek.trim().equals(item.getLabel_id())) {
                                                if (map_label.containsKey(label_id_chek)) {
                                                    new SweetAlertDialog(Outbound_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                                            .setTitleText("WARNING")
                                                            .setContentText("This Box has been scanned.")
                                                            .setCancelText("Delete")
                                                            .showCancelButton(true)
                                                            .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                                                @Override
                                                                public void onClick(SweetAlertDialog sDialog) {
                                                                    sDialog.cancel();
                                                                    map_label.remove(label_id_chek);
                                                                    map_fifo.remove(keymap_check);
                                                                    Log.d(getString(R.string.tag), "delete size = " + map_label.size());
                                                                    View_data();

                                                                }
                                                            })
                                                            .setConfirmText("Continue")
                                                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                                                @Override
                                                                public void onClick(SweetAlertDialog sDialog) {
                                                                    sDialog.cancel();
                                                                    View_data();

                                                                }
                                                            })
                                                            .show();
//                                                }else{
//
//                                                }
                                            }else{
                                                map_label.put(jArray.getJSONObject(0).getString("id").trim(), new LabelItem_out_sh_list(
                                                        "",
                                                        jArray.getJSONObject(0).getString("id").trim(),
                                                        jArray.getJSONObject(0).getString("lbl_order_no").trim(),
                                                        jArray.getJSONObject(0).getString("lbl_part_no").trim(),
                                                        jArray.getJSONObject(0).getString("lbl_part_name").trim(),
                                                        jArray.getJSONObject(0).getString("lbl_dwg_no").trim(),
                                                        jArray.getJSONObject(0).getString("lot_no").trim(),
                                                        String.valueOf(Math.round(Double.parseDouble(jArray.getJSONObject(0).getString("act_stock_qty").trim()))),
                                                        jArray.getJSONObject(0).getString("act_stock_qty").trim(),
                                                        jArray.getJSONObject(0).getString("lbl_rank").trim(),
                                                        jArray.getJSONObject(0).getString("serial_no").trim(),
                                                        jArray.getJSONObject(0).getString("lbl_unit").trim(),
                                                        jArray.getJSONObject(0).getString("control_unit").trim(),
                                                        "0",
                                                        jArray.getJSONObject(0).getString("lbl_supplier_id").trim(),
                                                        jArray.getJSONObject(0).getString("lbl_supplier").trim(),
                                                        jArray.getJSONObject(0).getString("lbl_ng").trim(),
                                                        jArray.getJSONObject(0).getString("status").trim(),
                                                        "0",
                                                        jArray.getJSONObject(0).getString("issue_stock_qty").trim(),
                                                        jArray.getJSONObject(0).getString("last_location_id").trim() == "null" ? "" : jArray.getJSONObject(0).getString("last_location_id"),
                                                        jArray.getJSONObject(0).getString("last_location_name").trim() == "null" ? "" : jArray.getJSONObject(0).getString("last_location_name"),
                                                        "",
                                                        "",
                                                        "",
                                                        ""));


                                                label_id_new_unit = jArray.getJSONObject(0).getString("lbl_unit");
                                                label_id = jArray.getJSONObject(0).getString("id");
                                                sum_qty = d_plan_qty - sum_total;
                                                Double pick_qty = jArray.getJSONObject(0).getDouble("act_stock_qty");
                                                Double p1 = Double.parseDouble(sum_qty.toString());
                                                Log.d(TAG, "d_plan_qty: " + d_plan_qty);
                                                Log.d(TAG, "sum_total: " + sum_total);
                                                Integer p2 = pick_qty.intValue();
                                                if (p2 > p1) {
                                                    new_qty = pick_qty - sum_qty;
                                                    amon_new_lablr_print = sum_qty - pick_qty;
                                                    Log.d(TAG, new_qty + "new_qty: =" + pick_qty + "-" + sum_qty);
                                                    Log.d(TAG, amon_new_lablr_print + "amon_new_lablr_print: =" + sum_qty + "-" + pick_qty);
                                                    Prepare_Lbael_2();
                                                    Update_fifo(jArray.getJSONObject(0).getString("last_location_id"), jArray.getJSONObject(0).getString("issue_stock_qty").trim(), jArray.getJSONObject(0).getString("lot_no").trim());
                                                }
                                                Update_fifo(jArray.getJSONObject(0).getString("last_location_id"), jArray.getJSONObject(0).getString("issue_stock_qty").trim(), jArray.getJSONObject(0).getString("lot_no").trim());


                                            }
//                                        }
                                    }else {
                                        map_label.put(jArray.getJSONObject(0).getString("id").trim(), new LabelItem_out_sh_list(
                                                "",
                                                jArray.getJSONObject(0).getString("id").trim(),
                                                jArray.getJSONObject(0).getString("lbl_order_no").trim(),
                                                jArray.getJSONObject(0).getString("lbl_part_no").trim(),
                                                jArray.getJSONObject(0).getString("lbl_part_name").trim(),
                                                jArray.getJSONObject(0).getString("lbl_dwg_no").trim(),
                                                jArray.getJSONObject(0).getString("lot_no").trim(),
                                                String.valueOf(Math.round(Double.parseDouble(jArray.getJSONObject(0).getString("act_stock_qty").trim()))),
                                                jArray.getJSONObject(0).getString("act_stock_qty").trim(),
                                                jArray.getJSONObject(0).getString("lbl_rank").trim(),
                                                jArray.getJSONObject(0).getString("serial_no").trim(),
                                                jArray.getJSONObject(0).getString("lbl_unit").trim(),
                                                jArray.getJSONObject(0).getString("control_unit").trim(),
                                                "0",
                                                jArray.getJSONObject(0).getString("lbl_supplier_id").trim(),
                                                jArray.getJSONObject(0).getString("lbl_supplier").trim(),
                                                jArray.getJSONObject(0).getString("lbl_ng").trim(),
                                                jArray.getJSONObject(0).getString("status").trim(),
                                                "0",
                                                jArray.getJSONObject(0).getString("issue_stock_qty").trim(),
                                                jArray.getJSONObject(0).getString("last_location_id").trim() == "null" ? "" : jArray.getJSONObject(0).getString("last_location_id"),
                                                jArray.getJSONObject(0).getString("last_location_name").trim() == "null" ? "" : jArray.getJSONObject(0).getString("last_location_name"),
                                                "",
                                                "",
                                                "",
                                                ""));


                                        label_id_new_unit = jArray.getJSONObject(0).getString("lbl_unit");
                                        label_id = jArray.getJSONObject(0).getString("id");
                                        sum_qty = d_plan_qty - sum_total;
                                        Double pick_qty = jArray.getJSONObject(0).getDouble("act_stock_qty");
                                        Double p1 = Double.parseDouble(sum_qty.toString());
                                        Log.d(TAG, "d_plan_qty: " + d_plan_qty);
                                        Log.d(TAG, "sum_total: " + sum_total);
                                        Integer p2 = pick_qty.intValue();
                                        if (p2 > p1) {
                                            new_qty = pick_qty - sum_qty;
                                            amon_new_lablr_print = sum_qty - pick_qty;
                                            Log.d(TAG, new_qty + "new_qty: =" + pick_qty + "-" + sum_qty);
                                            Log.d(TAG, amon_new_lablr_print + "amon_new_lablr_print: =" + sum_qty + "-" + pick_qty);
                                            Prepare_Lbael_2();
                                            Update_fifo(jArray.getJSONObject(0).getString("last_location_id"), jArray.getJSONObject(0).getString("issue_stock_qty").trim(), jArray.getJSONObject(0).getString("lot_no").trim());
                                        }
                                        Update_fifo(jArray.getJSONObject(0).getString("last_location_id"), jArray.getJSONObject(0).getString("issue_stock_qty").trim(), jArray.getJSONObject(0).getString("lot_no").trim());
                                    }

                                } else {
                                    new SweetAlertDialog(Outbound_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                            .setTitleText("WARNING")
                                            .setContentText("Invalid Label!")
                                            .show();
                                }

                                Log.d(getString(R.string.tag), "map_label : " + map_label.size());
                                label_id = label.getString("id");
                                Log.d(getString(R.string.tag), "label_id : " + label_id);

                                btn_confirm.setEnabled(true);
                                btn_confirm.setBackgroundResource(R.drawable.button_background_blue);


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

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

            }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 SendOutbound() {
        Log.d(getString(R.string.tag),"SendOutbound "+ str_mode);
        try {
            JSONObject json = new JSONObject();
            Map<String, String> jsonParams = new HashMap<>();//sample data
            json.put("cmd", "OUTBOUND/SCHEDULE/DETAIL/CONFIRM");
            JSONArray jsonArray = new JSONArray();
            for (String key : map_label.keySet()){
                LabelItem_out_sh_list item = map_label.get(key);

                String Label_id = item.getLabel_id().trim();
                String Status = item.getStatus().trim();
                Log.d(TAG, "SendOutbound: label_id_old :" + label_id_old+ " Label_id " +Label_id +  "Status:"+ Status);

                if(Status.trim().equals("0")) {
                   jsonParams.put("ref_sch_id", str_sch_id);
                } else{
                   jsonParams.put("ref_sch_id", "");
                }
                    jsonParams.put("item_id", item.getPart_no().trim());
                    jsonParams.put("item_name", item.getPart_name().trim());
                    jsonParams.put("lot_no", item.getLot_no().trim());
                    jsonParams.put("package_id", item.getUnit().trim());
                    jsonParams.put("unit_qty",  item.getControl_unit().trim());
                    jsonParams.put("package_qty", item.getIssue_qty());
                    jsonParams.put("qty", item.getIssue_qty());
                    jsonParams.put("location_id", item.getLast_location_id().trim());
                    jsonParams.put("location_name", item.getLast_location_name().trim().equals("null") ? "" : item.getLast_location_name());
                    jsonParams.put("label_id", item.getLabel_id());
                    jsonParams.put("inspection_flg", "0");
                    jsonParams.put("status", "2"); // OUT_STORE = 2;
                    jsonParams.put("slip_divide", "4");
                    jsonParams.put("create_user_id", Settings.getLoginUser().getId());
                    jsonParams.put("ng", item.getLbl_ng());
                    jsonParams.put("supplier_id", item.getLbl_supplier_id());
                    jsonParams.put("supplier_name", item.getLbl_supplier());
                    jsonParams.put("factory_code", item.getLast_location_id());
                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) {
                    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) {
                            SendInbound_Re();
                        }else{
                            Unblock_button();
                            showWarning("Can't Outbound");
                        }

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

                }
            }.execute();
        }catch (Exception e) {
            Unblock_button();
            new SweetAlertDialog(Outbound_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {

        finish();
    }

    private void Prepare_Lbael_2() {
        Integer n = 0;
        try {
            JSONObject json = new JSONObject();
//            json.put("cmd", "LABEL/DETAIL");
            json.put("cmd", "RELABELING/CONFIRM/PREPARE");
            json.put("ref_label_id", label_id );
            json.put("new_qty", String.valueOf(decimalFormat.format(Math.abs(new_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.trim().equals("error")){
                            String error = jsonObject.getString("error");
                            new SweetAlertDialog(Outbound_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(error)
                                    .show();
                        }else {
                            String value = jsonObject.getString("value");
                            JSONArray jArray = new JSONArray(value);
                            LABEL_QTY = jArray.length();

                            payload_list.clear();
                            for (int i = 0; i < jArray.length(); i++) {
                                String  scrap_flg =  jArray.getJSONObject(i).getString("scrap_flg").trim();
                                if(scrap_flg.trim().equals("1")){
                                    scrap_flg =  "-SC";
                                }else {
                                    scrap_flg =  "";
                                }
                                payload_list.add(new Payload_list_out(
                                        jArray.getJSONObject(i).getString("id"),
                                        scrap_flg,
                                        jArray.getJSONObject(i).getString("payload"),
                                        jArray.getJSONObject(i).getString("issue_qty"),
                                        ""
                                ));
                            }

                            // เช็ค id label และแทนที่ id label เดิม
                            for (int i = 0; i < payload_list.size(); i++) {
                                Payload_list_out list = payload_list.get(i);
                                String Key_map = label_id.trim();
                                String label_id_new = list.getId().trim();
                                Log.d(getString(R.string.tag), "Key_map: " + Key_map + "label_id " + label_id_new);
                                for (String key : map_label.keySet()){
                                    LabelItem_out_sh_list item = map_label.get(key);
                                    if(item.getLabel_id().trim().equals(label_id)){
                                        map_label_repck.put(list.getId() , new LabelItem_out_sh_list(
                                                "",
                                                label_id,
                                                item.getOrder_no(),
                                                item.getPart_no(),
                                                item.getPart_name(),
                                                item.getDwg_no(),
                                                item.getLot_no(),
                                                item.getIssue_qty(),
                                                item.getIssue_stock_qty(),
                                                item.getRank(),
                                                item.getBox_no(),
                                                item.getUnit(),
                                                item.getControl_unit(),
                                                "1",
                                                item.getLbl_supplier_id(),
                                                item.getLbl_supplier(),
                                                item.getLbl_ng(),
                                                item.getStatus_label(),
                                                list.getQty(),
                                                item.getLabel_qty(),
                                                item.getLast_location_id(),
                                                item.getLast_location_name(),
                                                list.getId(),
                                                "",
                                                "",
                                                ""));

                                        label_id_new_re = list.getId();

                                    }
                                    Log.d(getString(R.string.tag), "map_label_repck: " + map_label_repck.size() +" label_id_new_re "+ label_id_new_re);
                                }
                            }

                            for (int i = 0; i < payload_list.size(); i++) {
                                Payload_list_out list = payload_list.get(i);
                                payload_list_2.add(new Payload_list_out(
                                        list.getId(),
                                        list.getScrap_flg(),
                                        list.getPayload(),
                                        list.getQty(),
                                        list.getStatus()
                                ));

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

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

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

        PRINT_TIMES = 0;
        stopThread = false;
        Log.d("Thread.sleep", "stopThread: " + stopThread + ":" + PRINT_TIMES);

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

    }
    private void AlertConfirmPrint() {
        new SweetAlertDialog(Outbound_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) {

                        if (map_label.containsKey(label_id_old)) {
                            LabelItem_out_sh_list item = map_label.get(label_id_old);

                            for(String key : map_label.keySet()) {
                                keyitem = key;
                                if(label_id_old.trim().equals(keyitem)){
                                    item.setLabel_id(label_id_old);
                                    map_label.put(label_id_old, item);
                                }
                            }
                        }
                        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() {
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "RELABELING/CONFIRM/CONFIRM");
            JSONArray jArray = new JSONArray();
            for (int i = 0; i < payload_list_2.size(); i++){
                Payload_list_out list = payload_list_2.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(Outbound_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(error)
                                    .show();
                        }
                    }catch (JSONException e) {
                        Unblock_button();
                        new SweetAlertDialog(Outbound_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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

    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_out payload_l = payload_list_2.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(Outbound_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 View_data() {
        itemFifo_lists.clear();
        sum_total = Double.valueOf(0);
        int no = 0;
        Log.d(getString(R.string.tag),"mapItem"+ String.valueOf(map_fifo.size()));
        for (String key : map_fifo.keySet()){
            ItemFifo_list item = map_fifo.get(key);
            itemFifo_lists.add(new ItemFifo_list(
                    String.valueOf(no+1),
                    item.getLot_no(),
                    item.getLocation(),
                    item.getQty(),
                    item.getLabel_id(),
                    item.getPlan_qty(),
                    item.getQty_sum()
            ));

            Double qty = Double.parseDouble(item.getQty());
            sum_total = (sum_total + qty);
            Log.d(getString(R.string.tag),"SUM1 "+ String.valueOf(sum_total));

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


        if (str_mode.trim().equals(ActionType.Type.OUTBOUND_WORK.toString()) || str_mode.trim().equals(ActionType.Type.OUTBOUND_PRODUCTION.toString())) {//Outbound Schedule
            //+act_qty

//            sum_total = (sum_total + d_plan_qty);
            Log.d(getString(R.string.tag), "sum_total = "+sum_total);
            txt_total.setText(format_comma.format(Math.round(sum_total))  + "/" + format_comma.format(Math.round(d_plan_qty)));
        }else {
            txt_total.setText(String.valueOf(format_comma.format(Math.round(sum_total))));


            if (map_label.size() == 0){

                str_part_no = "";
                str_part_name = "";
                str_lot_no = "";
            }
        }
    }

    public void Update_fifo(String lacation, String qty ,String lot_no) {
        Integer  num_label ;
        Double det = 0.0;

            String Key_map = lacation.trim()+lot_no.trim();
            Double qty_label = Double.parseDouble(qty.trim());


            Log.d(getString(R.string.tag),"SUM1 "+ String.valueOf(sum_total));

            if (map_fifo.containsKey(Key_map)) {
                Log.d(getString(R.string.tag), "containsKey: " + Key_map );
                ItemFifo_list item = map_fifo.get(Key_map);

                for(String key : map_fifo.keySet()) {
                    ItemFifo_list item2 = map_fifo.get(key);
                    keyitem = key;
                    if(Key_map.trim().equals(keyitem)){//เช็คคีย์
                        Double sum_pal_check = d_plan_qty - sum_total;
                        Log.d(getString(R.string.tag), "if Key_map --------------");
                        if(sum_pal_check < qty_label){ //เช็คจำนวนจาก label มากกว่า plan หรือป่าว

                            Double labrl_qty = Double.parseDouble(item.getQty());
                            Log.d(getString(R.string.tag), "labrl_qty " + labrl_qty);

                            Double sum_paln = (d_plan_qty - sum_total) - qty_label ; //(plan - qty_in_map) - qty_scan_label
                            Log.d(getString(R.string.tag), String.valueOf(sum_paln +"=("+d_plan_qty)+"-"+sum_total+")-"+qty_label);

                            det = qty_label - Math.abs(sum_paln) ;
                            Log.d(getString(R.string.tag), det+"="+  qty_label+"-"+ Math.abs(sum_paln));

                            Double total = det + labrl_qty ;
                            Log.d(getString(R.string.tag), "total " + total +" = "+ det +" + "+ labrl_qty);

                            Log.d(getString(R.string.tag), "d_plan_qty = " + d_plan_qty +" / "+ det +" = "+ det);

                            new_qty = Math.abs(sum_paln);

                            if(total > d_plan_qty){
                                item.setQty(d_plan_qty.toString());
                            }else{
                                item.setQty(total.toString());
                            }
                            Update_maplabel(label_id ,det.toString(), "1");

                        }else{
                            Double labrl_qty = Double.parseDouble(item.getQty());
                            Double sum = labrl_qty + qty_label;
                            item.setQty(sum.toString());
                            Update_maplabel(label_id ,qty_label.toString(),"0");
                        }

                        map_fifo.put(Key_map, item);
                    }
                }
            }else{


                Double sum = d_plan_qty - sum_total;
                Double  det_p = qty_label - sum;

                    if(qty_label > d_plan_qty){
                        sum = d_plan_qty - sum_total;
                        new_qty = Math.abs(det_p);
                        det = Math.abs(det_p);

                    }else{
                        sum = Double.parseDouble(qty);
                        det = Math.abs(qty_label);
                    }

                map_fifo.put(lacation.trim()+lot_no.trim(), new ItemFifo_list(
                        "1",
                        lot_no,
                        lacation,
                        sum.toString(),
                        "1",
                        d_plan_qty.toString(),
                        sum.toString()
                ));
            }
        View_data();
    }

    public void Update_maplabel(String id, String qty ,String status) {
        Log.d(getString(R.string.tag), "KEYMAP = " + id +" / qty = "+ qty +"status "+ status);
        String Key_map = id.trim();
        if (map_label.containsKey(Key_map)) {
            Log.d(getString(R.string.tag), "containsKey_Update_maplabel:  " + Key_map );
            LabelItem_out_sh_list item = map_label.get(Key_map);
            item.setIssue_stock_qty(qty);
            item.setStatus(status.trim());
            map_label.put(Key_map, item);
            label_id_old = Key_map;

        }
    }

    private void SendOutbound_Re() {
        Payload_list_out list = payload_list.get(0);
        String id_label = list.getId();
        Log.d(TAG, "SendOutbound_Re: id_label ="+ id_label);
        try {
            JSONObject json = new JSONObject();
            Map<String, String> jsonParams = new HashMap<>();//sample data
            json.put("cmd", "OUTBOUND/SCHEDULE/DETAIL/CONFIRM");
            JSONArray jsonArray = new JSONArray();
            for (String key : map_label_repck.keySet()){
                LabelItem_out_sh_list item = map_label_repck.get(key);
                String id_new = item.getLabel_id_new();

                if(id_new.equals(id_label)){
                    jsonParams.put("item_id", item.getPart_no().trim());
                    jsonParams.put("item_name", item.getPart_name().trim());
                    jsonParams.put("lot_no", item.getLot_no().trim());
                    if (str_mode.trim().equals(ActionType.Type.OUTBOUND_PRODUCTION.toString()) || str_mode.trim().equals(ActionType.Type.OUTBOUND_WORK.toString())
                            || item.getLabel_id_new().equals("")) {
                        jsonParams.put("ref_sch_id", str_sch_id);
                    }
                    jsonParams.put("package_id", item.getUnit().trim());
                    jsonParams.put("unit_qty",  item.getControl_unit().trim());
                    jsonParams.put("package_qty", item.getNg_qty());
                    jsonParams.put("qty", item.getNg_qty());
                    jsonParams.put("location_id", item.getLast_location_id().trim());
                    if(item.getLast_location_name().trim().equals("null")){
                        jsonParams.put("location_name", "");
                    }else{
                        jsonParams.put("location_name", item.getLast_location_name());
                    }
                    jsonParams.put("label_id", item.getLabel_id_new());
                    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", item.getLbl_ng());
                    jsonParams.put("supplier_id", item.getLbl_supplier_id());
                    jsonParams.put("supplier_name", item.getLbl_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){
                            //SUCCESS
//                            new SweetAlertDialog(Outbound_Activity.this, SweetAlertDialog.SUCCESS_TYPE)
//                                    .setTitleText("SUCCESS")
//                                    .setContentText("Insert data completed")
//                                    .show();
                            finish();

                        }else {
                            Unblock_button();
                            String error = jsonObject.getString("error");
                            new SweetAlertDialog(Outbound_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(error)
                                    .show();

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

    private void SendInbound_Re() {
        try {
            JSONObject json = new JSONObject();
            Map<String, String> jsonParams = new HashMap<>();//sample data
            json.put("cmd", "INBOUND/MANUAL/DETAIL/CONFIRM");
            JSONArray jsonArray = new JSONArray();
            for (String key : map_label_repck.keySet()){
                LabelItem_out_sh_list item = map_label_repck.get(key);
                jsonParams.put("item_id", item.getPart_no().trim());
                jsonParams.put("item_name", item.getPart_name().trim());
                jsonParams.put("lot_no", item.getLot_no().trim());
                jsonParams.put("package_id",  item.getUnit().trim());
                jsonParams.put("unit_qty",  item.getControl_unit().trim());
                jsonParams.put("package_qty",item.getNg_qty());
                jsonParams.put("qty", item.getNg_qty());
                jsonParams.put("location_id", item.getLast_location_id());
                jsonParams.put("location_name", item.getLast_location_name().trim().equals("null") ? "" : item.getLast_location_name());
                jsonParams.put("label_id", item.getLabel_id_new());
                jsonParams.put("inspection_flg", "0");
                jsonParams.put("status", "1"); //  IN_STORE = 2
                jsonParams.put("slip_divide", "3");
                jsonParams.put("create_user_id", Settings.getLoginUser().getId());
                jsonParams.put("ng", item.getLbl_ng());
                jsonParams.put("supplier_name", item.getLbl_supplier().trim().equals("null") ? "" :  item.getLbl_supplier());
                jsonParams.put("supplier_id", item.getLbl_supplier().trim().equals("null")  ? "" : item.getLbl_supplier_id());

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

                        }else {
                            Unblock_button();
                            String error = jsonObject.getString("error");
                            new SweetAlertDialog(Outbound_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(error)
                                    .show();

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

    private void AlertConfirmPrint_Newlabel() {
        new SweetAlertDialog(Outbound_Activity.this, SweetAlertDialog.SUCCESS_TYPE)
                .setTitleText("SUCCESS")
                .setContentText("Do you want to print the new "+ Math.abs(amon_new_lablr_print) + " "+ label_id_new_unit +" label?")
                .setCancelText("No")
                .showCancelButton(true)
                .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sDialog) {
                        payload_list_2.clear();

                        status_print = "0";
                            Payload_list_out list = payload_list.get(0);
                            String Key_map = label_id.trim();
                            String label_id_new = list.getId().trim();
                            Log.d(getString(R.string.tag), "Key_map: " + Key_map + "label_id " + label_id_new);
                                payload_list_2.add(new Payload_list_out(
                                        list.getId(),
                                        list.getScrap_flg(),
                                        list.getPayload(),
                                        list.getQty(),
                                        list.getStatus()
                                ));
                        LABEL_QTY = payload_list_2.size();
                        if (Settings.getMgmtList().get("skip_print").trim().equals("1")){
                            AlertConfirmPrint();

                        }else {
                            Command_Print();
                        }
                        sDialog.cancel();
                    }
                })
                .setConfirmText("Yes")
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sDialog) {
                        status_print = "1";
                        if (Settings.getMgmtList().get("skip_print").trim().equals("1")){
                            AlertConfirmPrint();

                        }else {
                            Command_Print();
                        }
                        sDialog.cancel();
                    }
                })
                .show();


    }

    public void Check_In_out(){

        if (Settings.getPrinter().trim().equals("")||Settings.getPrinter().trim().equals("null")){
            new SweetAlertDialog(Outbound_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("WARNING")
                    .setContentText("Please setting printer")
                    .show();
        }else {
            if(new_qty > 0){
                AlertConfirmPrint_Newlabel();

            }else{
                SendOutbound_m();
            }
        }
    }

    private void SendOutbound_m() {// ไม่เชื่อม inbound
        Log.d(getString(R.string.tag),"SendOutbound "+ str_mode);
        try {
            JSONObject json = new JSONObject();
            Map<String, String> jsonParams = new HashMap<>();//sample data
            json.put("cmd", "OUTBOUND/SCHEDULE/DETAIL/CONFIRM");
            JSONArray jsonArray = new JSONArray();
            for (String key : map_label.keySet()){
                LabelItem_out_sh_list item = map_label.get(key);
                jsonParams.put("item_id", item.getPart_no().trim());
                jsonParams.put("item_name", item.getPart_name().trim());
                jsonParams.put("lot_no", item.getLot_no().trim());
                if (str_mode.trim().equals(ActionType.Type.OUTBOUND_WORK.toString()) || str_mode.trim().equals(ActionType.Type.OUTBOUND_PRODUCTION.toString())
                        && item.getLabel_id_new().trim().equals("")) {
                    jsonParams.put("ref_sch_id", str_sch_id);
                }
                jsonParams.put("package_id", item.getUnit().trim());
                jsonParams.put("unit_qty",  item.getControl_unit().trim());
                jsonParams.put("package_qty", item.getIssue_qty());
                jsonParams.put("qty", item.getIssue_qty());
                jsonParams.put("location_id", item.getLast_location_id().trim());
                if(item.getLast_location_name().trim().equals("null")){
                    jsonParams.put("location_name", "");
                }else{
                    jsonParams.put("location_name", item.getLast_location_name());
                }
                if(item.getLabel_id_new().trim().equals("")){
                    jsonParams.put("label_id", item.getLabel_id());
                }else{
                    jsonParams.put("label_id", item.getLabel_id_new());
                }
                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", item.getLbl_ng());
                jsonParams.put("supplier_id", item.getLbl_supplier_id());
                jsonParams.put("supplier_name", item.getLbl_supplier());
                jsonParams.put("factory_code", item.getLast_location_id());

                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) {
                    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) {
                            Toast.makeText(Outbound_Activity.this,"Outbound complete",Toast.LENGTH_SHORT).show();
                            showSuccess("Outbound completed", new DialogInterface.OnDismissListener() {
                                @Override
                                public void onDismiss(DialogInterface dialogInterface) {
                                    finish();
                                }
                            });

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

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

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

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