package com.tomas.ht_ydt;

import android.annotation.SuppressLint;
import android.app.DatePickerDialog;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.keyence.autoid.sdk.scan.DecodeResult;
import com.tomas.ht_ydt.Adapter.Rework_Adapter;
import com.tomas.ht_ydt.ListData.LabelItem_list;
import com.tomas.ht_ydt.ListData.Rework_List;
import com.tomas.ht_ydt.lib.ActionType;
import com.tomas.ht_ydt.lib.AlertProgress;
import com.tomas.ht_ydt.lib.KeyMapping;
import com.tomas.ht_ydt.lib.Scanner;
import com.tomas.ht_ydt.lib.Settings;
import com.tomas.ht_ydt.lib.common.AsyncHttpClient;
import com.tomas.ht_ydt.lib.common.AsyncTcpClient;
import com.tomas.ht_ydt.lib.common.Utils;

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

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import cn.pedant.SweetAlert.SweetAlertDialog;

public class InboundRework_Activity extends Scanner implements View.OnClickListener, ClickItem_Rework {

    TextView txt_user, txt_device, txt_part_no, txt_header, txtc_part_no, txtc_unit, txt_qty, txt_label_qty;
    EditText edtc_qty, edtc_lot_no;
    Button btn_confirm, btn_clear;
    ImageButton imb_back;
    private JSONArray j_schedules;
    Spinner spinner_location;
    String str_menu, str_part_no, str_lot_no, str_today, update_id, l_part_no, l_lot_no, l_serial, l_label_id,
            key_label, bf_change_lot, bf_change_qty;
    RecyclerView view_data;
    LinearLayout layout_edit;
    Map<String, Rework_List> map_item_rework;
    Map<String, LabelItem_list> map_label_scan, map_label_prepare;
    List<Rework_List>rework_lists;
    Rework_Adapter reworkAdapter;
    boolean b_confirm, edit_qty;
    Calendar calendar;
    SimpleDateFormat date;
    AlertProgress alert;
    int total_qty = 0;

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

        alert = new AlertProgress(InboundRework_Activity.this);
        calendar = Calendar.getInstance();
        date = new SimpleDateFormat("yyyy-MM-dd");
        str_today = date.format(calendar.getTime());

        b_confirm = false;
        edit_qty = false;

        map_item_rework = new LinkedHashMap<>();
        map_label_scan = new LinkedHashMap<>();
        map_label_prepare = new LinkedHashMap<>();
        rework_lists = new ArrayList<Rework_List>();

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

        str_menu = Settings.getMENU().toString();
        txt_header = (TextView) findViewById(R.id.txt_header);
        spinner_location =(Spinner) findViewById(R.id.spinner_location);
        if (str_menu.trim().equals(ActionType.Menu.INBOUND_REWORK.toString())){
            txt_header.setText("Inbound Rework");
            ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>
                    (getApplicationContext(), R.layout.spinner_list, Settings.getList_location_ok());
            dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinner_location.setAdapter(dataAdapter);

        }else {
            txt_header.setText("Inbound Rework NG");
            ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>
                    (getApplicationContext(), R.layout.spinner_list, Settings.getList_location_ng());
            dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinner_location.setAdapter(dataAdapter);
        }
        txt_part_no = (TextView) findViewById(R.id.txt_part_no);
        txt_qty = (TextView)findViewById(R.id.txt_qty);
        txt_label_qty = (TextView)findViewById(R.id.txt_label_qty);

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

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

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

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

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

                final Calendar currentDate = Calendar.getInstance();
                new DatePickerDialog(InboundRework_Activity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        str_lot_no =( year+"-"+
                                (String.format("%2s",monthOfYear + 1).replace(' ','0'))+"-"+
                                (String.format("%2s",dayOfMonth).replace(' ','0')));
                        edtc_lot_no.setText(str_lot_no);
                    }
                }, currentDate.get(Calendar.YEAR), currentDate.get(Calendar.MONTH), currentDate.get(Calendar.DATE)).show();
            }
        });
    }

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

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

            case R.id.btn_confirm:
                if (map_label_scan.size() == 0) {
                    return;
                }else {
                    if (b_confirm == false) {
                        Block_button();
                        Prepare_Label();
                    }
                }

                break;

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

            case R.id.btn_cancel:
                layout_edit.setVisibility(View.GONE);
                Clear_layout_edit();
                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_layout() {
        edit_qty = false;
        b_confirm = false;
        map_label_scan.clear();
        map_label_prepare.clear();
        rework_lists.clear();
        map_item_rework.clear();
        txt_part_no.setText("");
        txt_qty.setText("");
        txt_label_qty.setText("");
        spinner_location.setSelection(0);
        Clear_layout_edit();
        view_data();
    }

    @Override
    public void processData(String data, DecodeResult.Result result, String codeType) {
        if (data.trim().equals(""))
            return;
        try {
            Log.d(getString(R.string.tag), "data read:" + data);
            String[] tokens = data.split(getString(R.string.DELIMITER_SCAN_TOKEN),-1);
            Log.d(getString(R.string.tag), Arrays.deepToString(tokens));
            if (tokens.length == 2){
                if (txt_part_no.getText().toString().trim().equals("")){
                    showWarning("Please scan label!");
                    return;
                }
                String location = tokens[0].trim();
                String list_item = tokens[1].trim();
                String[] tokens_part = list_item.split(",",-1);

                if (Settings.getMap_location().containsKey(location)) {//check has location
//                    if (list_item.trim().equals("")){//free location
                        if (str_menu.trim().equals(ActionType.Menu.INBOUND_REWORK.toString())){
                            spinner_location.setSelection(Settings.getList_location_ok().indexOf(location));
                        }else {
                            spinner_location.setSelection(Settings.getList_location_ng().indexOf(location));
                        }

//                    }else {
//                        Boolean search = false;
//                        for (int i = 0; i < tokens_part.length; i++) { //for check part can use
//                            if (str_part_no.trim().equals(tokens_part[i])) {
//                                search = true;
//                                if (str_menu.trim().equals(ActionType.Menu.INBOUND_REWORK.toString())){
//                                    spinner_location.setSelection(Settings.getList_location_ok().indexOf(location));
//                                }else {
//                                    spinner_location.setSelection(Settings.getList_location_ng().indexOf(location));
//                                }
//                                break;
//                            } else {
//                                search = false;
//                            }
//                        }//for
//
//                        if (search == false) {
//                            showWarning("Location not match!");
//                            return;
//                        }
//                    }
                }else {
                    showWarning("Location not found!");
                }

            }else if (tokens.length == 4){
                key_label = data.trim();
                l_part_no = tokens[0].trim();
                l_lot_no = tokens[1].trim();
                l_serial = tokens[2].trim();
                l_label_id = tokens[3].trim();

                if (map_label_scan.size() > 0) {
                    str_part_no = txt_part_no.getText().toString().trim();
                    if (str_part_no.trim().equals(l_part_no)) {
                        if (map_label_scan.containsKey(key_label)) {
                            SweetAlertDialog d = new SweetAlertDialog(InboundRework_Activity.this, SweetAlertDialog.WARNING_TYPE);
                            d.setCancelable(false);
                            d.setTitleText("WARNING");
                            d.setContentText("This label has been scanned.");
                            d.setCancelText("Delete");
                            d.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sd) {
                                    sd.dismiss();
                                    map_label_scan.remove(key_label);
                                    Log.d(getString(R.string.tag), "delete size = " + map_label_scan.size());
                                    if (map_label_scan.size()>0) {
                                        Calculate_BOM();
                                    }else {
                                        Clear_layout();
                                    }
                                }
                            });
                            d.setConfirmText("Continue");
                            d.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sd) {
                                    sd.dismiss();
                                }
                            });
                            d.show();

                        } else {
                            if (edit_qty == true){
                                showConfirmationDialog();
                            }else {
                                Check_Label();
                            }
                        }
                    }else {
                        showWarning("Parts not match!");
                    }
                }else {
                    Check_Label();
                }

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

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

    private void showConfirmationDialog() {
        SweetAlertDialog d = new SweetAlertDialog(InboundRework_Activity.this, SweetAlertDialog.WARNING_TYPE);
        d.setCancelable(false);
        d.setTitleText("QTY changed detect");
        d.setContentText("Click “YES” to clear all data?");
        d.setCancelText("No");
        d.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
            @Override
            public void onClick(SweetAlertDialog sDialog) {
                sDialog.dismiss();

            }
        });
        d.setConfirmText("Yes");
        d.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
            @Override
            public void onClick(SweetAlertDialog sDialog) {
                sDialog.dismiss();
                edit_qty = false;
                map_item_rework.clear();
                map_label_scan.clear();
                map_label_prepare.clear();
                Check_Label();
            }
        });
        d.show();
    }

    private void Check_Label() {
        Log.d(getString(R.string.tag), "Check_Label : " + key_label+": "+l_label_id+" "+l_part_no+" "+l_lot_no+" "+l_serial);
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "LABEL/DETAIL");
            json.put("id", l_label_id);
            json.put("parts_no", l_part_no);
            json.put("lot_no", l_lot_no);
            json.put("serial_no", l_serial);

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

                    try{
                        JSONObject jsonObject = new JSONObject(response);
                        String value = jsonObject.getString("value");
                        JSONArray jArray = new JSONArray(value);
                        if (jArray.length() == 0){
                            showWarning("Label not found!");

                        }else {
                            String status_label = jArray.getJSONObject(0).getString("status").trim();
                            Log.d(getString(R.string.tag), "status_label: " + status_label);
                            if (status_label.trim().equals("2") || status_label.trim().equals("3")) {
                                str_part_no =  jArray.getJSONObject(0).getString("lbl_part_no").trim();
                                map_label_scan.put(key_label, new LabelItem_list(
                                        "",
                                        jArray.getJSONObject(0).getString("id").trim(),
                                        jArray.getJSONObject(0).getString("lot_no").trim(),
                                        jArray.getJSONObject(0).getString("serial_no").trim(),
                                        jArray.getJSONObject(0).getString("status").trim(),
                                        String.valueOf(Math.round(Double.parseDouble(jArray.getJSONObject(0).getString("issue_qty").trim()))),
                                        jArray.getJSONObject(0).getString("issue_stock_qty").trim(),
                                        jArray.getJSONObject(0).getString("act_stock_qty").trim(),
                                        jArray.getJSONObject(0).getString("control_unit").trim(),
                                        jArray.getJSONObject(0).getString("lbl_supplier_id").trim(),
                                        jArray.getJSONObject(0).getString("lbl_supplier").trim(),
                                        str_part_no,
                                        jArray.getJSONObject(0).getString("lbl_part_name").trim(),
                                        jArray.getJSONObject(0).getString("lbl_unit").trim(),
                                        jArray.getJSONObject(0).getString("lbl_ng").trim(),
                                        jArray.getJSONObject(0).getString("last_location_id").trim().equals("null") ? "" : jArray.getJSONObject(0).getString("last_location_id").trim(),
                                        jArray.getJSONObject(0).getString("last_location_name").trim().equals("null") ? "" : jArray.getJSONObject(0).getString("last_location_name").trim(),
                                        "",
                                        "",
                                        jArray.getJSONObject(0).getString("lbl_order_no").trim()));

//                                if (map_label.size() == 1){
//                                    Get_BOM();
//                                }else {
                                    Calculate_BOM();
//                                }

                            }else {
                                showWarning("Invalid Label Status! : "+status_label);
                            }
                        }
                    }catch (JSONException e) {
                        showError(e.getMessage());

                    }
                }
            }.execute();

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

    private void Calculate_BOM() {
        total_qty = 0;
        Double sum = 0.0;
        for (String K : map_label_scan.keySet()){
            LabelItem_list list = map_label_scan.get(K);
            String act_qty = list.getAct_stock_qty();
            Double d_act_qty = Double.parseDouble(act_qty);
            sum = (sum + d_act_qty);

        }

        total_qty = (int) Math.round(sum);
        txt_qty.setText(String.valueOf(total_qty));
        txt_part_no.setText(str_part_no);
        txt_label_qty.setText(String.valueOf(map_label_scan.size()));

        if (map_label_scan.size() > 0) {
            Get_BOM();

        }else {
            Clear_layout();
        }

    }


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

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

                    try{
                        JSONObject jsonObject = new JSONObject(response);
                        String value = jsonObject.getString("value");
                        JSONArray jArray = new JSONArray(value);
                        if (jArray.length() == 0){
                            txt_part_no.setText("");
                            map_label_scan.remove(key_label);
                            showWarning("BOM not found!");

                        }else {
                            for(int i = 0; i < jArray.length(); i++) {
                                Double sum_qty = 0.0;
                                if (str_menu.trim().equals(ActionType.Menu.INBOUND_REWORK.toString())) {
                                    Double qty_FG = Double.parseDouble(txt_qty.getText().toString().trim());
                                    String qty_ratio = jArray.getJSONObject(i).getString("qty_ratio").trim();
                                    String[] tokens = qty_ratio.split(":", -1);
                                    Double qty_item = Double.parseDouble(tokens[0]);
                                    sum_qty = (qty_item * qty_FG);
                                    Log.d(getString(R.string.tag), "getQty: " + qty_item);
                                    Log.d(getString(R.string.tag), "sum_qty: " + sum_qty);
                                }else {
                                    sum_qty = 0.0;
                                }

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

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

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

        if (map_label_scan.size()>0) {
            //calculate map_label_scan again
            total_qty = 0;
            Double sum = 0.0;
            for (String K : map_label_scan.keySet()) {
                LabelItem_list list = map_label_scan.get(K);
                String act_qty = list.getAct_stock_qty();
                Double d_act_qty = Double.parseDouble(act_qty);
                sum = (sum + d_act_qty);

            }

            total_qty = (int) Math.round(sum);
            txt_qty.setText(String.valueOf(total_qty));
            txt_part_no.setText(str_part_no);
            txt_label_qty.setText(String.valueOf(map_label_scan.size()));
        }
    }

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

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


        if (!lot_update.trim().equals(bf_change_lot) || bf_qty > d_qty_update || bf_qty < d_qty_update) {
            edit_qty = true;
            Rework_List item = map_item_rework.get(update_id);
            item.setQty(qty_update);
            item.setLot_no(lot_update);
            map_item_rework.put(update_id,item);
        }
        view_data();
        Clear_layout_edit();
    }

    private void Clear_layout_edit() {
        update_id = "";
        txtc_part_no.setText("");
        edtc_qty.setText("");
        txtc_unit.setText("");
        edtc_lot_no.setText("");
        bf_change_lot = "";
        bf_change_qty = "";
    }
    private void Prepare_Label() {
        try {
            JSONObject json = new JSONObject();
            Map<String, String> jsonParams = new HashMap<>();
            if (str_menu.trim().equals(ActionType.Menu.INBOUND_REWORK.toString())){
                json.put("cmd", "LABEL/REWORK/CONFIRM/PREPARE");

            }else{//INBOUND_REWORK NG
                json.put("cmd", "LABEL/REWORK_NG/CONFIRM/PREPARE");
            }
            JSONArray jsonArray = new JSONArray();
            for (String key : map_item_rework.keySet()) {
                Rework_List item = map_item_rework.get(key);
                Double qty = Double.parseDouble(item.getQty());
                if (qty > 0) {
                    jsonParams.put("parts_no", item.getPart_no());
                    jsonParams.put("lot_no", item.getLot_no());

                    if (str_menu.trim().equals(ActionType.Menu.INBOUND_REWORK.toString())) {
                        jsonParams.put("ok_act_qty", item.getQty());
                        jsonParams.put("ok_qty_per_box", item.getQty());
                    } else {
                        jsonParams.put("ng_act_qty", item.getQty());
                        jsonParams.put("ng_qty_per_box", item.getQty());
                    }
                    jsonParams.put("user_id", Settings.getLoginUser().getId());

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

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

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

                    try{
                        JSONObject jsonObject = new JSONObject(response);
                        String status = jsonObject.getString("status");
                        if (status.trim().equals("error")){
                            String error = jsonObject.getString("error");
                            showError(error);
                            Unblock_button();
                        }else {
                            String value = jsonObject.getString("value");
                            j_schedules = new JSONArray(value);

                            if (str_menu.trim().equals(ActionType.Menu.INBOUND_REWORK_NG.toString())){
                                Confirm_Request_Print();

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

                                } else {
                                    if (Settings.getPrinter().trim().equals("")
                                            || Settings.getPrinter().trim().equals(null)
                                            || Settings.getPrinter().trim().equals("null")) {
                                        Unblock_button();
                                        showWarning("Please setting printer");

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

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

    private void Confirm_Request_Print() {
        try {
            SweetAlertDialog d = new SweetAlertDialog(InboundRework_Activity.this, SweetAlertDialog.WARNING_TYPE);
            d.setCancelable(false);
            d.setTitleText("WARNING");
            d.setContentText("Do you want to print label?");
            d.setCancelText("No");
            d.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                @Override
                public void onClick(SweetAlertDialog sDialog) {
                    sDialog.dismiss();
                    Confirm_Label();
                }
            });
            d.setConfirmText("Yes");
            d.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                @Override
                public void onClick(SweetAlertDialog sDialog) {
                    sDialog.dismiss();
                    if (Settings.getMgmtList().get("skip_print").trim().equals("1")) {
                        AlertConfirmPrint();

                    } else {
                        if (Settings.getPrinter().trim().equals("")
                                || Settings.getPrinter().trim().equals(null)
                                || Settings.getPrinter().trim().equals("null")) {
                            Unblock_button();
                            showWarning("Please setting printer");

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

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

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

        String tmp_label = "";
        try {
            for (int i = 0; i < j_schedules.length(); i++) {
                String payload = j_schedules.getJSONObject(i).getString("payload");
                String content_label = j_schedules.getJSONObject(i).getString("content_label");
                String tmp = String.format(
                        "%s %s-%s%s\n%s"
                        , "PST"
                        , Settings.getPrinter()
                        , content_label
                        , ""
                        , payload+"\n");

                tmp_label = (tmp_label + tmp);

                Log.e(getString(R.string.tag), "payload tmp: " + tmp);
            }
            Log.e(getString(R.string.tag), "payload tmp_label: " + tmp_label);

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

                new AsyncTcpClient(getApplicationContext(),
                        Settings.getMgmtList().get("lpc_host"),
                        Integer.parseInt(Settings.getMgmtList().get("lpc_port")),
                        tmp_label+"\n\n\n"
                ) {
                    @Override
                    protected void onFinished(String response) {
                        Log.d(getString(R.string.tag), "TCP response: " + response);

                        if (response.equals("OK")) {
                            alert.dismiss();
                            AlertConfirmPrint();

                        } else {
                            alert.dismiss();
                            Unblock_button();
                            showError("Can't connect to print server");

                        }
                    }
                }.execute();
                throw new JSONException(err_msg);

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

    private void AlertConfirmPrint() {
        try {
            SweetAlertDialog d = new SweetAlertDialog(InboundRework_Activity.this, SweetAlertDialog.WARNING_TYPE);
            d.setCancelable(false);
            d.setTitleText("WARNING");
            d.setContentText("Click 'No' if nothing printed out?");
            d.setCancelText("No");
            d.setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sDialog) {
                            sDialog.dismiss();
                            Unblock_button();
                        }
                    });
            d.setConfirmText("Yes");
            d.setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sDialog) {
                            sDialog.dismiss();
                            Confirm_Label();
                        }
                    });
            d.show();
        }catch (WindowManager.BadTokenException e) {
            Unblock_button();
            showWarning("Please check the label status on Pegasus!");

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

    private void Confirm_Label() {
        try {
            JSONObject json = new JSONObject();
            if (str_menu.trim().equals(ActionType.Menu.INBOUND_REWORK.toString())){
                json.put("cmd", "LABEL/REWORK/CONFIRM/CONFIRM");

            }else{////INBOUND_REWORK NG
                json.put("cmd", "LABEL/REWORK_NG/CONFIRM/CONFIRM");
            }
            JSONArray jArray = new JSONArray();
            for (int i = 0; i < j_schedules.length(); i++) {
                String label_id = j_schedules.getJSONObject(i).getString("id").trim();
                Map<String, String> jsParams = new HashMap<>();
                jsParams.put("label_id", label_id);
                JSONObject jsonObject = new JSONObject(jsParams);
                jArray.put(jsonObject);
            }
            json.put("value",jArray);

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

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

                        if (status.trim().equals("success") && affected_rows > 0){
                            Label_Detail();
                        }else {
                            String error = jsonObject.getString("error");
                            showError(error);
                            Unblock_button();
                        }
                    }catch (JSONException e) {
                        showError(e.getMessage());
                        Unblock_button();
                    }
                }
            }.execute();

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

    private void Label_Detail() {
        map_label_prepare.clear();
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "LABEL/REWORK/DETAIL");
            JSONArray jArray = new JSONArray();
            for (int i = 0; i < j_schedules.length(); i++) {
                String label_id = j_schedules.getJSONObject(i).getString("id").trim();
                Map<String, String> jsParams = new HashMap<>();
                jsParams.put("id", label_id);
                JSONObject jsonObject = new JSONObject(jsParams);
                jArray.put(jsonObject);
            }
            json.put("value",jArray);

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

                    try{
                        JSONObject jsonObject = new JSONObject(response);
                        String value = jsonObject.getString("value");
                        JSONArray jArray = new JSONArray(value);
                        Log.d(getString(R.string.tag), "jArray: " + jArray.toString());
                        if (jArray.length() == 0){
                            showError("LABEL/REWORK/DETAIL not found!");

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

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

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

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

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

    private void Confirm_Inbound() {
        try {
            JSONObject json = new JSONObject();
            Map<String, String> jsonParams = new HashMap<>();//sample data
            if (str_menu.trim().equals(ActionType.Menu.INBOUND_REWORK.toString())){
                json.put("cmd", "INBOUND/REWORK/DETAIL/CONFIRM");
            }else {
                json.put("cmd", "INBOUND/REWORK_NG/DETAIL/CONFIRM");
            }

            JSONArray jsonArray = new JSONArray();
            for (String key : map_label_prepare.keySet()){
                LabelItem_list item = map_label_prepare.get(key);
                jsonParams.put("item_id", item.getLbl_part_no());
                jsonParams.put("item_name", item.getLbl_part_name());
                jsonParams.put("supplier_id", item.getLbl_supplier_id().trim().equals("null") ? "" : item.getLbl_supplier_id().trim());
                jsonParams.put("supplier_name", item.getLbl_supplier().trim().equals("null") ? "" : item.getLbl_supplier().trim());
                jsonParams.put("package_id", item.getLbl_unit());
                jsonParams.put("package_qty",item.getIssue_qty());
                jsonParams.put("lot_no", item.getLot_no().trim());
                //order_no
                jsonParams.put("qty",item.getIssue_stock_qty());
                jsonParams.put("unit_qty", item.getControl_unit());
                jsonParams.put("location_id", spinner_location.getSelectedItem().toString().trim());
                jsonParams.put("location_name", Settings.getMap_location().get(spinner_location.getSelectedItem().toString().trim()).getName() );
                jsonParams.put("ref_sch_id", "0");
                jsonParams.put("label_id", item.getLabel_id());
                jsonParams.put("status",  "1");
                jsonParams.put("slip_divide", "3");
                jsonParams.put("create_user_id", Settings.getLoginUser().getId());
                jsonParams.put("inspection_flg", "0");
                jsonParams.put("ng", item.getLbl_ng());

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

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

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

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

    private void Outbound_Label() {
        Log.d(getString(R.string.tag),"Outbound_Label");
        try {
            JSONObject json = new JSONObject();
            Map<String, String> jsonParams = new HashMap<>();
            json.put("cmd", "OUTBOUND/MANUAL/DETAIL/CONFIRM");
            JSONArray jsonArray = new JSONArray();

            for (String key : map_label_scan.keySet()) {
                LabelItem_list item = map_label_scan.get(key);
                String status = item.getStatus();
                Log.d(getString(R.string.tag),"status"+ status);
                if (status.trim().equals("2")) {
                    jsonParams.put("ref_sch_id", "0");
                    jsonParams.put("order_no", "");
                    jsonParams.put("label_id", item.getLabel_id());
                    jsonParams.put("item_id", item.getLbl_part_no());
                    jsonParams.put("item_name", item.getLbl_part_name());
                    jsonParams.put("lot_no", item.getLot_no());
                    jsonParams.put("package_id", item.getLbl_unit());
                    jsonParams.put("unit_qty", item.getControl_unit());
                    jsonParams.put("package_qty", item.getAct_stock_qty());
                    jsonParams.put("qty", item.getAct_stock_qty());
                    jsonParams.put("location_id", item.getLast_location_id());
                    jsonParams.put("location_name", item.getLast_location_name().trim().equals("null") ? "" : item.getLast_location_name());
                    jsonParams.put("ng", item.getLbl_ng());
                    jsonParams.put("supplier_id", item.getLbl_supplier_id().trim().equals("null") ? "" : item.getLbl_supplier_id().trim());
                    jsonParams.put("supplier_name", item.getLbl_supplier().trim().equals("null") ? "" : item.getLbl_supplier().trim());
                    jsonParams.put("inspection_flg", "0");
                    jsonParams.put("status", "2"); // OUT_STORE = 3;
                    jsonParams.put("slip_divide", "4");
                    jsonParams.put("create_user_id", Settings.getLoginUser().getId());

                    JSONObject jsonObject = new JSONObject(jsonParams);
                    jsonArray.put(jsonObject);
                }
            }
            Log.d(getString(R.string.tag),"jsonArray"+ jsonArray.length());

            json.put("value", jsonArray);
            if (jsonArray.length() == 0) {
                new SweetAlertDialog(InboundRework_Activity.this, SweetAlertDialog.SUCCESS_TYPE)
                        .setTitleText("INFORMATION")
                        .setContentText("Operation Completed")
                        .show();
                Unblock_button();
                Clear_layout();

            } else {

                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);
                                new SweetAlertDialog(InboundRework_Activity.this, SweetAlertDialog.SUCCESS_TYPE)
                                        .setTitleText("INFORMATION")
                                        .setContentText("Operation Completed")
                                        .show();
                                Unblock_button();
                                Clear_layout();

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

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

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

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

                case P3:
                    btn_clear.performClick();
                    break;

                case P4:
                    btn_confirm.performClick();
                    break;
            }
        }

        return super.onKeyUp(keyCode, event);
    }

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