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.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.constraintlayout.widget.ConstraintLayout;
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_qc_Adapter;
import com.tomas.ht_mast.ListData.ItemFifo_list;
import com.tomas.ht_mast.ListData.LabelItem_qc_list;
import com.tomas.ht_mast.ListData.Location_list;
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 QCCheck_Activity extends Scanner implements View.OnClickListener, ClickRowItemNg {

    TextView txt_user, txt_device, txt_date, txt_part_no, txt_part_name, txt_total, txt_location, txt_box_no, edit_total_good, txt_totalng, txt_order_no;
    EditText  edit_total_ng ;
    Button btn_clear, btn_confirm, btn_ok, btn_reject;
    RecyclerView view_data;
    Bundle bundle;
    Calendar calendar;
    boolean b_confirm;
    SimpleDateFormat date, date_time_fm;
    List<Integer> sending_ticket;
    DecimalFormat decimalFormat, decimalFormat_commar;
    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,keyitem,label_id,label_id_old, label_id_new, ref_id, str_warehouse,str_unit
            ,str_lb_part_no ,str_control_unit, str_lbl_unit;
    Map<String, LabelItem_qc_list> map_label;
    List<LabelItem_qc_list> list_label;
    Double sum_total = 0.0, f_plan_qty = 0.0, f_act_qty =0.0, isuse_qty =0.0,total_net = 0.0, act_stock_qty = 0.0;
    ItemLabel_qc_Adapter label_adapter;

    ConstraintLayout layout_ng;
    Integer LABEL_QTY, PRINT_TIMES;
    List<Payload_list> payload_list;
    AlertProgress alert;
    private volatile boolean stopThread = true;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_qccheck);
        default_view = (EditText) findViewById(R.id.txt_label_issue_tmp);
        alert = new AlertProgress(QCCheck_Activity.this);
        layout_ng = (ConstraintLayout)findViewById(R.id.layout_alert);
        calendar = Calendar.getInstance();

        date_time_fm = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        date = new SimpleDateFormat("dd/MM/yyyy");
        str_today = date.format(calendar.getTime());

        sending_ticket = new ArrayList<>();
        sending_ticket.add(0,1);//for send outbound
        sending_ticket.add(1,1);//for sent inbound

        map_label = new LinkedHashMap<>();
        list_label = new ArrayList<LabelItem_qc_list>();
        stopThread = true;
        decimalFormat = new DecimalFormat("##0.00");

        b_confirm = false;
        decimalFormat_commar = new DecimalFormat("#,#00");
        sum_total = Double.valueOf(0);
        payload_list = new ArrayList<Payload_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());
        txt_date = (TextView) findViewById(R.id.txt_date);
        txt_date.setText(str_today);

        txt_part_no = (TextView) findViewById(R.id.txt_part_no);
        txt_part_name = (TextView) findViewById(R.id.txt_part_name);
        txt_total = (TextView) findViewById(R.id.txt_total);
        txt_location = (TextView) findViewById(R.id.txt_location);
        txt_order_no = (TextView)findViewById(R.id.txt_order_no);

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

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

        txt_box_no = (TextView) findViewById(R.id.txt_box_no);
        txt_totalng = (TextView) findViewById(R.id.txt_total_issue);
        edit_total_good = (TextView) findViewById(R.id.txt_total_good);
        edit_total_ng = (EditText) findViewById(R.id.txt_total_ng);

        bundle = getIntent().getExtras();
        str_mode = Settings.getActionType().toString();
        Log.d(getString(R.string.tag), "str_mode:" + str_mode);
        if (str_mode.trim().equals(ActionType.Type.QC_SCHEDULE.toString())) {
            str_sch_id = bundle.getString("schedule_id");
            str_order = bundle.getString("order_no");
            str_part_no = bundle.getString("part_no");
            str_part_name = bundle.getString("part_name");
            str_rank = bundle.getString("rank");
            str_location = bundle.getString("location");
            str_plan_qty = bundle.getString("plan_qty");
            str_act_qty = bundle.getString("act_qty");
            str_inspection_flg = bundle.getString("inspection_flg");
            str_supplier_name = bundle.getString("supplier_name");
            str_supplier_id = bundle.getString("supplier_id");
            ref_id = bundle.getString("ref_id");
            str_warehouse = bundle.getString("warehouse");
            str_unit = bundle.getString("unit");

            f_plan_qty = Double.parseDouble(str_plan_qty);
            f_act_qty = Double.parseDouble(str_act_qty);

            if (str_location.trim().equals("")){
                txt_location.setBackgroundResource(R.drawable.button_background_yellow);
            }else {
                txt_location.setHint(str_location);
            }

            txt_location.setHint(str_location);
            txt_part_no.setText(str_part_no);
            txt_part_name.setText(str_part_name);
            txt_order_no.setText(str_order);
            txt_total.setText(String.valueOf( decimalFormat_commar.format(Math.round(f_act_qty)) +"/")+String.valueOf(decimalFormat_commar.format(Math.round(f_plan_qty))));
//            txt_total.setText( str_act_qty+"/"+str_plan_qty);

            if (bundle.getBoolean("scan") == true) {
                t_box = bundle.getString("t_box");
                try {
                    Log.d(getString(R.string.tag), "JSON Label:" + Settings.getJS_label_detail().getString("id").toString());
                    map_label.put(t_box, new LabelItem_qc_list(
                            "",
                            Settings.getJS_label_detail().getString("id").trim(),
                            Settings.getJS_label_detail().getString("lbl_order_no").trim(),
                            Settings.getJS_label_detail().getString("lbl_part_no").trim(),
                            Settings.getJS_label_detail().getString("lbl_part_name").trim(),
                            Settings.getJS_label_detail().getString("lbl_dwg_no").trim(),
                            Settings.getJS_label_detail().getString("lot_no").trim(),
                            Settings.getJS_label_detail().getString("issue_qty").trim(),
                            Settings.getJS_label_detail().getString("issue_stock_qty").trim(),
                            Settings.getJS_label_detail().getString("lbl_rank").trim(),
                            Settings.getJS_label_detail().getString("serial_no").trim(),
                            Settings.getJS_label_detail().getString("lbl_unit").trim(),
                            Settings.getJS_label_detail().getString("control_unit").trim(),
                            "OK",
                            Settings.getJS_label_detail().getString("lbl_supplier_id").trim(),
                            Settings.getJS_label_detail().getString("lbl_supplier").trim(),
                            Settings.getJS_label_detail().getString("lbl_ng").trim(),
                            Settings.getJS_label_detail().getString("status").trim(),
                            "0",
                            Settings.getJS_label_detail().getString("issue_qty").trim(),
                            Settings.getJS_label_detail().getString("last_location_id").trim(),
                            Settings.getJS_label_detail().getString("last_location_name").trim(),
                            "",
                            Settings.getJS_label_detail().getString("issue_stock_qty").trim()));
                    str_lot_no = Settings.getJS_label_detail().getString("lot_no").trim().toString();

                    View_data();
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
            }
        }else {
            txt_order_no.setBackgroundResource(R.drawable.button_background_gray);
        }
    }

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

            case R.id.btn_clear:
                map_label.clear();
                View_data();
                break;

            case R.id.btn_confirm:
                if (b_confirm == false) {
                    Block_button();
                    Check_condition();

                }
                break;

            case R.id.btn_ok:
                Sum_Ng();
                break;

            case R.id.btn_cancel:
                layout_ng.setVisibility(View.GONE);
                break;

            case  R.id.btn_reject:
                if(str_mode.trim().equals(ActionType.Type.QC_SCHEDULE.toString())){
                    AlertConfirmReject();
                }else{
                    SendOutbound_Rej();
                }
                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 (txt_location.getText().toString().equals("")){
            Unblock_button();
            new SweetAlertDialog(QCCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("WARNING")
                    .setContentText("Please scan location!")
                    .show();
        }else {
            if (str_mode.trim().equals(ActionType.Type.QC_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) {

                                    sDialog.dismiss();
                                    Unblock_button();
                                }
                            })
                            .setConfirmText("Yes")
                            .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                @Override
                                public void onClick(SweetAlertDialog sDialog) {
                                    sDialog.dismiss();
                                    //sent to save....
                                    SendOutbound();
                                    SendInbound();
                                }
                            })
                            .show();
                }else {
                    SendOutbound();
                    SendInbound();
                }

            } else {//MANUAL
                SendOutbound();
                SendInbound();
            }
        }
    }

    @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 == 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 if (tokens.length == 3){//scan location

                if (map_label.size() == 0){
                    new SweetAlertDialog(QCCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("WARNING")
                            .setContentText("Please scan label part no.!")
                            .show();
                    return;
                }

                String[] tokens_lo = data.split(getString(R.string.DELIMITER_SCAN_TOKEN),-1);
                Log.d(getString(R.string.tag), Arrays.deepToString(tokens_lo));
                l_location = tokens_lo[0].trim();
                l_part_no = tokens_lo[1].trim();

                if (Settings.getMap_location().containsKey(l_location)){
                    Location_list list = Settings.getMap_location().get(l_location);
                    if (!list.getQc_area().equals("1")){ //Qc_area location
                        Check_location_part();
                    }else{
                        new SweetAlertDialog(QCCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("WARNING")
                                .setContentText("Can't scan QC location !")
                                .show();
                        txt_location.setHint(str_location);
                        txt_location.setBackgroundResource(R.drawable.img_background_gray);
                    }
                }else{
                    new SweetAlertDialog(QCCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                            .setTitleText("WARNING")
                            .setContentText("Location not found!")
                            .show();
                }

            }else{
                new SweetAlertDialog(QCCheck_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() {
        Log.d(getString(R.string.tag), "Check_previous_label :" + str_mode+"="+t_qty);
        if (str_mode.trim().equals(ActionType.Type.QC_SCHEDULE.toString())) {//Qc Schedule
            Log.d(getString(R.string.tag), "str_mode :" + str_mode);

            if (str_part_no.trim().equals(t_part)) {//check part_no
                Log.d(getString(R.string.tag), "str_part_no :" + str_part_no+"="+t_part+"/"+map_label.size());

                if (map_label.size() > 0){
                    if (str_lot_no.trim().equals(t_lot_no)) {//check lot_no
                        Log.d(getString(R.string.tag), "lot_no :" + str_lot_no+"="+t_lot_no);

                        if (map_label.containsKey(t_box)) {//delete label
                            new SweetAlertDialog(QCCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("WARNING")
                                    .setContentText("This Box has been scanned.")
                                    .setCancelText("Delete")
                                    .showCancelButton(true)
                                    .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                        @Override
                                        public void onClick(SweetAlertDialog sDialog) {
                                            sDialog.dismiss();
                                            map_label.remove(t_box);
                                            Log.d(getString(R.string.tag), "delete size = " + map_label.size());
                                            View_data();
                                        }
                                    })
                                    .setConfirmText("Continue")
                                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                        @Override
                                        public void onClick(SweetAlertDialog sDialog) {
                                            sDialog.dismiss();
                                        }
                                    })
                                    .show();
                        } else {
                            str_lot_no = t_lot_no;
                            Log.d(getString(R.string.tag), "str_part_no :" + str_part_no+"/"+t_qty);

                            Double f_label_qty = Double.parseDouble(t_qty.replaceAll(",",""));
                            Double pre_total = sum_total+f_label_qty;//before add to map

                            if (str_warehouse.trim().equals("ETG")){//no check over plan
                                Label_Inquiry(t_order, t_part, t_lot_no, t_box);

                            }else {//check over plan
                                if (sum_total >= f_plan_qty || pre_total > f_plan_qty) { //check sum_total
                                    new SweetAlertDialog(QCCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                            .setTitleText("WARNING")
                                            .setContentText("The planned quantity has been exceeded")
                                            .show();
                                } else {
                                    Label_Inquiry(t_order, t_part, t_lot_no, t_box);
                                }
                            }
                        }
                    } else {
                        new SweetAlertDialog(QCCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("WARNING")
                                .setContentText("Lot number is different")
                                .show();
                    }
                }else {
                    str_lot_no = t_lot_no;
                    Log.d(getString(R.string.tag), "str_part_no :" + str_part_no);
                    Label_Inquiry(t_order, t_part, t_lot_no, t_box);
                }
            } else {
                new SweetAlertDialog(QCCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("WARNING")
                        .setContentText("Part No. does not match Plan")
                        .show();
            }
        }else {//Qc 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(QCCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("WARNING")
                                    .setContentText("This Box has been scanned.")
                                    .setCancelText("Delete")
                                    .showCancelButton(true)
                                    .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                                        @Override
                                        public void onClick(SweetAlertDialog sDialog) {
                                            sDialog.dismiss();
                                            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.dismiss();
                                        }
                                    })
                                    .show();

                        } else {
                            Label_Inquiry(t_order, t_part, t_lot_no, t_box);
                        }
                    }else {
                        new SweetAlertDialog(QCCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                .setTitleText("WARNING")
                                .setContentText("Lot number is different")
                                .show();
                    }
                }else {
                    new SweetAlertDialog(QCCheck_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(QCCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                    .setTitleText("WARNING")
                                    .setContentText("Label not found!")
                                    .show();
                        }else {
                            String status_label = jArray.getJSONObject(0).getString("status").trim();
                            if (status_label.trim().equals("5")){
                                Log.d(getString(R.string.tag), "serial box: " + t_box);


                                map_label.put(t_box, new LabelItem_qc_list(
                                        "",
                                        jArray.getJSONObject(0).getString("id").trim(),
                                        jArray.getJSONObject(0).getString("lbl_order_no").trim(),
                                        jArray.getJSONObject(0).getString("lbl_part_no").trim(),
                                        jArray.getJSONObject(0).getString("lbl_part_name").trim(),
                                        jArray.getJSONObject(0).getString("lbl_dwg_no").trim(),
                                        jArray.getJSONObject(0).getString("lot_no").trim(),
                                        String.valueOf(Math.round(Double.parseDouble(jArray.getJSONObject(0).getString("issue_qty").trim()))),
                                        jArray.getJSONObject(0).getString("issue_stock_qty").trim(),
                                        jArray.getJSONObject(0).getString("lbl_rank").trim(),
//                                        String.format("%4s", jArray.getJSONObject(0).getString("serial_no").trim()).replace(' ', '0'),
                                        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(),
                                        "0",
                                        jArray.getJSONObject(0).getString("issue_qty").trim(),
                                        jArray.getJSONObject(0).getString("last_location_id").trim()=="null"?"":jArray.getJSONObject(0).getString("last_location_id"),
                                        jArray.getJSONObject(0).getString("last_location_name").trim()=="null"?"":jArray.getJSONObject(0).getString("last_location_name"),
                                        "",
                                        jArray.getJSONObject(0).getString("issue_stock_qty").trim()));

                                if (str_mode.trim().equals(ActionType.Type.QC_MANUAL.toString()) && map_label.size() == 1) {
                                    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();
                                    String location_fix = jArray.getJSONObject(0).getString("last_location_id").trim()=="null"?"":jArray.getJSONObject(0).getString("last_location_id");
                                    txt_location.setHint(str_location);
                                    if (location_fix.trim().equals("")){
                                        txt_location.setBackgroundResource(R.drawable.button_background_yellow);
                                    }else {
                                        txt_location.setBackgroundResource(R.drawable.img_background_gray);
                                    }

                                    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(QCCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                        .setTitleText("WARNING")
                                        .setContentText("Invalid Label!")
                                        .show();
                            }
                        }
                    }catch (JSONException e) {
                        new SweetAlertDialog(QCCheck_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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

    private void Check_location_part() {
        if (l_part_no.trim().equals("")){//label location part_no == "";
            txt_location.setText(l_location);
            txt_location.setBackgroundResource(R.drawable.button_background_green);
        }else{//check math part

            String[] tokens_lo_part = str_part_no.split(getString(R.string.DELIMITER_SCAN_TOKEN_PART),-1);
            Log.d(getString(R.string.tag), Arrays.deepToString(tokens_lo_part));
            String l_location_p = tokens_lo_part[1].trim();

            Log.e(getString(R.string.tag), "part label location: " + l_location_p);

//            if (str_part_no.trim().equals(l_part_no)){
            if (l_location_p.trim().equals(l_part_no)){
                txt_location.setText(l_location);
                txt_location.setBackgroundResource(R.drawable.button_background_green);

            }else {
//                new SweetAlertDialog(QCCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
//                        .setTitleText("WARNING")
//                        .setContentText("Are you sure about the overflow location")
//                        .setCancelText("No")
//                        .showCancelButton(true)
//                        .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
//                            @Override
//                            public void onClick(SweetAlertDialog sDialog) {
//                                sDialog.dismiss();
//                                txt_location.setHint(str_location);
//                                txt_location.setBackgroundResource(R.drawable.img_background_gray);
//                            }
//                        })
//                        .setConfirmText("Yes")
//                        .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
//                            @Override
//                            public void onClick(SweetAlertDialog sDialog) {
//                                sDialog.dismiss();
//                                txt_location.setText(l_location);
//                                txt_location.setBackgroundResource(R.drawable.button_background_green);
//                            }
//                        })
                new SweetAlertDialog(QCCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                        .setTitleText("WARNING")
                        .setContentText("Unable to change location")
                        .setCancelText("ok")
                        .showCancelButton(true)
                        .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                            @Override
                            public void onClick(SweetAlertDialog sDialog) {
                                sDialog.dismiss();
                                txt_location.setHint(str_location);
                                txt_location.setBackgroundResource(R.drawable.img_background_gray);
                            }
                        })
                        .show();
            }
        }

        if (Settings.getMap_location().containsKey(txt_location.getText().toString().trim())){
            Location_list list = Settings.getMap_location().get(txt_location.getText().toString().trim());
            str_location_name = list.getName();
        }
    }

    private void View_data() {
        b_confirm = false;
        list_label.clear();
//        txt_location.setText("");
//        txt_location.setBackgroundResource(R.drawable.img_background_gray);
        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()){
            no = (no + 1);
            LabelItem_qc_list item = map_label.get(key);
            list_label.add(new LabelItem_qc_list(
                    String.valueOf(no),
                    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.getNg_qty(),
                    item.getLabel_qty(),
                    item.getLast_location_id(),
                    item.getLast_location_name(),
                    item.getLabel_id_new(),
                    item.getStock_new_qty()));

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

        label_adapter = new ItemLabel_qc_Adapter(list_label, this,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);
            btn_reject.setEnabled(false);
            btn_reject.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);
            btn_reject.setEnabled(false);
            btn_reject.setBackgroundResource(R.drawable.button_background_orange);
        }

        if (str_mode.trim().equals(ActionType.Type.QC_SCHEDULE.toString())) {//Inbound Schedule
            //+act_qty
            Log.d(getString(R.string.tag), "sum_total : "+sum_total+"+"+f_act_qty);
            sum_total = (sum_total + f_act_qty);
            Log.d(getString(R.string.tag), "sum_total = "+sum_total);
            txt_total.setText(decimalFormat_commar.format(Math.round(sum_total)  )+ "/" + decimalFormat_commar.format(Math.round(f_plan_qty)));
        }else {
            txt_total.setText(String.valueOf(decimalFormat_commar.format(Math.round(sum_total))));
            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 SendOutbound() {
        Log.d(getString(R.string.tag),"SendOutbound "+ str_mode+"/"+str_inspection_flg);
        Log.d(getString(R.string.tag), "Outbound sending_ticket: " + sending_ticket.get(0));
        if (sending_ticket.get(0) == 0) {
            return;
        }

        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_qc_list item = map_label.get(key);
                jsonParams.put("item_id", item.getPart_no().trim());
                jsonParams.put("item_name", item.getPart_name().trim());
                jsonParams.put("lot_no", item.getLot_no().trim());
                jsonParams.put("package_id", item.getUnit().trim());
                jsonParams.put("unit_qty",  item.getControl_unit().trim());
                jsonParams.put("package_qty", item.getStock_new_qty());
                jsonParams.put("qty", item.getStock_new_qty());
                jsonParams.put("location_id", item.getLast_location_id().trim());
                if(item.getLast_location_name().trim().equals("null")){
                    jsonParams.put("location_name", "");
                }else{
                    jsonParams.put("location_name", item.getLast_location_name());
                }
                jsonParams.put("label_id", item.getLabel_id());
                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.getNg_qty());
                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){
                            sending_ticket.set(0,0);
                            Log.d(getString(R.string.tag), "Outbound sending_ticket: " + sending_ticket.get(0));
                            //SUCCESS
//                            if (str_mode.trim().equals(ActionType.Type.QC_MANUAL.toString())) {
//                                txt_part_name.setText("");
//                                txt_part_no.setText("");
//                                txt_location.setText("");
//                                txt_location.setBackgroundResource(R.drawable.img_background_gray);
//                                txt_total.setText("0");
//
//                                map_label.clear();
//                                View_data();
//                            }else {
                            finish();
//                            }
                        }else {
                            Unblock_button();
                            String error = jsonObject.getString("error");
                            new SweetAlertDialog(QCCheck_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(error)
                                    .show();

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

    private void SendInbound() {
        Log.d(getString(R.string.tag),"SendInbound "+ str_mode+"/"+str_inspection_flg);
        Log.d(getString(R.string.tag), "Inbound sending_ticket: " + sending_ticket.get(0));
        if (sending_ticket.get(1) == 0) {
            return;
        }

        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.keySet()){
                LabelItem_qc_list item = map_label.get(key);
                jsonParams.put("item_id", item.getPart_no().trim());
                jsonParams.put("item_name", item.getPart_name().trim());
                jsonParams.put("lot_no", item.getLot_no().trim());
                if (str_mode.trim().equals(ActionType.Type.QC_SCHEDULE.toString())) {
                    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.getStock_new_qty());
                jsonParams.put("qty", item.getStock_new_qty());
                jsonParams.put("location_id", txt_location.getText().toString().trim());
                jsonParams.put("location_name", item.getLast_location_name().trim().equals("null") ? "" : item.getLast_location_name().trim());
                if( item.getNg_qty().trim().equals("0")){
                    jsonParams.put("label_id", item.getLabel_id());
                }else{
                    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.getNg_qty());
                jsonParams.put("supplier_id", item.getLbl_supplier_id());
                jsonParams.put("supplier_name", item.getLbl_supplier());
                jsonParams.put("inspection_dt", dt_to_server);
                jsonParams.put("inspection_user_id", Settings.getLoginUser().getId());
                jsonParams.put("ng_qc_user_id", Settings.getLoginUser().getId());

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

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

                        if (status.trim().equals("success") && affected_rows > 0){
                            sending_ticket.set(1,0);
                            Log.d(getString(R.string.tag), "Inbound sending_ticket: " + sending_ticket.get(1));
                            //SUCCESS
//                            if (str_mode.trim().equals(ActionType.Type.QC_MANUAL.toString())) {
//                                new SweetAlertDialog(QCCheck_Activity.this, SweetAlertDialog.SUCCESS_TYPE)
//                                        .setTitleText("SUCCESS")
//                                        .setContentText("Insert data completed")
//                                        .show();
//                                txt_part_name.setText("");
//                                txt_part_no.setText("");
//                                txt_location.setText("");
//                                txt_location.setBackgroundResource(R.drawable.img_background_gray);
//                                txt_total.setText("0");
//                                map_label.clear();
//                                View_data();
//                            }else {
                            finish();
//                            }
                            Unblock_button();
                        }else {
                            Unblock_button();
                            String error = jsonObject.getString("error");
                            new SweetAlertDialog(QCCheck_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(error)
                                    .show();
                        }

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



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


    @Override
    public void onClickRow(String id, String qty,
                           String box, String ng_qty, String isus_qty, String lb_part_no,String control_unit,
                           String lbl_unit) {

        Log.d(getString(R.string.tag), "SelectionItemRow :" + id + "|" + qty + "|"
                + box + "|");

        txt_box_no.setText(box);
        txt_totalng.setText(decimalFormat_commar.format(Double.parseDouble(isus_qty)));
        edit_total_good.setText(qty);
        edit_total_ng.setText(ng_qty);
        isuse_qty = new Double(isus_qty);
        label_id = id;
        layout_ng.setVisibility(View.VISIBLE);
        str_lb_part_no = lb_part_no;
        str_control_unit = control_unit;
        str_lbl_unit = lbl_unit;

    }

    public void Sum_Ng(){
        total_net = Double.valueOf(0);
        Double total_issu = isuse_qty;
//       Integer total_good= new Integer(edit_total_good.getText().toString()).intValue();
        Double total_ng = Double.parseDouble(edit_total_ng.getText().toString());
        total_net = total_issu - total_ng;
        Log.d(TAG, "Sum_Ng:  total_issu  =" + total_issu + " total_ng = "+ total_ng );

        //convert unit qty
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "conversion-unit");
            json.put("parts_no", str_lb_part_no);
            json.put("qty",  total_net);
            json.put("from_unit", str_unit);
            json.put("to_unit", str_control_unit);

            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/packing_standard_master.php",
                    json.toString()) {
                @Override
                protected void onFinished(String response, int resp_code) {
                    try{
                        JSONArray jArray = new JSONArray(response);
                        Log.d(getString(R.string.tag), "response: " + response);
                        if (jArray.length() == 0){
                            new SweetAlertDialog(QCCheck_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText("Not found packing standard")
                                    .show();
                            return;
                        }else {
                            act_stock_qty = jArray.getJSONObject(0).getDouble("qty");//ใช้ตัวนี้ไป out
                            Log.d(getString(R.string.tag), "act_stock_qty: " + act_stock_qty);

                        }
                    }catch (JSONException e) {
                        new SweetAlertDialog(QCCheck_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();
        }catch (JSONException e){
            e.printStackTrace();
        }
        layout_ng.setVisibility(View.GONE);
        String Key_map = txt_box_no.getText().toString();
        Log.d(TAG, "Sum_Ng:  total_net  =" + total_net);
        if (map_label.containsKey(Key_map)) {
            LabelItem_qc_list item = map_label.get(Key_map);
            Log.d(getString(R.string.tag), "containsKey: " + item.getLabel_id());

//            for(String key : map_label.keySet()) {
//                LabelItem_qc_list item2 = map_label.get(key);
//                    keyitem = key;
//                Log.d(getString(R.string.tag), "keyitem: " + keyitem);

//                if(Key_map.trim().equals(keyitem)){
            item.setNg_qty(total_ng.toString());
            item.setLabel_qty(total_net.toString());
            item.setStock_new_qty(act_stock_qty.toString());

            map_label.put(Key_map, item);
            Log.d(TAG, "Sum_Ng: " +map_label.get(Key_map).getNg_qty().toString());
            Prepare_Label();
//                }
//            }
        }else{
            new SweetAlertDialog(QCCheck_Activity.this, SweetAlertDialog.ERROR_TYPE)
                    .setTitleText("ERROR")
                    .setContentText("not found label")
                    .show();
        }
    }

    private void Prepare_Label() {
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "QC/LABEL/PRINT/PREPARE");
            json.put("ref_label_id", label_id);
            json.put("new_qty", String.valueOf(decimalFormat.format(total_net)));
            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(QCCheck_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(
                                        jArray.getJSONObject(i).getString("id"),
                                        scrap_flg,
                                        jArray.getJSONObject(i).getString("payload"),
                                        jArray.getJSONObject(i).getString("issue_qty")));
                            }

                            for (int i = 0; i < payload_list.size(); i++){
                                Payload_list list = payload_list.get(i);
                                String Key_map = txt_box_no.getText().toString();
//                                String Key_map = label_id;
                                String label_id_new = list.getId().trim();
                                Log.d(getString(R.string.tag), "Key_map: " + Key_map + "label_id "+ label_id_new);

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

                                    for(String key : map_label.keySet()) {
                                        LabelItem_qc_list item2 = map_label.get(key);
                                        keyitem = key;
                                        if(Key_map.trim().equals(keyitem)){
                                            item.setLabel_id_new(label_id_new.trim());
                                            map_label.put(Key_map, item);
                                            label_id_old = Key_map;

                                            View_data();
                                        }
                                    }
                                }else{
                                    new SweetAlertDialog(QCCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                            .setTitleText("WARNING")
                                            .setContentText("Not found label on map_label")
                                            .show();
                                }
                            }

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

        }catch (JSONException e) {
            new SweetAlertDialog(QCCheck_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() {
        try {
            new SweetAlertDialog(QCCheck_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) {
                            sDialog.dismiss();
                            if (map_label.containsKey(label_id_old)) {
                                LabelItem_qc_list item = map_label.get(label_id_old);
                                for(String key : map_label.keySet()) {
                                    keyitem = key;
                                    if(label_id_old.trim().equals(keyitem)){
                                        item.setLabel_qty(String.valueOf(decimalFormat.format(isuse_qty)));
                                        item.setLabel_id(label_id_old);
                                        item.setNg_qty("0");
                                        map_label.put(label_id_old, item);

                                        View_data();

                                    }
                                }
                            }else{
                                new SweetAlertDialog(QCCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                                        .setTitleText("WARNING")
                                        .setContentText("Not found label on map_label")
                                        .show();
                            }

                        }
                    })
                    .setConfirmText("Yes")
                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sDialog) {
                            sDialog.dismiss();
                            Confirm_Label();
                        }
                    })
                    .show();

        }catch (WindowManager.BadTokenException e) {
            new SweetAlertDialog(QCCheck_Activity.this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("WARNING")
                    .setContentText("Please check the label status on Pegasus!")
                    .show();

        }
    }

    private void Confirm_Label() {
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "QC/LABEL/PRINT/CONFIRM");
            JSONArray jArray = new JSONArray();
            for (int i = 0; i < payload_list.size(); i++){
                Payload_list list = payload_list.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){
                            //SUCCESS
                            View_data();
                        }else {
                            String error = jsonObject.getString("error");
                            new SweetAlertDialog(QCCheck_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(error)
                                    .show();
                        }
                    }catch (JSONException e) {
                        new SweetAlertDialog(QCCheck_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

        }catch (JSONException e) {
            new SweetAlertDialog(QCCheck_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(3000);
                    Log.d("Thread.sleep2", "stopThread: " + stopThread);

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

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

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

        Payload_list payload_l = payload_list.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 {
                        alert.dismiss();
                        new SweetAlertDialog(QCCheck_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());
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyMapping.Down.getId() || keyCode == KeyMapping.P1.getId()
                || keyCode == KeyMapping.ENT.getId())
        {
            switch (KeyMapping.fromId(keyCode)) {
                case Down:
                    finish();
                    break;

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

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

        return super.onKeyUp(keyCode, event);
    }


    private void AlertConfirmReject() {
        new SweetAlertDialog(QCCheck_Activity.this, SweetAlertDialog.SUCCESS_TYPE)
                .setTitleText("SUCCESS")
                .setContentText("Do you want to reject this item?")
                .setCancelText("No")
                .showCancelButton(true)
                .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sDialog) {

                        sDialog.dismiss();
                    }
                })
                .setConfirmText("Yes")
                .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                    @Override
                    public void onClick(SweetAlertDialog sDialog) {
                        sDialog.dismiss();
                        Confirm_Reject();

                    }
                })
                .show();
    }


    private void Confirm_Reject() {
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "QC/SCHEDULE/REJECT/INBOUND/LABEL/INQUIRY");
            json.put("ref_id", ref_id);
            new AsyncHttpClient(getApplicationContext(),
                    Settings.getMgmtList().get("web_api") + "/ht_api.php",
                    json.toString()) {
                @Override
                protected void onFinished(String response, int resp_code) {
                    Log.d(getString(R.string.tag), "response: " + response);

                    try{
                        JSONArray jArray = new JSONArray(response);
                        for (int i = 0; i < jArray.length(); i++){
                            map_label.put(t_box, new LabelItem_qc_list(
                                    "",
                                    jArray.getJSONObject(i).getString("id").trim(),
                                    jArray.getJSONObject(i).getString("lbl_order_no").trim(),
                                    jArray.getJSONObject(i).getString("lbl_part_no").trim(),
                                    jArray.getJSONObject(i).getString("lbl_part_name").trim(),
                                    jArray.getJSONObject(i).getString("lbl_dwg_no").trim(),
                                    jArray.getJSONObject(i).getString("lot_no").trim(),
                                    String.valueOf(Math.round(Double.parseDouble(jArray.getJSONObject(i).getString("act_stock_qty").trim()))),
                                    jArray.getJSONObject(i).getString("act_stock_qty").trim(),
                                    jArray.getJSONObject(i).getString("lbl_rank").trim(),
                                    String.format("%4s", jArray.getJSONObject(i).getString("serial_no").trim()).replace(' ', '0'),
                                    jArray.getJSONObject(i).getString("lbl_unit").trim(),
                                    jArray.getJSONObject(i).getString("control_unit").trim(),
                                    "OK",
                                    jArray.getJSONObject(i).getString("lbl_supplier_id").trim(),
                                    jArray.getJSONObject(i).getString("lbl_supplier").trim(),
                                    jArray.getJSONObject(i).getString("lbl_ng").trim(),
                                    jArray.getJSONObject(i).getString("status").trim(),
                                    "0",
                                    jArray.getJSONObject(i).getString("issue_stock_qty").trim(),
                                    jArray.getJSONObject(i).getString("last_location_id").trim()=="null"?"":jArray.getJSONObject(0).getString("last_location_id"),
                                    jArray.getJSONObject(i).getString("last_location_name").trim()=="null"?"":jArray.getJSONObject(0).getString("last_location_name"),
                                    "",
                                    ""));
                        }

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

                    SendOutbound_Rej();
                }

            }.execute();

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

    private void SendOutbound_Rej() {
        Log.d(getString(R.string.tag),"SendOutbound_Rej "+ str_mode+"/"+str_inspection_flg);
        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_qc_list item = map_label.get(key);
                jsonParams.put("item_id", item.getPart_no().trim());
                jsonParams.put("item_name", item.getPart_name().trim());
                jsonParams.put("lot_no", item.getLot_no().trim());
                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_stock_qty());
                jsonParams.put("location_id", item.getLast_location_id().trim());
                if(item.getLast_location_name().trim().equals("null")){
                    jsonParams.put("location_name", "");
                }else{
                    jsonParams.put("location_name", item.getLast_location_name());
                }
                jsonParams.put("ref_sch_id", str_sch_id);
                jsonParams.put("label_id", item.getLabel_id());
                jsonParams.put("inspection_flg", "0");
                jsonParams.put("status", "2"); // OUT_STORE = 3;
                jsonParams.put("slip_divide", "4");
                jsonParams.put("create_user_id", Settings.getLoginUser().getId());
                jsonParams.put("ng", item.getNg_qty());
                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
                            Confirm_rej();
                        }else {
                            Unblock_button();
                            String error = jsonObject.getString("error");
                            new SweetAlertDialog(QCCheck_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(error)
                                    .show();

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

    private void Confirm_rej() {
        try {
            JSONObject json = new JSONObject();
            json.put("cmd", "QC/SCHEDULE/REJECT/CONFIRM");
            json.put("id", str_sch_id);
            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");
                        int affected_rows = jsonObject.getInt("affected_rows");

                        if (status.trim().equals("success") && affected_rows > 0){
                            //SUCCESS
//                            if (str_mode.trim().equals(ActionType.Type.QC_MANUAL.toString())) {
//                                new SweetAlertDialog(QCCheck_Activity.this, SweetAlertDialog.SUCCESS_TYPE)
//                                        .setTitleText("SUCCESS")
//                                        .setContentText("Reject data completed")
//                                        .show();
//                                txt_part_name.setText("");
//                                txt_part_no.setText("");
//                                txt_location.setText("");
//                                txt_location.setBackgroundResource(R.drawable.img_background_gray);
//                                txt_total.setText("0");
//                                map_label.clear();
//                                View_data();
//                            }else {
                            finish();
//                            }
                        }else {
                            String error = jsonObject.getString("error");
                            new SweetAlertDialog(QCCheck_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                    .setTitleText("ERROR")
                                    .setContentText(error)
                                    .show();
                        }
                    }catch (JSONException e) {
                        new SweetAlertDialog(QCCheck_Activity.this, SweetAlertDialog.ERROR_TYPE)
                                .setTitleText("ERROR")
                                .setContentText(e.getMessage())
                                .show();
                    }
                }
            }.execute();

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