package com.tomas.ht_mast;

import static android.content.ContentValues.TAG;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
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.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_Adapter_out_man;
import com.tomas.ht_mast.ListData.LabelItem_list_out_man;
import com.tomas.ht_mast.ListData.LabelItem_out_sh_list;
import com.tomas.ht_mast.ListData.LabelItem_qc_list;
import com.tomas.ht_mast.ListData.Payload_list_out;
import com.tomas.ht_mast.ListData.Payload_list;
import com.tomas.ht_mast.lib.ActionType;
import com.tomas.ht_mast.lib.AlertProgress;
import com.tomas.ht_mast.lib.KeyMapping;
import com.tomas.ht_mast.lib.Scanner;
import com.tomas.ht_mast.lib.Settings;
import com.tomas.ht_mast.lib.common.AsyncHttpClient;
import com.tomas.ht_mast.lib.common.AsyncTcpClient;
import com.tomas.ht_mast.lib.common.Utils;

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

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

import cn.pedant.SweetAlert.SweetAlertDialog;

public class OutboundManual_Activity extends Scanner implements View.OnClickListener {
    TextView txt_user, txt_device, txt_date, txt_part_no, txt_part_name, txt_total, txt_location;
    Button btn_clear, btn_confirm;
    RecyclerView view_data;
    Bundle bundle;
    Calendar calendar;
    SimpleDateFormat date;
    boolean b_confirm;
    String str_mode, str_sch_id, str_order, str_lot_no, str_part_no, str_part_name, str_rank, str_location, str_plan_qty, str_act_qty,
            str_inspection_flg, str_location_name, str_today, t_order, t_part, t_dwg, t_lot_no, t_qty, t_rank, t_box, l_location,
            l_part_no, str_supplier_id, str_supplier_name ,label_id, label_id_new_re,label_id_old,keyitem ,status_print;
    Map<String, LabelItem_list_out_man>map_label;
    List<LabelItem_list_out_man>list_label;
    Double sum_total, f_plan_qty, f_act_qty;
    ItemLabel_Adapter_out_man label_adapter;
    DecimalFormat decimalFormat, format_comma;
    Double d_act_qty ,d_plan_qty, d_total_net,sum_qty , d_issue_qty, qty_new = 0.0 ;
    EditText  edit_tatal;
    List<Payload_list_out> payload_list;
    Integer LABEL_QTY, PRINT_TIMES;
    AlertProgress alert;
    List<Payload_list_out> payload_list_2;
    Map<String, LabelItem_list_out_man>  map_label_repck;
    SimpleDateFormat  date_time_fm;
    private volatile boolean stopThread = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_outbound_manual);
        default_view = (EditText) findViewById(R.id.txt_label_issue_tmp);
        d_plan_qty = 0.0;
        decimalFormat = new DecimalFormat("#,#00");
        format_comma = new DecimalFormat("#,##0");
        calendar = Calendar.getInstance();
        date = new SimpleDateFormat("dd/MM/yyyy");
        str_today = date.format(calendar.getTime());

        map_label = new LinkedHashMap<>();
        list_label = new ArrayList<LabelItem_list_out_man>();

        sum_total = Double.valueOf(0);
        b_confirm = false;
        map_label_repck = new LinkedHashMap<>();
        txt_user = (TextView) findViewById(R.id.txt_user);
        txt_user.setText("User : "+ Settings.getLoginUser().getName());
        txt_device = (TextView) findViewById(R.id.txt_device);
        txt_device.setText("Device : "+Settings.getDeviceNo());
        txt_date = (TextView) findViewById(R.id.txt_date);
        txt_date.setText(str_today);
        payload_list_2 = new ArrayList<Payload_list_out>();
        txt_part_no = (TextView) findViewById(R.id.txt_part_no);
        txt_part_name = (TextView) findViewById(R.id.txt_part_name);
        txt_total = (TextView) findViewById(R.id.txt_total);
        payload_list = new ArrayList<Payload_list_out>();

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

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

        txt_total.setText(format_comma.format(Math.round(0)) +"/"+format_comma.format(Math.round(0)));
        bundle = getIntent().getExtras();
        str_mode = Settings.getActionType().toString();
        Log.d(getString(R.string.tag), "str_mode:" + str_mode);
        alert = new AlertProgress(OutboundManual_Activity.this);
        payload_list = new ArrayList<Payload_list_out>();
        date_time_fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");


        edit_tatal.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

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

                }
                txt_total.setText(Math.round(sum_total)+"/"+Math.round(d_plan_qty));
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });

    }

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

            case R.id.btn_clear:
                b_confirm = false;
                map_label.clear();
                View_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 Check_condition() {

        if (str_mode.trim().equals(ActionType.Type.INBOUND_SCHEDULE.toString())) {
            if (sum_total < f_plan_qty) {
                new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("WARNING")
                        .setContentText("Quantity is small. Proceed with the process?")
                        .setCancelText("No")
                        .showCancelButton(true)
                        .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sDialog) {
                                Unblock_button();
                                sDialog.cancel();
                            }
                        })
                        .setConfirmText("Yes")
                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sDialog) {
                                sDialog.cancel();
                                //sent to save....
                                Confirm_Outbound();
                            }
                        })
                        .show();
            }
        } else {//MANUAL

            Confirm_Outbound();
        }

    }

    @Override
    public void processData(String data, DecodeResult.Result result, String codeType) {
        if (data.trim().equals(""))
            return;
        if (sum_total >= d_plan_qty){

        }else{

            if (Utils.CompareDouble(d_plan_qty , 0.0)) {
                new SweetAlertDialog(OutboundManual_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("WARNING")
                        .setContentText("Please enter quantity")
                        .show();
            }else {
                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 == 7) {//scan label
                        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);

                        Check_previous_label();

                    } else {
                        new SweetAlertDialog(OutboundManual_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("WARNING")
                                .setContentText("Invalid QR code!")
                                .show();
                    }
                    Utils.hideKeyboardFrom(getApplicationContext(), default_view);

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


    private void Check_previous_label() {
        //Outbound manual
        if (map_label.size() > 0) {
            Log.e(getString(R.string.tag), "First label: " + str_part_no+"|"+str_part_name+"|"+str_lot_no);
            if (str_part_no.trim().equals(t_part)){//check part
                if (str_lot_no.trim().equals(t_lot_no)){ //check lot
                    if (map_label.containsKey(t_box)) {//delete label

                        new SweetAlertDialog(OutboundManual_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) {
                                        map_label.remove(t_box);
                                        Log.d(getString(R.string.tag), "map_label size = " + map_label.size());
                                        View_data();
                                    }
                                })
                                .setConfirmText("Continue")
                                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                    @Override
                                    public void onClick(SweetAlertDialog sDialog) {
                                        sDialog.cancel();
                                    }
                                })
                                .show();
                    } else {
                        Label_Inquiry(t_order, t_part, t_lot_no, t_box);
                    }
                }else {
                    new SweetAlertDialog(OutboundManual_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("WARNING")
                            .setContentText("Lot number is different")
                            .show();
                }
            }else {
                new SweetAlertDialog(OutboundManual_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("WARNING")
                        .setContentText("Part No. is different")
                        .show();
            }
        }else{//first label
            Label_Inquiry(t_order, t_part, t_lot_no, t_box);
        }
    }

    private void Label_Inquiry(String order_no, String parts_no, String lot_no, String box) {
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "LABEL/DETAIL");
            json.put("order_no", order_no);
            json.put("parts_no", parts_no);
            json.put("lot_no", lot_no);
            json.put("serial_no", box);

            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){
                            new SweetAlertDialog(OutboundManual_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("WARNING")
                                    .setContentText("Label not found!")
                                    .show();
                        }else {
                            String status_label = jArray.getJSONObject(0).getString("status").trim();
                            String label_id_chek = jArray.getJSONObject(0).getString("id");
                            if (status_label.trim().equals("2")) {
                                map_label.put(jArray.getJSONObject(0).getString("id").trim(), new LabelItem_list_out_man(
                                        "",
                                        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("issue_qty").trim()))),
                                        jArray.getJSONObject(0).getString("issue_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(),
                                        "OK",
                                        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(),
                                        jArray.getJSONObject(0).getString("last_location_id").trim(),
                                        ""));

                                d_issue_qty = Double.parseDouble(jArray.getJSONObject(0).getString("issue_qty").trim());
                                label_id = jArray.getJSONObject(0).getString("id").trim();
                                Double sum = 0.0;
                                Double sum_net = 0.0;
                                Double sum_total_net = 0.0;

//                                    sum = d_plan_qty - d_issue_qty ;
                                sum_net = sum_total - d_plan_qty;
                                sum_total_net = Math.abs(sum_net) - d_issue_qty;

                                Double pp = Math.abs(sum_net);
                                Log.d(TAG, "pp: "+ pp);
                                Log.d(TAG, "sum_net: " + sum_net +"= sum_total"+sum_total +" - d_plan_qty "+ d_plan_qty);
                                Log.d(TAG, "sum_total_net: "+sum_total_net +" Math.abs(sum_net) - "+Math.abs(sum_net)+" d_issue_qty "+ d_issue_qty +") - d_issue_qty" +d_issue_qty);
                                Log.d(TAG, "sum_total_net: " + sum_total_net );

                                if (pp < d_issue_qty) {
                                    qty_new = d_issue_qty - Math.abs(pp);
                                    String st_sum =  Double.toString(Math.abs(pp));
//                                        String s_qty_new = Math.abs(qty_new.toString());

                                    if (map_label.containsKey(label_id)) {
                                        LabelItem_list_out_man item = map_label.get(label_id);
                                        item.setIssue_qty(st_sum);
                                        map_label.put(label_id, item);
                                    }
                                    Log.d(TAG, "Label_Inquiry: qty_new " + qty_new + " = sum_total " + sum_total + " - d_issue_qty " + d_issue_qty);
                                }else{



                                }

                                str_part_no = jArray.getJSONObject(0).getString("lbl_part_no").trim();
                                str_part_name = jArray.getJSONObject(0).getString("lbl_part_name").trim();
                                str_lot_no = jArray.getJSONObject(0).getString("lot_no").trim();
                                str_rank = jArray.getJSONObject(0).getString("lbl_rank").trim();
                                Log.d(getString(R.string.tag), "RANK: " + str_rank);
                                if (str_rank.trim().equals("A") || str_rank.trim().equals("B")) {
                                    str_inspection_flg = "1";
                                } else {
                                    str_inspection_flg = "0";
                                }
                                Log.d(getString(R.string.tag), "str_inspection_flg: " + str_inspection_flg);

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


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

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

    private void View_data() {
        list_label.clear();
        sum_total = Double.valueOf(0);
        int no = 0;
        Log.d(getString(R.string.tag),"mapItem"+ String.valueOf(map_label.size()));
        for (String key : map_label.keySet()){
            LabelItem_list_out_man item = map_label.get(key);
            list_label.add(new LabelItem_list_out_man(
                    String.valueOf(no+1),
                    item.getLabel_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(),
                    item.getStatus(),
                    item.getLbl_supplier_id(),
                    item.getLbl_supplier(),
                    item.getLbl_ng(),
                    item.getStatus_label(),
                    item.getLast_location_id(),
                    item.getLabel_id_new()));

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

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

        if (map_label.size() == 0){
            btn_confirm.setEnabled(false);
            btn_confirm.setBackgroundResource(R.drawable.button_background_gray);
            btn_clear.setEnabled(false);
            btn_clear.setBackgroundResource(R.drawable.button_background_gray);
        }else {
            btn_confirm.setEnabled(true);
            btn_confirm.setBackgroundResource(R.drawable.button_background_blue);
            btn_clear.setEnabled(true);
            btn_clear.setBackgroundResource(R.drawable.button_background_yellow);
        }
        txt_total.setText(String.valueOf(decimalFormat.format(Math.round(sum_total))+"/"+Math.round(d_plan_qty)));
        txt_part_name.setText(str_part_name);
        txt_part_no.setText(str_part_no);
        if (map_label.size() == 0){
            txt_part_no.setText("");
            txt_part_name.setText("");
            str_part_no = "";
            str_part_name = "";
            str_lot_no = "";
        }

    }

    private void Confirm_Outbound() {
        Log.d(getString(R.string.tag),"Confirm_Outbound "+ str_mode+"/"+str_inspection_flg);
        try {
            JSONObject json = new JSONObject();
            Map<String, String> jsonParams = new HashMap<>();//sample data
            json.put("cmd", "OUTBOUND/MANUAL/DETAIL/CONFIRM");

            JSONArray jsonArray = new JSONArray();
            for (String key : map_label.keySet()){
                LabelItem_list_out_man item = map_label.get(key);
                jsonParams.put("item_id", txt_part_no.getText().toString().trim());
                jsonParams.put("item_name", txt_part_name.getText().toString().trim());
                jsonParams.put("lot_no", item.getLot_no().trim());

                jsonParams.put("inspection_flg", str_inspection_flg);
                jsonParams.put("status", "2");
                jsonParams.put("slip_divide", "4");
                jsonParams.put("create_user_id", Settings.getLoginUser().getId());

                jsonParams.put("qty",item.getIssue_stock_qty());
                jsonParams.put("package_qty",item.getIssue_stock_qty());
                jsonParams.put("location_id", item.getLast_location_id());
                jsonParams.put("location_name", "");
                jsonParams.put("supplier_id", item.getLbl_supplier_id());
                jsonParams.put("supplier_name", item.getLbl_supplier());
                jsonParams.put("package_id", item.getUnit());
                jsonParams.put("unit_qty", item.getControl_unit());
                jsonParams.put("label_id", item.getLabel_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){
                            //SUCCESS

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

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

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

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

                case P3:
                    b_confirm = false;
                    map_label.clear();
                    View_data();
                    break;

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

        return super.onKeyUp(keyCode, event);
    }
    private void Prepare_Lbael() {
        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(qty_new))));
            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(OutboundManual_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();
                                String issue_qty = list.getQty().trim();
                                Log.d(getString(R.string.tag), "Key_map: " + Key_map + "label_id_new " + label_id_new);
                                Log.d(getString(R.string.tag), "Key_map: " + Key_map + "label_id " + label_id);
                                for (String key : map_label.keySet()){
                                    LabelItem_list_out_man item = map_label.get(key);
                                    if (map_label.containsKey(label_id)) {
                                        map_label_repck.put(list.getId() , new LabelItem_list_out_man(
                                                "",
                                                label_id,
                                                item.getOrder_no(),
                                                item.getPart_no(),
                                                item.getPart_name(),
                                                item.getDwg_no(),
                                                item.getLot_no(),
                                                issue_qty,
                                                item.getRank(),
                                                item.getIssue_stock_qty(),
                                                item.getBox_no(),
                                                item.getUnit(),
                                                item.getControl_unit(),
                                                item.getStatus(),
                                                item.getLbl_supplier_id(),
                                                item.getLbl_supplier(),
                                                item.getLbl_ng(),
                                                item.getStatus_label(),
                                                item.getLast_location_id(),
                                                label_id_new
                                        ));

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

                            }


                            //check printer
                            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")){
                                    new SweetAlertDialog(OutboundManual_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                            .setTitleText("WARNING")
                                            .setContentText("Please setting printer")
                                            .show();
                                }else {
                                    Command_Print();
                                }
                            }
                        }
                    }catch (JSONException e) {
                        new SweetAlertDialog(OutboundManual_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

        }catch (JSONException e) {
            new SweetAlertDialog(OutboundManual_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(OutboundManual_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_list_out_man 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){
                            SendInbound();


                        }else {
                            Unblock_button();
                            String error = jsonObject.getString("error");
                            new SweetAlertDialog(OutboundManual_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(error)
                                    .show();
                        }
                    }catch (JSONException e) {
                        Unblock_button();
                        new SweetAlertDialog(OutboundManual_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

        }catch (JSONException e) {
            Unblock_button();
            new SweetAlertDialog(OutboundManual_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(OutboundManual_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 SendInbound() {
        Log.d(getString(R.string.tag),"SendInbound "+ str_mode+"/"+str_inspection_flg);
        Log.d(TAG, "SendInbound: map_label_repck" + map_label_repck.size());
        calendar = Calendar.getInstance();
        calendar = (Calendar) calendar.clone();
        String dt_to_server = date_time_fm.format(calendar.getTime());
        Log.d(getString(R.string.tag), "dt_to_server : " + dt_to_server);

        try {
            JSONObject json = new JSONObject();
            Map<String, String> jsonParams = new HashMap<>();//sample data
            json.put("cmd", "INBOUND/SCHEDULE/DETAIL/CONFIRM");
            JSONArray jsonArray = new JSONArray();
            for (String key : map_label_repck.keySet()){
                LabelItem_list_out_man 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.getIssue_qty());
                jsonParams.put("qty", item.getIssue_qty());
                jsonParams.put("location_id", item.getLast_location_id());
                jsonParams.put("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){
                            //SUCCESS
                            SendOutbound_Re();
                            Unblock_button();
                        }else {
                            Unblock_button();
                            String error = jsonObject.getString("error");
                            new SweetAlertDialog(OutboundManual_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(error)
                                    .show();
                        }

                    }catch (JSONException e) {
                        Unblock_button();
                        new SweetAlertDialog(OutboundManual_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        }catch (Exception e) {
            Unblock_button();
            new SweetAlertDialog(OutboundManual_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }
    public void Check_In_out(){
        if (Settings.getPrinter().trim().equals("")||Settings.getPrinter().trim().equals("null")){
            new SweetAlertDialog(OutboundManual_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("WARNING")
                    .setContentText("Please setting printer")
                    .show();
        }else {
            if(qty_new > 0){
                Confirm_Outbound();
                Prepare_Lbael();

            }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_list_out_man 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.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(OutboundManual_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(OutboundManual_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText(e.getMessage())
                    .show();
        }
    }

    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_list_out_man 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.getIssue_qty());
                    jsonParams.put("qty", item.getIssue_qty());
                    jsonParams.put("location_id", item.getLast_location_id().trim());

                    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(OutboundManual_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(error)
                                    .show();

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

}